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 json module makes it easy to convert between Python objects and JSON strings.


Related Built-in Functions:object float bool dict list None int str

1. Python Objects <-> JSON Strings

▶ Example: Serializing to JSON String

▶ Try it Yourself

Output:

TEXT 📖 Display only
# Executed successfully

Output:

JSON
{
  "name": "Zhang San",
  "age": 25,
  "is_student": false,
  "scores": [85, 92, 78],
  "address": null
}

Tip: ensure_ascii=False is important: Without this parameter, non-ASCII characters are escaped to Unicode codes. Use it to preserve original characters. indent=2 formats the output for readability. In production, use indent=None to compress into a single line, saving bandwidth.



2. JSON String -> Python Objects (Deserialization)

▶ Example: Deserializing a JSON String

▶ Try it Yourself

Output:

TEXT 📖 Display only
# 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 Yourself

Output:

TEXT 📖 Display only
# Executed successfully

▶ Example: Data Persistence (Difficulty: Star-Star)

▶ Try it Yourself

Output:

TEXT 📖 Display only
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 Yourself

Output:

TEXT 📖 Display only
# Function defined successfully


5. Common Use Cases


Related Built-in Functions:object float bool dict list None int str

❓ FAQ

Q What's the difference between json.dumps() and json.dump()?
A 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.
Q What are the advantages of JSON over CSV?
A JSON supports nested structures (dicts within lists, lists within dicts), while CSV can only represent flat tables. JSON preserves data types automatically (numbers, booleans, null), while all CSV values are strings. JSON is more readable. The downside is that JSON files are usually larger than CSV.
Q What happens if ensure_ascii=False is not set?
A Chinese characters will be escaped into \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


📝 Exercises

  1. 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).

  2. Intermediate (Difficulty: Star-Star): Write two functions: save_contacts(contacts) and load_contacts(). Save a contact list (list of dicts) to contacts.json and auto-load on program start. Each contact has a name, phone, and email.

  3. 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).

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏