Lesson 27 of 30
In progress
JSON: structured data that survives
Convert between Python objects and JSON text, handle malformed input, and store settings without inventing a format.
Saving a dictionary with str() gives you Python syntax that only Python can read, and eval is not a parser you should point at a file. JSON is the format every language, browser and API already understands.
What you will learn
- Convert Python values to JSON text and back with
dumpsandloads. - Read and write JSON files without losing structure.
- Recover from malformed JSON instead of crashing.
Two functions do most of the work
json.dumps turns a Python value into a string. json.loads turns a string back into Python values.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
data = {
"name": "Ana",
"scores": [88, 92],
"active": True,
"address": {"city": "Pune", "pin": "411001"}
}
text = json.dumps(data)
print(text)
back = json.loads(text)
print(back["address"]["city"])
print(type(back["scores"]))
Press Run to see the output.
The types map cleanly: dictionaries become objects, lists become arrays, strings and numbers stay themselves, True becomes true, and None becomes null. Tuples become arrays, so a tuple round-trips as a list; sets are not serialisable at all, because JSON has no concept of an unordered unique collection.
Make output readable
The compact form is right for machines and wrong for humans. indent formats it, sort_keys makes diffs stable, and ensure_ascii=False keeps non-English text readable.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
data = {"नाम": "अनन्या", "score": 91}
print(json.dumps(data, ensure_ascii=False))
print(json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False))
Press Run to see the output.
Without ensure_ascii=False, Hindi text is written as u0905... escapes. That is valid JSON and parses back correctly, but it is unreadable in a file a person may edit. The file is still UTF-8, so keep the encoding explicit when writing.
Files use load and dump
json.dump writes to a file object and json.load reads from one. Note the missing s.
import json
from pathlib import Path
path = Path("settings.json")
settings = {"theme": "dark", "font_size": 16}
with path.open("w", encoding="utf-8") as handle:
json.dump(settings, handle, indent=2, ensure_ascii=False)
with path.open(encoding="utf-8") as handle:
loaded = json.load(handle)
print(loaded["theme"])
Opening the file yourself keeps the encoding explicit and the with visible. path.write_text(json.dumps(...)) is shorter, but you must pass the encoding there too.
Malformed JSON is a normal case
A truncated file, a stray comma or an HTML error page saved as JSON all raise json.JSONDecodeError, which is a subclass of ValueError.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
raw = '{"name": "Ana",}'
try:
data = json.loads(raw)
except json.JSONDecodeError as error:
print("Invalid JSON at line", error.lineno, "column", error.colno)
data = {}
Press Run to see the output.
JSON from other people is input, not trusted data. A key you expect may be missing, a number may arrive as a string, and a list may turn out to be a dictionary. Validate the shape at the boundary, then work with values you have checked. A KeyError deep inside a report is far harder to diagnose than a clear message at load time.
The exception carries lineno, colno and pos, which is far more useful than printing a generic failure. When a file is user-editable, catch this and show the position; when it is generated by your own code, a traceback is the honest response because the bug is yours.
A round trip is a test
The simplest check for a data model is to serialise it, parse it back and compare. Differences reveal types JSON cannot represent.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
original = {"count": 3, "tags": ["a", "b"], "meta": None}
again = json.loads(json.dumps(original))
print(again == original)
print(again)
Press Run to see the output.
This passes because every value is JSON-native. Add a tuple or a set and the comparison fails or the dump raises, which is exactly the information you want before writing data to disk.
json.dumps raises TypeError: Object of type set is not JSON serialisable for sets, and the same for datetime objects and custom classes. Convert deliberately: sorted(my_set) for a set, value.isoformat() for a datetime, and a dictionary of chosen fields for a class. Do not reach for default=str as a blanket fix; it silently turns structured values into strings that nothing can parse back.
Parse the JSON string below, print each product whose price is above 100, and write a new JSON string containing only their names, sorted alphabetically and indented by two spaces.
raw = '[{"name": "pen", "price": 12}, {"name": "desk", "price": 450}, {"name": "lamp", "price": 180}]'
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
raw = '[{"name": "pen", "price": 12}, {"name": "desk", "price": 450}, {"name": "lamp", "price": 180}]'
products = json.loads(raw)
expensive = [item for item in products if item["price"] > 100]
names = sorted(item["name"] for item in expensive)
print(json.dumps(names, indent=2))
Press Run to see the output.
The list comprehension filters, the generator inside sorted extracts names, and dumps produces the final text. Keeping the data as Python objects until the last step is what makes the transformations readable.
Recap
dumps/loadswork on strings,dump/loadwork on files.- JSON maps dictionaries, lists, strings, numbers, booleans and null; tuples become lists and sets fail.
indent,sort_keysandensure_ascii=Falsemake files readable for people.
Next, you will let a script accept arguments, so it can be reused without editing the source.
Is JSON the same as a Python dictionary?
Can I store comments in a JSON file?
Progress is saved in this browser only. No account, no email.