JSON (JavaScript Object Notation) is the standard lightweight data-interchange format. Python's json module translates JSON strings to Python primitives (and vice-versa).
flowchart LR
subgraph JSON Primitive
j_obj["object {}"]
j_arr["array []"]
j_str["string"]
j_num["number"]
j_bool["true/false"]
j_null["null"]
end
subgraph Python Type
p_dict["dict"]
p_list["list"]
p_str["str"]
p_num["int / float"]
p_bool["bool (True/False)"]
p_none["None"]
end
j_obj --> p_dict
j_arr --> p_list
j_str --> p_str
j_num --> p_num
j_bool --> p_bool
j_null --> p_none
json.dumps(obj): Serialize Python object to a JSON formatted str.json.loads(json_str): Deserialize JSON str to a Python object.json.dump(obj, file_obj): Serialize object directly to a file stream.json.load(file_obj): Deserialize object directly from a file stream.import json
from datetime import datetime
from typing import Any
class DatetimeEncoder(json.JSONEncoder):
"""Custom JSON Encoder supporting datetime objects."""
def default(self, obj: Any) -> Any:
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
def json_serialization_demo() -> None:
data = {
"user_id": 1024,
"username": "coder_dev",
"roles": ["developer", "admin"],
"active": True,
"created_at": datetime.now()
}
# Serialize using Custom Encoder
json_string = json.dumps(data, cls=DatetimeEncoder, indent=2)
print("Serialized JSON:
", json_string)
# Deserialize back
parsed = json.loads(json_string)
print(f"
Deserialized User: {parsed['username']} (Roles: {parsed['roles']})")
if __name__ == "__main__":
json_serialization_demo()
json.dumps((1, 2))), it converts to a JSON array [1, 2]. Deserializing it returns a Python list, not a tuple.{1: "a"}), json.dumps() converts them to string keys ({"1": "a"}).indent=2 for Human Readability: Use indent=2 during debugging or config file generation.Write a function save_json(filepath: str, data: dict) that safely writes a dictionary to a JSON file using json.dump() with 4-space indentation.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.