Fundamentals 8 min read

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.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Using Python's json Module: Serialization, Deserialization, and Common Operations

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</code>
<code>data = {"name": "Alice", "age": 25, "city": "Beijing"}</code>
<code>json_str = json.dumps(data)</code>
<code>print(json_str)</code>
<code># Output: {"name": "Alice", "age": 25, "city": "Beijing"}

Example 2: Pretty‑print JSON with indentation

json_pretty = json.dumps(data, indent=4)</code>
<code>print(json_pretty)</code>
<code># Output:</code>
<code>{</code>
<code>    "name": "Alice",</code>
<code>    "age": 25,</code>
<code>    "city": "Beijing"</code>
<code>}

Example 3: Convert a JSON string to a dictionary

json_str = '{"name": "Bob", "age": 30}'</code>
<code>data_dict = json.loads(json_str)</code>
<code>print(data_dict["name"])</code>
<code># Output: Bob

Example 4: Write JSON to a file

with open("user.json", "w", encoding="utf-8") as f:</code>
<code>    json.dump(data, f, indent=2)</code>
<code>print("已写入 user.json")</code>
<code># File content:</code>
<code># {</code>
<code>#   "name": "Alice",</code>
<code>#   "age": 25,</code>
<code>#   "city": "Beijing"</code>
<code># }

Example 5: Read JSON data from a file

with open("user.json", "r", encoding="utf-8") as f:</code>
<code>    data = json.load(f)</code>
<code>print(data["city"])</code>
<code># Output: Beijing

Example 6: Preserve non‑ASCII characters (ensure_ascii=False)

data = {"城市": "上海", "人口": 24150000}</code>
<code>json_str = json.dumps(data, ensure_ascii=False)</code>
<code>print(json_str)</code>
<code># Output: {"城市": "上海", "人口": 24150000}

Example 7: Convert a list to a JSON array

fruits = ["apple", "banana", "cherry"]</code>
<code>json_list = json.dumps(fruits)</code>
<code>print(json_list)</code>
<code># Output: ["apple", "banana", "cherry"]

Example 8: Serialize nested structures

data = {"student": {"name": "Tom", "grades": [90, 85, 92]}}</code>
<code>json_str = json.dumps(data, indent=2)</code>
<code>print(json_str)</code>
<code># Output:</code>
<code># {</code>
<code>#   "student": {</code>
<code>#     "name": "Tom",</code>
<code>#     "grades": [90, 85, 92]</code>
<code>#   }</code>
<code># }

Example 9: Sort keys when dumping

data = {"c": 3, "a": 1, "b": 2}</code>
<code>json_sorted = json.dumps(data, sort_keys=True)</code>
<code>print(json_sorted)</code>
<code># Output: {"a": 1, "b": 2, "c": 3}

Example 10: Custom JSON encoder for non‑standard types (e.g., datetime)

from datetime import datetime</code>
<code>class CustomEncoder(json.JSONEncoder):</code>
<code>    def default(self, obj):</code>
<code>        if isinstance(obj, datetime):</code>
<code>            return obj.strftime("%Y-%m-%d %H:%M:%S")</code>
<code>        return super().default(obj)</code>
<code>now = datetime.now()</code>
<code>data = {"timestamp": now}</code>
<code>json_str = json.dumps(data, cls=CustomEncoder)</code>
<code>print(json_str)</code>
<code># 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):</code>
<code>    if isinstance(o, complex):</code>
<code>        return {"__complex__": True, "real": o.real, "imag": o.imag}</code>
<code>    return json.JSONEncoder.default(o)</code>
<code>c = complex(3, 4)</code>
<code>json_str = json.dumps({"value": c}, default=default)</code>
<code>print(json_str)</code>
<code># 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):</code>
<code>    try:</code>
<code>        json.loads(json_str)</code>
<code>        return True</code>
<code>    except ValueError:</code>
<code>        return False</code>
<code>print(is_valid_json('{"name": "John"}'))  # True</code>
<code>print(is_valid_json('{"name": John}'))      # False

Example 13: Merge multiple JSON objects

json1 = '{"name": "Alice"}'</code>
<code>json2 = '{"age": 25}'</code>
<code>dict1 = json.loads(json1)</code>
<code>dict2 = json.loads(json2)</code>
<code>merged = {**dict1, **dict2}</code>
<code>print(json.dumps(merged))</code>
<code># Output: {"name": "Alice", "age": 25}

Example 14: Fetch JSON response from a network request (requests + json)

import requests</code>
<code>response = requests.get("https://api.example.com/data")</code>
<code>data = response.json()  # automatically calls json.loads()</code>
<code>print(data.get("status"))

Example 15: Process multiple items in a JSON array

json_array = '[{"name": "A"}, {"name": "B"}, {"name": "C"}]'</code>
<code>items = json.loads(json_array)</code>
<code>for item in items:</code>
<code>    print(item['name'])</code>
<code># Output:</code>
<code># A</code>
<code># B</code>
<code># C

Summary

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonserializationJSONDeserializationdata handlingjson module
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.