Working with JSON in Python
1Python JSON: overview
JSON is a plain-text format for structured data, and Python's built-in json module converts JSON text into dictionaries and lists — and back again.
Before this lesson: Python Dictionaries, Python File Handling
2Python JSON: diagram
3Python JSON: explained step by step
JSON (JavaScript Object Notation) is the most common way for programs to swap data: web APIs answer in JSON, apps save settings in it, and many tools export it. It looks a lot like Python, which makes it easy to read — but until you convert it, JSON is just text: one long string.
JSON text to Python: json.loads()
json.loads() ("load string") parses JSON text and gives you ordinary Python objects:
- a JSON object
{...}becomes adict - a JSON array
[...]becomes alist true/falsebecomeTrue/False, andnullbecomesNone- strings and numbers stay strings and numbers
import json
text = '{"name": "Asha", "age": 21, "member": true, "coupon": null}'
user = json.loads(text)
print(user)
print(type(user).__name__, user["member"], user["coupon"])Python to JSON text: json.dumps()
json.dumps() ("dump string") goes the other way. Without options you get one compact line, ideal for sending over a network. Add indent=2 for readable, multi-line output, and sort_keys=True to order the keys alphabetically.
Only some Python types have a JSON equivalent: dicts with string keys, lists, tuples (they become arrays), strings, numbers, True, False and None. Anything else — a set, a date, your own object — raises TypeError: Object of type ... is not JSON serializable, so convert it first.
Reading nested data
Real JSON is usually nested: a dict that contains lists of dicts. Work from the outside in, one key or index at a time. Use .get() for keys that might be missing, so your program doesn't crash on incomplete data.
import json
order = json.loads('''
{"id": 1042,
"customer": {"name": "Ben", "city": "Pune"},
"items": [{"sku": "A1", "qty": 2}, {"sku": "B7", "qty": 1}]}
''')
print(order["customer"]["city"])
print(order["items"][0]["sku"])
print(sum(item["qty"] for item in order["items"]))
print(order.get("discount", 0))JSON files: json.dump() and json.load()
The versions without the "s" work with files instead of strings: json.dump(data, f) writes to an open file, and json.load(f) reads one back. Together they are the easiest way to save a program's data and load it next time. (On this site, files live in your browser's temporary in-memory file system.)
JSON is stricter than Python
JSON requires double quotes around strings and keys, does not allow a trailing comma after the last item, and has no comments. When json.loads() meets any of these, it raises json.JSONDecodeError with the line and column where it gave up — a good place to start looking.
Quick reference: Python JSON
- How to Read a JSON File in Python — Open the file and call `json.load()`: `with open("data.json", encoding="utf-8") as f: data = json.load(f)`. Y…
- How to Convert JSON to a Dictionary in Python — Use `json.loads(text)` to turn a JSON string into a dictionary, or `json.load(file)` to read it from an open …
4Python JSON: syntax
import json
data = json.loads(text) # JSON string -> dict / list
text = json.dumps(data) # dict / list -> compact JSON string
text = json.dumps(data, indent=2) # pretty, multi-line JSON
with open("data.json", "w") as f:
json.dump(data, f, indent=2) # write to a file
with open("data.json") as f:
data = json.load(f) # read from a file
5Python JSON: run the example
Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.
import json
response_text = '''
{"user": "asha_k", "verified": true, "nickname": null,
"books": [
{"title": "Dune", "pages": 412},
{"title": "Emma", "pages": 474}
]}
'''
data = json.loads(response_text)
print(data["user"], data["verified"], data["nickname"])
total = sum(book["pages"] for book in data["books"])
print("Books:", len(data["books"]), "| Pages:", total)
data["books"].append({"title": "Holes", "pages": 233})
print(json.dumps(data["books"][-1]))
print(json.dumps({"user": data["user"], "count": len(data["books"])}, indent=2))Expected outputasha_k True None
Books: 2 | Pages: 886
{"title": "Holes", "pages": 233}
{
"user": "asha_k",
"count": 3
}
7Python JSON: how the example works
Hover or tap a step to highlight its lines in the example above.
- Line 1
jsonis part of the standard library, so a plainimportis all you need. - Line 3-9The JSON arrives as one string — exactly what you would get from a file or a web API. Note the JSON spellings
trueandnull. - Line 11
json.loads()parses the text into a Pythondict. - Line 12The values are now Python values:
truebecameTrueandnullbecameNone. - Line 14
data["books"]is a list of dicts. The generator expression adds up the"pages"value of each book: 412 + 474. - Line 15
len()counts the books and the total is printed. - Line 17Parsed JSON is ordinary Python data, so you can change it — here a third book is appended to the list.
- Line 18
json.dumps()turns the new book back into compact JSON text. Notice the double quotes: this is JSON, not a Python dict. - Line 19
indent=2produces readable, multi-line JSON — handy for saving files people may open.
8Python JSON: common mistakes
Writing JSON with single quotes
✗ Wrong
import json
user = json.loads("{'name': 'Asha'}")✓ Right
import json
user = json.loads('{"name": "Asha"}')
print(user["name"])JSON only accepts double quotes. Wrap the JSON text in single quotes on the Python side so you can use double quotes inside it.
Using the JSON string as if it were a dict
✗ Wrong
import json
text = '{"city": "Pune", "temp": 31}'
print(text["city"])✓ Right
import json
text = '{"city": "Pune", "temp": 31}'
weather = json.loads(text)
print(weather["city"])JSON text is just a string until you parse it. Call json.loads() first, then use keys on the resulting dict.
Mixing up load() and loads()
✗ Wrong
import json
text = '{"theme": "dark"}'
settings = json.load(text)✓ Right
import json
text = '{"theme": "dark"}'
settings = json.loads(text)
print(settings["theme"])json.load() expects an open file. For a string, use json.loads() — the "s" stands for string.
9Python JSON: exercises
Write your answer, then press Check. The checks run in your browser.
1. Describe a product from JSON
Write code Easy ✓ CompletedWrite a function describe(json_text) that parses a JSON product such as {"name": "Lamp", "price": 24.5, "in_stock": true} and returns a string like "Lamp costs $24.50". If in_stock is false, add " (sold out)" to the end.
import json
def describe(json_text):
# parse json_text with json.loads, then build and return the message
pass
print(describe('{"name": "Lamp", "price": 24.5, "in_stock": true}'))
print(describe('{"name": "Desk", "price": 120, "in_stock": false}'))
json.loads() gives you a dict. Format the price with :.2f inside an f-string, and remember that JSON false becomes Python False.import json
def describe(json_text):
product = json.loads(json_text)
message = f"{product['name']} costs ${product['price']:.2f}"
if not product["in_stock"]:
message += " (sold out)"
return message
print(describe('{"name": "Lamp", "price": 24.5, "in_stock": true}'))
print(describe('{"name": "Desk", "price": 120, "in_stock": false}'))
2. Predict the conversions
Predict the output Medium ✓ CompletedRead the code and type exactly what it prints. Watch the spelling of null/None and false/False on each line.
import json
data = json.loads('{"a": [1, 2, {"b": null}], "c": false}')
print(data["a"][2])
print(len(data), data["c"])
print(json.dumps(data))
json.dumps() produces JSON text with double quotes and JSON spellings.{'b': None}
2 False
{"a": [1, 2, {"b": null}], "c": false}
2 more exercises → 4 more examples
Questions learners ask
What is the difference between json.load() and json.loads()?
json.loads() parses a string that contains JSON. json.load() reads JSON from an open file object. The same pattern applies to json.dumps() (returns a string) and json.dump() (writes to a file).
Why do I get 'Object of type ... is not JSON serializable'?
JSON only has objects, arrays, strings, numbers, true/false and null. Convert other values before calling dumps(): a set to a sorted list, a date to a string with isoformat(), and your own objects to a dict of their attributes.
Is JSON the same as a Python dictionary?
No. JSON is text with its own rules (double quotes only, true/false/null, no trailing commas). A dict is a Python object in memory. json.loads() and json.dumps() convert between the two.
Further reading
10Next lesson
Up nextPython CSV FilesA CSV file stores a table as plain text — one row per line, values separated by commas — and Python's csv module reads …Related:
Python DictionariesPython CSV FilesPython requests: Call Web APIsPython API Example: Build an API Client
← Python Dataclasses · All Practical Python lessons · Practise in the IDE