Python: JSON Data Processing
Last updated: 2026-09-22
JSON (JavaScript Object Notation) is the most common data exchange format on the web. Almost all Web APIs return JSON data. Python's
jsonmodule makes it easy to convert between Python objects and JSON strings.
1. Python Objects <-> JSON Strings
▶ Example: Serializing to JSON String
▶ Try it YourselfOutput:
# Executed successfully
Output:
{
"name": "Zhang San",
"age": 25,
"is_student": false,
"scores": [85, 92, 78],
"address": null
}
Tip:
ensure_ascii=Falseis important: Without this parameter, non-ASCII characters are escaped to Unicode codes. Use it to preserve original characters.indent=2formats the output for readability. In production, useindent=Noneto compress into a single line, saving bandwidth.
2. JSON String -> Python Objects (Deserialization)
▶ Example: Deserializing a JSON String
▶ Try it YourselfOutput:
# Executed successfully
(1) JSON Type to Python Type Mapping
| JSON | Python |
|---|---|
string |
str |
number |
int / float |
boolean |
bool |
null |
None |
array |
list |
object |
dict |
3. JSON File I/O
▶ Example: Reading and Writing JSON Files
▶ Try it YourselfOutput:
# Executed successfully
▶ Example: Data Persistence (Difficulty: Star-Star)
▶ Try it YourselfOutput:
No notes yet
4. Handling Complex Data Types
By default, the json module only supports basic types. Custom objects need manual conversion:
▶ Example: Custom Serialization
▶ Try it YourselfOutput:
# Function defined successfully
5. Common Use Cases
- Web API data: Send and receive JSON data when calling external APIs.
- Configuration files: Store configuration in JSON format — more flexible than INI.
- Data persistence: Save program data as JSON files — more structured than CSV (supports nesting).
- Data exchange: Transfer data between different languages and systems.
❓ FAQ
json.dumps() and json.dump()?dumps() returns a JSON string (s for string); dump() writes directly to a file object. Similarly, loads() parses from a string; load() reads from a file object. The 's' suffix indicates string.ensure_ascii=False is not set?\uXXXX format. Program functionality is unaffected — json.loads() will restore them automatically. However, for human readability, escaped content is completely unreadable. Add ensure_ascii=False when you need to view JSON files manually.📖 Summary
json.dumps()Python -> JSON string;json.loads()JSON string -> Pythonjson.dump()Python -> JSON file;json.load()JSON file -> Pythonensure_ascii=Falsepreserves non-ASCII characters;indent=2formats output- JSON type mapping:
object->dict,array->list,number->int/float,null->None - Custom types need a
defaultserialization function
📝 Exercises
-
Beginner (Difficulty: Star): Create a dictionary containing your name, age, and three hobbies (list). Use
json.dumps()to output a formatted JSON string (preserve characters, indent 2). -
Intermediate (Difficulty: Star-Star): Write two functions:
save_contacts(contacts)andload_contacts(). Save a contact list (list of dicts) tocontacts.jsonand auto-load on program start. Each contact has a name, phone, and email. -
Advanced (Difficulty: Star-Star-Star): Implement a "simple data exporter" using JSON. Given a student score list
students = [{"name": "Zhang San", "scores": {"Chinese": 85, "Math": 92}}], output as: 1) A formatted JSON file; 2) A compressed (no indent) JSON string; 3) A JSON string with sorted keys (sort_keys=True).