Using Python's json Module: Serialization, Deserialization, and Common Operations
This article introduces Python's built‑in json module, explaining how to serialize Python objects to JSON strings and files, deserialize JSON back to Python, and demonstrates common tasks such as pretty‑printing, handling Unicode, working with lists and nested structures, custom encoders, and network responses.
Python's standard library provides the json module for converting between Python objects and JSON strings (serialization) and vice‑versa (deserialization). The module also supports reading from and writing to files.
Common functions include json.dumps() (object → JSON string), json.loads() (JSON string → object), json.dump() (object → file), and json.load() (file → object).
Example 1: Convert a dictionary to a JSON string
import json
data = {"name": "Alice", "age": 25, "city": "Beijing"}
json_str = json.dumps(data)
print(json_str)
# Output: {"name": "Alice", "age": 25, "city": "Beijing"}Example 2: Pretty‑print JSON with indentation
json_pretty = json.dumps(data, indent=4)
print(json_pretty)
# Output:
{
"name": "Alice",
"age": 25,
"city": "Beijing"
}Example 3: Convert a JSON string to a dictionary
json_str = '{"name": "Bob", "age": 30}'
data_dict = json.loads(json_str)
print(data_dict["name"])
# Output: BobExample 4: Write JSON to a file
with open("user.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
print("已写入 user.json")
# File content:
# {
# "name": "Alice",
# "age": 25,
# "city": "Beijing"
# }Example 5: Read JSON data from a file
with open("user.json", "r", encoding="utf-8") as f:
data = json.load(f)
print(data["city"])
# Output: BeijingExample 6: Preserve non‑ASCII characters (ensure_ascii=False)
data = {"城市": "上海", "人口": 24150000}
json_str = json.dumps(data, ensure_ascii=False)
print(json_str)
# Output: {"城市": "上海", "人口": 24150000}Example 7: Convert a list to a JSON array
fruits = ["apple", "banana", "cherry"]
json_list = json.dumps(fruits)
print(json_list)
# Output: ["apple", "banana", "cherry"]Example 8: Serialize nested structures
data = {"student": {"name": "Tom", "grades": [90, 85, 92]}}
json_str = json.dumps(data, indent=2)
print(json_str)
# Output:
# {
# "student": {
# "name": "Tom",
# "grades": [90, 85, 92]
# }
# }Example 9: Sort keys when dumping
data = {"c": 3, "a": 1, "b": 2}
json_sorted = json.dumps(data, sort_keys=True)
print(json_sorted)
# Output: {"a": 1, "b": 2, "c": 3}Example 10: Custom JSON encoder for non‑standard types (e.g., datetime)
from datetime import datetime
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S")
return super().default(obj)
now = datetime.now()
data = {"timestamp": now}
json_str = json.dumps(data, cls=CustomEncoder)
print(json_str)
# Output: {"timestamp": "2025-05-06 14:48:00"}Example 11: Use a default function to handle unserializable objects (e.g., complex numbers)
def default(o):
if isinstance(o, complex):
return {"__complex__": True, "real": o.real, "imag": o.imag}
return json.JSONEncoder.default(o)
c = complex(3, 4)
json_str = json.dumps({"value": c}, default=default)
print(json_str)
# Output: {"value": {"__complex__": true, "real": 3.0, "imag": 4.0}}Example 12: Validate whether a string is valid JSON
def is_valid_json(json_str):
try:
json.loads(json_str)
return True
except ValueError:
return False
print(is_valid_json('{"name": "John"}')) # True
print(is_valid_json('{"name": John}')) # FalseExample 13: Merge multiple JSON objects
json1 = '{"name": "Alice"}'
json2 = '{"age": 25}'
dict1 = json.loads(json1)
dict2 = json.loads(json2)
merged = {**dict1, **dict2}
print(json.dumps(merged))
# Output: {"name": "Alice", "age": 25}Example 14: Fetch JSON response from a network request (requests + json)
import requests
response = requests.get("https://api.example.com/data")
data = response.json() # automatically calls json.loads()
print(data.get("status"))Example 15: Process multiple items in a JSON array
json_array = '[{"name": "A"}, {"name": "B"}, {"name": "C"}]'
items = json.loads(json_array)
for item in items:
print(item['name'])
# Output:
# A
# B
# CSummary
The json module is a versatile tool for handling JSON data in Python, covering basic serialization/deserialization, file I/O, pretty‑printing, Unicode handling, custom encoding, validation, merging, and integration with web requests.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.