Lesson 27 of 30

In progress

Course progress

Python

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 dumps and loads.
  • 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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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/loads work on strings, dump/load work on files.
  • JSON maps dictionaries, lists, strings, numbers, booleans and null; tuples become lists and sets fail.
  • indent, sort_keys and ensure_ascii=False make 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?
No. JSON is text with a strict grammar; a dictionary is a Python object. The text happens to look similar, but JSON allows only double-quoted keys, no trailing commas and no comments.
Can I store comments in a JSON file?
Not in standard JSON. Some tools accept comments, but `json.loads` will reject them. Put explanations in a separate README or in a key such as `”_comment”`.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.