Python JSON Parser and Validator
Learn how to read, validate, modify, and serialize JSON in Python. Master the built-in json library with realistic examples.
How it Works
JSON (JavaScript Object Notation) is the standard format for exchanging data on the web. Python provides a powerful built-in module named `json` that translates JSON strings into Python dictionaries and vice versa.
The module exposes two main sets of operations: `loads` and `dumps` for handling JSON strings directly, and `load` and `dump` for writing or reading data directly from file streams.
When working with JSON, error handling is critical. Python raises a `json.JSONDecodeError` if the string syntax is broken, which is essential to catch when consuming payloads from public APIs.
Source Code
A script demonstrating JSON string validation, dict parsing, modifications, and pretty printing.
import json
raw_json = """
{
"status": "success",
"data": {
"user_id": 9042,
"username": "coder_xyz",
"roles": ["admin", "developer"],
"verified": true
}
}
"""
try:
# Parsing JSON string into Python dict
data = json.loads(raw_json)
print("--- JSON Decoded Successfully ---")
print(f"Username: {data['data']['username']}")
print(f"Is Admin: {'admin' in data['data']['roles']}")
# Mutating Python dict
data['data']['verified'] = False
data['data']['last_login'] = "2026-05-25"
# Serializing dict back to formatted JSON
pretty_json = json.dumps(data, indent=4)
print("\n--- Modified JSON String ---")
print(pretty_json)
except json.JSONDecodeError as e:
print(f"Invalid JSON Format: {e}")--- JSON Decoded Successfully ---
Username: coder_xyz
Is Admin: True
--- Modified JSON String ---
{
"status": "success",
"data": {
"user_id": 9042,
"username": "coder_xyz",
"roles": [
"admin",
"developer"
],
"verified": false,
"last_login": "2026-05-25"
}
}Real-world Applications
- Reading application configurations and credential files
- Parsing responses from REST API endpoints
- Saving program states or levels in desktop utilities
Frequently Asked Questions
What is the difference between dump and dumps in Python?
`dumps` serializes an object into a JSON string format, while `dump` writes the serialized JSON stream directly into a writeable file object.
How does Python handle JSON null values?
Python's `json` decoder automatically maps JSON `null` to `None`, `true` and `false` to `True` and `False`, and arrays to lists.