Introduction

JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data. It’s widely used in APIs, configuration files, and data storage. Python has a built-in json
module that makes handling JSON simple and efficient.
1. Importing the JSON Module
import json
2. Converting Python Objects to JSON (Serialization)
import json
person = {
"name": "Alice",
"age": 25,
"city": "Paris"
}
# Convert Python dict to JSON string
json_data = json.dumps(person)
print(json_data)
Output:
{"name": "Alice", "age": 25, "city": "Paris"}
3. Converting JSON to Python Objects (Deserialization)
json_str = '{"name": "Bob", "age": 30, "city": "London"}'
# Convert JSON string to Python dict
person_dict = json.loads(json_str)
print(person_dict["name"]) # Output: Bob
4. Working with JSON Files
Write JSON to File:
with open("data.json", "w") as f:
json.dump(person, f)
Read JSON from File:
with open("data.json", "r") as f:
data = json.load(f)
print(data)
5. Pretty Printing JSON
print(json.dumps(person, indent=4))
Output:
{
"name": "Alice",
"age": 25,
"city": "Paris"
}
6. Real-World Example: JSON from an API
import requests
import json
response = requests.get("https://api.github.com")
data = response.json()
print(data["current_user_url"])
✅ Summary
- Use the
json
module to serialize (dumps
,dump
) and deserialize (loads
,load
) JSON. - JSON is useful for APIs, configs, and data exchange.
- Supports reading/writing JSON files.
- Works seamlessly with third-party APIs.