Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

JSON in Python: Working with JSON Data

1 min read .
JSON in Python: Working with JSON Data

JSON (JavaScript Object Notation) is a text format for structured data exchange. Python includes the json module in the standard library, so common JSON operations require no third-party dependency.

Python Objects to JSON Strings

Use json.dumps() to serialize a Python object:

import json

data = {
    "name": "Alice",
    "age": 25,
    "city": "New York",
}

json_string = json.dumps(data)
print(json_string)

For readable output:

print(json.dumps(data, indent=2))

JSON Strings to Python Objects

Use json.loads() to parse a JSON string:

payload = '{"name": "Alice", "age": 25}'
data = json.loads(payload)

print(data["name"])

JSON objects become Python dictionaries, arrays become lists, and JSON scalar values map to their corresponding Python types.

Write JSON to a File

Use json.dump() when writing directly to a file object:

with open("data.json", "w", encoding="utf-8") as file:
    json.dump(data, file, indent=2, ensure_ascii=False)

ensure_ascii=False preserves non-ASCII characters in readable Unicode form.

Read JSON from a File

with open("data.json", "r", encoding="utf-8") as file:
    data = json.load(file)

print(data)

Handle Invalid JSON

Parsing malformed JSON raises json.JSONDecodeError:

import json

try:
    data = json.loads('{"name": "Alice",}')
except json.JSONDecodeError as exc:
    print(f"Invalid JSON: {exc}")

Common Serialization Limitation

Not every Python object is directly JSON serializable. For example, datetime, Decimal, Path, and custom classes need explicit conversion or a custom encoder.

from datetime import datetime
import json

data = {"created_at": datetime.now().isoformat()}
print(json.dumps(data))

JSON Is Not the Same as a Python Literal

JSON uses true, false, and null, while Python uses True, False, and None. Always parse external JSON with the json module rather than eval().

Conclusion

Use dumps() and loads() for JSON strings, and dump() and load() for file objects. Handle decoding errors explicitly and convert unsupported Python types before serialization.

Related Posts

chevron-up