π¦ Python Tutorial β JSON Module
Introduction π
The json module in Python allows you to encode and decode data in theJSON (JavaScript Object Notation) format β one of the most popular data formats for APIs, web services, config files, and data interchange.
Note
π‘ JSON = Lightweight, text-based, language-independent
π‘ Python provides easy conversion between JSON β Python objects
π‘ Python provides easy conversion between JSON β Python objects
1. Importing the JSON Module π§±
import_json.py
import json2. Converting Python β JSON (Serialization) π€
Using json.dumps()
dumps_example.py
import json
data = {
"name": "Sathish",
"age": 25,
"languages": ["Python", "Java"]
}
json_str = json.dumps(data)
print(json_str)β Converts Python dict β JSON string
Pretty Printing JSON
dumps_pretty.py
print(json.dumps(data, indent=4))3. Writing JSON to a File π
json_dump_file.py
with open("data.json", "w") as f:
json.dump(data, f, indent=4)β dump() writes JSON directly to a file
4. Converting JSON β Python (Deserialization) π₯
Using json.loads()
loads_example.py
json_str = '{"name":"Sathish","age":25}'
data = json.loads(json_str)
print(data["name"])Reading JSON from a File
json_load_file.py
with open("data.json", "r") as f:
data = json.load(f)
print(data)5. Data Conversion Table π
| Python | JSON |
|---|---|
| dict | object |
| list, tuple | array |
| str | string |
| int, float | number |
| True / False | true / false |
| None | null |
6. Handling Custom Objects π§©
custom_encoder.py
import json
class User:
def __init__(self, name, age):
self.name = name
self.age = age
def encode_user(obj):
if isinstance(obj, User):
return {"name": obj.name, "age": obj.age}
raise TypeError("Object not JSON serializable")
u = User("Sathish", 25)
print(json.dumps(u, default=encode_user))β Use default= to encode custom classes
7. JSON Decode Hooks πͺ
object_hook.py
json_str = '{"name":"Sathish","age":25}'
def to_user(d):
return User(d["name"], d["age"])
user = json.loads(json_str, object_hook=to_user)
print(user.name, user.age)β Converts JSON dict β custom class
8. Sorting Keys π
sort_keys.py
print(json.dumps(data, sort_keys=True, indent=4))β Useful for debugging, comparisons, logs
9. Ignoring Invalid Keys (skipkeys=True) π«
skipkeys_example.py
print(json.dumps({1: "one", "two": 2}, skipkeys=True))Note
β οΈ JSON keys must be strings. skipkeys=True silently ignores invalid keys.
10. Real-World Example β API Response Handling π
api_example.py
import json
response = '{"status":"ok","data":{"count":5}}'
parsed = json.loads(response)
print(parsed["data"]["count"])11. Real-World Example β Config File Loader βοΈ
config_loader.py
import json
with open("config.json") as f:
config = json.load(f)
print(config["database"]["host"])β JSON is commonly used for configuration
12. JSON Module Cheat Sheet π
| Function | Purpose |
|---|---|
| json.dumps() | Python β JSON string |
| json.dump() | Python β JSON file |
| json.loads() | JSON string β Python |
| json.load() | JSON file β Python |
| default= | Encode custom objects |
| object_hook= | Decode custom objects |
| sort_keys=True | Sort keys alphabetically |
Best Practices π‘
- β Always wrap file operations in with open()
- β Use JSON for API responses, configs, serialization
- β Use indent for readable output
- β Validate JSON before parsing to avoid errors
- β Use custom encoders for classes
Conclusion π
>>βJSON makes data portable β Python makes JSON effortless.β β¨
You now fully understand the JSON module! Want the next topic? Try Pickle, CSV, XML, YAML, REST APIs, or Dataclasses. Just tell me! π