codePython

How to Parse JSON in Python

Python's built-in json module makes JSON parsing straightforward. This guide covers json.loads(), json.load(), json.dumps(), error handling, and real-world patterns.

Parsing a JSON String with json.loads()

Use json.loads() to parse a JSON string into Python data structures. The json module is part of the Python standard library — no install required.

import json

# Parse a JSON string
json_string = '{"name": "Alice", "age": 30, "active": True}'
# Note: JSON uses true/false/null — Python gets True/False/None
json_string = '{"name": "Alice", "age": 30, "active": true}'
data = json.loads(json_string)

print(data["name"])    # Alice
print(data["age"])     # 30
print(data["active"])  # True (Python bool)
print(type(data))      # <class 'dict'>

# Parse a JSON array
json_array = '[1, 2, 3, "four", true, null]'
arr = json.loads(json_array)
print(arr[3])   # four
print(arr[5])   # None  (JSON null → Python None)

Reading JSON from a File with json.load()

import json

# Read a JSON file
with open("config.json", "r", encoding="utf-8") as f:
    config = json.load(f)  # load() reads from file object

print(config["database"]["host"])

# Read JSON from a URL response
import urllib.request

with urllib.request.urlopen("https://api.example.com/data") as response:
    data = json.load(response)  # response is file-like

# With requests library (recommended)
import requests

response = requests.get("https://api.example.com/data")
response.raise_for_status()
data = response.json()  # auto-parses JSON response

Serializing Python to JSON with json.dumps()

import json

data = {
    "name": "Alice",
    "age": 30,
    "roles": ["admin", "editor"],
    "active": True,
    "score": None
}

# Compact JSON string
json.dumps(data)
# '{"name": "Alice", "age": 30, "roles": ["admin", "editor"], ...}'

# Pretty-printed JSON
print(json.dumps(data, indent=2))
# {
#   "name": "Alice",
#   "age": 30, ...
# }

# Sort keys alphabetically
json.dumps(data, sort_keys=True)

# Write JSON to a file
with open("output.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2)  # json.dump() writes to file

Error Handling — json.JSONDecodeError

import json

def safe_parse(json_string):
    try:
        return json.loads(json_string)
    except json.JSONDecodeError as e:
        print(f"JSON error: {e.msg}")
        print(f"  Line {e.lineno}, column {e.colno}")
        print(f"  Near: {e.doc[max(0,e.pos-20):e.pos+20]}")
        return None

# JSONDecodeError provides:
# e.msg    — error description
# e.lineno — line number of the error
# e.colno  — column number
# e.pos    — character position
# e.doc    — the original JSON string

result = safe_parse('{"name": "Alice",}')  # trailing comma
# JSON error: Expecting property name enclosed in double quotes
# Line 1, column 18

JSON ↔ Python Type Mapping

JSON TypePython Type
stringstr
number (integer)int
number (float)float
true / falseTrue / False
nullNone
object {}dict
array []list

Parse JSON in Other Languages

FAQ

How do I parse a JSON string in Python?expand_more

Use json.loads(json_string) from the built-in json module. It returns a Python dict, list, str, int, float, bool, or None depending on the JSON content. Example: import json; data = json.loads('{"name": "Alice"}'); print(data["name"])

How do I read a JSON file in Python?expand_more

Open the file and use json.load() (not json.loads()). Example: with open("data.json") as f: data = json.load(f). The load() function reads from a file object; loads() parses a string.

What is the difference between json.load() and json.loads() in Python?expand_more

json.load() reads JSON from a file-like object (open file). json.loads() parses a JSON string. The "s" in loads() stands for "string". Use load() for files, loads() for strings.

How do I handle JSON decode errors in Python?expand_more

Catch json.JSONDecodeError: try: data = json.loads(text) except json.JSONDecodeError as e: print(f"Invalid JSON: {e.msg} at line {e.lineno}".). JSONDecodeError is a subclass of ValueError.

How to Parse JSON in Python — json.loads & json.dumps Guide