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"]
}
📚 Python's json
Module
Python provides a built-in module named json
to handle JSON data.
import json
📥 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'>
📤 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)
📝 Pretty Printing JSON
You can format JSON output with indentation for better readability:
print(json.dumps(person, indent=2))
📁 Reading JSON from a File
with open('data.json', 'r') as file:
data = json.load(file)
print(data["name"])
💾 Writing JSON to a File
with open('output.json', 'w') as file:
json.dump(person, file, indent=4)
🔁 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)
✅ 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'])
🛠️ Summary
- Use
json.loads()
to parse JSON strings. - Use
json.dumps()
to create JSON strings from Python data. - Use
json.load()
andjson.dump()
to work with JSON files. - JSON is used widely in APIs, config files, and more.