1. How to Parse JSON in Python (Convert JSON to Python Dictionary)

`json.loads()` takes a JSON-formatted string and turns it into a Python dictionary (or list, depending on the root element). That's it. No magic.\n\nThe json.loads python function is what you'll reach for every time you get a JSON string back from an API, a message queue, or a config value stored as text. The "s" in loads stands for string — it loads from a string.

Parsing JSON String to Python Dict
import json

raw = '{"name": "Ada", "mass_kg": 68, "languages": ["Python", "Rust"]}'

data = json.loads(raw)

print(data["name"])        # Ada
print(data["languages"][0]) # Python
print(type(data))           # <class 'dict'>
Explanation: `json.loads()` converts valid JSON strings into Python data types automatically.

Pro Tips

  • One thing to watch: `json.loads()` is strict. It expects valid JSON. Feed it malformed data and you'll get a `json.decoder.JSONDecodeError`.

2. Convert Python Dictionary to JSON String with `json.dumps`

Going the other direction is just as easy. `json.dumps()` serializes a Python object (dict, list, etc.) into a JSON string. Notice how Python's `True` became JSON's `true`? The module handles that mapping automatically (`True` → `true`, `False` → `false`, `None` → `null`).

Basic json.dumps usage
import json

user = {
    "id": 42,
    "username": "guido",
    "active": True,
    "roles": ["admin", "reviewer"]
}

json_string = json.dumps(user)
print(json_string)
# {"id": 42, "username": "guido", "active": true, "roles": ["admin", "reviewer"]}
Explanation: `json.dumps` handles the boolean mapping automatically.

3. Pretty Print JSON in Python for Debugging

By default, `json.dumps()` gives you a compact, single-line string. That's fine for sending over the wire, but terrible for debugging. Use the `indent` parameter to format it nicely.

Formatting Python Dict to Indented JSON
pretty = json.dumps(user, indent=4)
print(pretty)
Explanation: You can also throw in `sort_keys=True` if you want your keys alphabetically ordered — handy for diffing two JSON blobs.

4. How to Read JSON Files & Write JSON to File in Python

Here's where people trip up on naming. There are four functions, not two:\n\n- `json.loads()` : string → Python object\n- `json.load()` : file → Python object\n- `json.dumps()` : Python object → string\n- `json.dump()` : Python object → file\n\nThe versions without the "s" work directly with file objects.

File I/O with JSON
import json

# Reading a JSON file
with open("config.json", "r") as f:
    config = json.load(f)

# Writing a Python dict to a JSON file
settings = {
    "theme": "dark",
    "font_size": 14,
    "auto_save": True
}

with open("settings.json", "w") as f:
    json.dump(settings, f, indent=4)
Explanation: Use `json.load()` / `json.dump()` for files, `json.loads()` / `json.dumps()` for strings.

5. JSONDecodeError Python: Single Quotes vs Double Quotes

This is the #1 gotcha. Python is perfectly happy with single-quoted strings. JSON is not. JSON requires double quotes around keys and string values.\n\nBut what if you're getting single-quoted data from a legacy system or a badly serialized source? Don't try to regex your way out. Use `ast.literal_eval()` to parse the Python literal, then re-serialize:

Fixing Single Quotes via ast
import ast
import json

bad_payload = "{'name': 'Ada', 'active': True}"
python_obj = ast.literal_eval(bad_payload)
clean_json = json.dumps(python_obj)

print(clean_json)
# {"name": "Ada", "active": true}
Explanation: This safely parses a string representation of a Python dictionary into an actual dict.

Pitfall 2: Trailing Commas Are Illegal in JSON

Python dicts and JavaScript objects tolerate trailing commas. JSON doesn't. Your parser will choke on this. Strip it before parsing, or better yet — paste the broken payload into PrettyJSON.in to instantly format, validate, and auto-repair it.

Trailing Comma Error
{
    "name": "Ada",
    "age": 36,   // ← This trailing comma? Illegal.
}
Explanation: Remove the trailing comma to make the JSON valid.

Pitfall 3: None vs null, True vs true

Python and JSON have different names for the same concepts. `json.dumps()` handles this automatically when writing, but if you're manually constructing a JSON string (don't do this), you need to use `null`, `true`, and `false` — not their Python equivalents.

Boolean Mapping
# Let json.dumps handle the conversion — don't build JSON strings by hand
data = {"value": None, "flag": True}
print(json.dumps(data))
# {"value": null, "flag": true}
Explanation: Never use string concatenation to build JSON.

Pitfall 4: Encoding Non-Serializable Objects

Try to dump a `datetime` or a custom class and you'll hit a `TypeError: Object of type datetime is not JSON serializable`. The quick fix: use the `default` parameter with a custom serializer.

Custom Serializer for datetime
import json
from datetime import datetime

def serialize(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError(f"Type {type(obj)} not serializable")

print(json.dumps({"ts": datetime.now()}, default=serialize))
# {"ts": "2026-08-05T12:30:00.123456"}
Explanation: Passing `default=serialize` allows Python to convert custom objects like `datetime` into strings.

Quick Reference Cheat Sheet

That covers 95% of what you'll ever do with JSON in Python. The `json` module is simple, battle-tested, and comes free with every Python install. When things break, it's almost always a data problem — bad quotes, trailing commas, or non-serializable types.

JSON in Python Cheat Sheet
import json

# String → Dict
data = json.loads('{"key": "value"}')

# Dict → String
text = json.dumps(data, indent=4)

# File → Dict
with open("data.json") as f:
    data = json.load(f)

# Dict → File
with open("out.json", "w") as f:
    json.dump(data, f, indent=4)
Explanation: Keep this cheat sheet handy for everyday JSON operations in Python.