DEV Community

Cover image for Day 36/100: Working with JSON in Python
 Rahul Gupta
Rahul Gupta

Posted on

Day 36/100: Working with JSON in Python

Welcome to Day 36 of your Python learning journey!
Today, we dive into a real-world skill: working with JSON data in Python.
JSON (JavaScript Object Notation) is everywhereβ€”APIs, config files, databases, and web apps use it to store and exchange data.

Let’s learn how to read, write, parse, and manipulate JSON in Python with ease! 🧠


πŸ“¦ What is JSON?

JSON is a lightweight data format similar to Python dictionaries and lists.

Example JSON:

{
  "name": "Alice",
  "age": 30,
  "skills": ["Python", "Data Science"]
}
Enter fullscreen mode Exit fullscreen mode

πŸ“š Python's json Module

Python provides a built-in module named json to handle JSON data.

import json
Enter fullscreen mode Exit fullscreen mode

πŸ“₯ Converting JSON to Python (Deserialization)

You can load JSON strings into Python dictionaries using json.loads().

import json

json_str = '{"name": "Alice", "age": 30, "skills": ["Python", "Data Science"]}'
data = json.loads(json_str)

print(data["name"])  # Output: Alice
print(type(data))    # <class 'dict'>
Enter fullscreen mode Exit fullscreen mode

πŸ“€ Converting Python to JSON (Serialization)

You can convert Python objects (dict, list, etc.) into JSON strings using json.dumps().

person = {
    "name": "Bob",
    "age": 25,
    "skills": ["JavaScript", "React"]
}

json_data = json.dumps(person)
print(json_data)
Enter fullscreen mode Exit fullscreen mode

πŸ“ Pretty Printing JSON

You can format JSON output with indentation for better readability:

print(json.dumps(person, indent=2))
Enter fullscreen mode Exit fullscreen mode

πŸ“ Reading JSON from a File

with open('data.json', 'r') as file:
    data = json.load(file)

print(data["name"])
Enter fullscreen mode Exit fullscreen mode

πŸ’Ύ Writing JSON to a File

with open('output.json', 'w') as file:
    json.dump(person, file, indent=4)
Enter fullscreen mode Exit fullscreen mode

πŸ” JSON and Python Data Types

JSON Python
Object dict
Array list
String str
Number int/float
true/false True / False
null None

🧨 Handling Errors

When working with JSON, handle decoding errors using try-except.

try:
    data = json.loads('{"name": "Alice", "age": }')  # Invalid JSON
except json.JSONDecodeError as e:
    print("Error parsing JSON:", e)
Enter fullscreen mode Exit fullscreen mode

βœ… Practical Use Case: Fetching API Data

import requests
import json

response = requests.get("https://jsonplaceholder.typicode.com/users")
users = response.json()

for user in users:
    print(user['name'], '-', user['email'])
Enter fullscreen mode Exit fullscreen mode

πŸ› οΈ Summary

  • Use json.loads() to parse JSON strings.
  • Use json.dumps() to create JSON strings from Python data.
  • Use json.load() and json.dump() to work with JSON files.
  • JSON is used widely in APIs, config files, and more.

Top comments (0)