Python JSON
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. Python has a built-in module called json to handle JSON data.
Import JSON Module
import json1. Convert Python to JSON (json.dumps())
import json
data = {"name": "Alice", "age": 30, "is_member": True}
json_data = json.dumps(data)
print(json_data)Output:
{"name": "Alice", "age": 30, "is_member": true}Explanation:dumps() converts a Python dictionary to a JSON string. Note that True becomes true in JSON.
2. Convert JSON to Python (json.loads())
import json
json_string = '{"name": "Alice", "age": 30, "is_member": true}'
python_data = json.loads(json_string)
print(python_data["name"])Output:
AliceExplanation:loads() parses a JSON string and returns a Python dictionary.
3. Write JSON to a File (json.dump())
import json
data = {"id": 101, "status": "active"}
with open("data.json", "w") as file:
json.dump(data, file)Explanation:dump() writes Python data to a .json file.
4. Read JSON from a File (json.load())
import json
with open("data.json", "r") as file:
data = json.load(file)
print(data)Output:
{'id': 101, 'status': 'active'}Explanation:load() reads a JSON file and converts it into Python objects.
5. Pretty Print JSON
import json
data = {"name": "Alice", "languages": ["Python", "JavaScript"]}
print(json.dumps(data, indent=4))Output:
{
"name": "Alice",
"languages": [
"Python",
"JavaScript"
]
}Explanation:
Use indent=4 to make JSON more readable.
6. JSON with Custom Sorting
import json
data = {"b": 2, "a": 1}
print(json.dumps(data, sort_keys=True))Output:
{"a": 1, "b": 2}Explanation:sort_keys=True sorts keys alphabetically.
7. JSON Encoding Rules (Python → JSON)
| Python | JSON |
|---|---|
dict | object |
list, tuple | array |
str | string |
int, float | number |
True | true |
False | false |
None | null |
8. Custom Serialization with Classes
class User:
def __init__(self, name, email):
self.name = name
self.email = email
def encode_user(obj):
if isinstance(obj, User):
return obj.__dict__
raise TypeError("Object is not serializable")
user = User("Bob", "bob@example.com")
print(json.dumps(user, default=encode_user))Output:
{"name": "Bob", "email": "bob@example.com"}Explanation:
Use default to convert non-serializable objects to dictionaries.