Fundamentals 6 min read

Python JSON Handling: Encoding, Decoding, File I/O, Pretty‑Printing, Sorting, Custom Types and Non‑ASCII Support

This tutorial demonstrates how to encode Python objects to JSON strings, decode JSON back to Python, read and write JSON files, pretty‑print and sort JSON output, handle special types with custom encoders, preserve key order, manage non‑ASCII characters, and process binary JSON data using the built‑in json module.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python JSON Handling: Encoding, Decoding, File I/O, Pretty‑Printing, Sorting, Custom Types and Non‑ASCII Support

1. Encode a Python object to a JSON string – Use json.dumps to serialize a dictionary and print the resulting JSON text.

import json
data = {"name": "Alice", "age": 30, "is_student": False}
json_data = json.dumps(data)
print("JSON string:", json_data)

2. Decode a JSON string back to a Python object – Apply json.loads on a JSON‑formatted string and display the reconstructed dictionary.

import json
json_str = '{"name": "Alice", "age": 30, "is_student": false}'
data = json.loads(json_str)
print("Python object:", data)

3. Write a Python object to a JSON file – Open a file in write mode and use json.dump to store the data.

import json
data = {"name": "Alice", "age": 30, "is_student": False}
with open("data.json", "w") as f:
    json.dump(data, f)
print("Data saved to file")

4. Read a JSON file into a Python object – Open the file in read mode and load its contents with json.load .

import json
with open("data.json", "r") as f:
    data = json.load(f)
print("Read data:", data)

5. Pretty‑print JSON data – Use json.dumps with the indent parameter to format the output.

import json
data = {"name": "Alice", "age": 30, "is_student": False, "skills": ["Python", "JavaScript", "C++"]}
pretty_json = json.dumps(data, indent=4)
print("Pretty JSON output:\n", pretty_json)

6. Sort JSON output keys – Set sort_keys=True in json.dumps to produce an alphabetically ordered JSON string.

import json
data = {"name": "Alice", "age": 30, "is_student": False, "skills": ["Python", "JavaScript", "C++"]}
sorted_json = json.dumps(data, indent=4, sort_keys=True)
print("Sorted JSON output:\n", sorted_json)

7. Handle special types with a custom encoder – Subclass json.JSONEncoder to convert unsupported objects (e.g., set ) to JSON‑serializable forms.

import json
class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        return json.JSONEncoder.default(self, obj)

data = {"name": "Alice", "age": 30, "is_student": False, "skills": set(["Python", "JavaScript", "C++"])}
json_data = json.dumps(data, cls=MyEncoder)
print("JSON with special types:\n", json_data)

8. Preserve original key order – Use json.dumps with ensure_ascii=False (Python 3.7+ maintains insertion order by default).

import json
data = {"name": "Alice", "age": 30, "is_student": False, "skills": ["Python", "JavaScript", "C++"]}
json_data = json.dumps(data, indent=4, ensure_ascii=False)
print("Ordered JSON data:\n", json_data)

9. Serialize non‑ASCII characters – Set ensure_ascii=False to keep Unicode characters intact in the output.

import json
data = {"name": "Alice", "age": 30, "is_student": False, "skills": ["Python", "JavaScript", "C++"], "notes": "这是一个测试\n包含中文字符"}
json_data = json.dumps(data, indent=4, ensure_ascii=False)
print("JSON with non‑ASCII characters:\n", json_data)

10. Process binary JSON data – Decode a bytes object to a string, then use json.loads and json.dumps for conversion.

import json
binary_data = b'{"name": "Alice", "age": 30, "is_student": false}'
str_data = binary_data.decode('utf-8')
obj = json.loads(str_data)
print("Decoded Python object:", obj)
json_str = json.dumps(obj)
print("Re‑encoded JSON string:", json_str)
PythonJSONFile I/OData SerializationPretty Print
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login 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.