Python has built-in JSON support right in the standard library, so there’s nothing extra to install. This post covers the basics: reading JSON from a string, reading from a file, generating JSON from a Python object, and the most common errors you’ll run into along the way.
Importing the module
import json
That’s all it takes. json has been part of the standard library since Python 2.6, so there’s no pip install involved.
Converting a JSON string into a Python object
# python
json_text = '{"name": "Ana", "age": 30, "active": true}'
data = json.loads(json_text)
print(data["name"]) # Ana
print(type(data)) # <class 'dict'>
json.loads() (load string) takes a string and returns the matching Python object. A JSON object becomes a dict, and an array becomes a list.
Reading JSON directly from a file
# python
with open("data.json", "r", encoding="utf-8") as file:
data = json.load(file)
print(data)
Notice the difference: json.load() (no “s”) takes an open file, not a string. json.loads() is for when you already have the content as a string in memory.
Converting a Python object into JSON
# python
data = {"name": "Ana", "age": 30, "active": True}
json_text = json.dumps(data)
print(json_text) # '{"name": "Ana", "age": 30, "active": true}'
json.dumps() (dump string) does the reverse: it takes a Python object and returns a JSON string. Notice True (Python) became true (JSON), since the two have different capitalization conventions.
Saving JSON to a file
# python
data = {"name": "Ana", "age": 30}
with open("output.json", "w", encoding="utf-8") as file:
json.dump(data, file)
Again, json.dump() without the “s” works directly with the file, instead of generating an intermediate string.
Formatting the output JSON (indentation)
By default, json.dumps() generates everything on a single line. To make it readable, use the indent parameter.
# pyhton
data = {"name": "Ana", "address": {"city": "Rio de Janeiro", "zip": "20000-000"}}
formatted_text = json.dumps(data, indent=2, ensure_ascii=False)
print(formatted_text)
The ensure_ascii=False parameter matters when your data has accented characters or other non-ASCII text. Without it, Python escapes everything into \uXXXX sequences, which is still valid JSON, but unreadable for humans.
Handling parse errors
If the JSON is malformed, json.loads() raises a json.JSONDecodeError exception.
# python
try:
data = json.loads('{"name": "Ana",}') # trailing comma, invalid
except json.JSONDecodeError as error:
print(f"Invalid JSON: {error}")
Python’s error message usually points to the exact line and column of the problem, which makes debugging a lot easier without needing an external tool.
Type equivalence table
| JSON | Python |
|---|---|
| object | dict |
| array | list |
| string | str |
| number (int) | int |
| number (float) | float |
| true / false | True / False |
| null | None |
Quick checklist
- Using
loads()/dumps()for strings andload()/dump()for files? - Remembered
ensure_ascii=Falseif the content has accented characters? - Handling
json.JSONDecodeErrorin code that receives JSON from external sources (API, file upload, etc.)?
If you want to quickly validate a JSON before using it in your Python code, paste it into JSON Validator.