JSON in Python — Parse, Format & Generate
Python's built-in json module makes it straightforward to parse, generate, and manipulate JSON data. No third-party packages are required for most tasks.
Parse a JSON string
Use json.loads() to parse a JSON string into a Python dict or list. The 's' stands for string.
import json
json_string = '{"name": "Alice", "age": 30, "active": true}'
data = json.loads(json_string)
print(data["name"]) # Alice
print(data["age"]) # 30
print(type(data)) # <class 'dict'>Read a JSON file
Use json.load() (without 's') to parse a JSON file directly from a file object.
import json
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
print(data)Serialize Python objects to JSON
Use json.dumps() to convert a Python dict or list to a JSON string. Use indent for pretty-printing.
import json
data = {"name": "Alice", "scores": [95, 87, 92], "active": True}
# Compact
compact = json.dumps(data)
print(compact)
# {"name": "Alice", "scores": [95, 87, 92], "active": true}
# Pretty-printed
pretty = json.dumps(data, indent=2)
print(pretty)Write a JSON file
Use json.dump() to write Python data directly to a file.
import json
data = {"name": "Alice", "active": True}
with open("output.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)Handle JSON errors
Catch json.JSONDecodeError when parsing untrusted input.
import json
bad_json = '{"name": "Alice", missing_quote}'
try:
data = json.loads(bad_json)
except json.JSONDecodeError as e:
print(f"Parse error: {e.msg} at line {e.lineno}, col {e.colno}")Related Tools
Frequently Asked Questions
How do I parse JSON in Python?▾
Use json.loads() to parse a JSON string into a Python dict or list. For files, use json.load() with an open file object.
What is the difference between json.loads() and json.load()?▾
json.loads() parses a JSON string (the 's' stands for string). json.load() reads and parses from a file object directly.
How do I pretty-print JSON in Python?▾
Pass indent=2 (or any number) to json.dumps(): json.dumps(data, indent=2). This adds newlines and indentation.
How do I handle JSON parse errors in Python?▾
Wrap json.loads() in a try/except block and catch json.JSONDecodeError. It provides the error message, line number, and column number.
Can Python serialize custom objects to JSON?▾
Not directly. Use default= parameter to provide a custom encoder function, or subclass json.JSONEncoder and override the default() method.
JSON in Other Languages
Format and validate your JSON instantly
Free, no ads, no sign-up. Also converts JSON to TypeScript, YAML, CSV, and more.
Open JSON Formatter →If jsondecode.com saved you time, share it with your team
Free forever. No ads. No sign-up. Help other developers find it.