The standard library & JSON

Read structured data

Lesson 11 of 20 · 10 min · Module 4: Reliable little programs

Python’s standard library includes tools for common jobs. The json module turns JSON text into dictionaries, lists, and other Python values.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Import a standard library module
  • Distinguish JSON text from parsed Python values
  • Validate structure after successful parsing

The idea

Import a module with import json. Use json.loads(text) to parse a string. Catch json.JSONDecodeError for malformed JSON.

import json
settings = json.loads('{"theme": "dark"}')
print(settings["theme"]) # dark

01Parsing is only the first check

Valid JSON can describe a list, a number, or null, not just an object. A successful parse does not guarantee the dictionary shape that your function expects.

02Follow a clear validation order

First parse the text. Next check its type. Finally read the optional key. This ordering keeps malformed input, unexpected structure, and missing data separate.

Your turn

Define read_theme(text). Parse a JSON object and return its theme value. Return "light" if the key is missing, the JSON is malformed, or the parsed value is not a dictionary.

What the checks look for

  • Reads the requested theme
  • Defaults for a missing key
  • Recovers from malformed text
  • Handles a different JSON type
Try it in the editor →

Take this with you

Data is ready to use only after both its syntax and its structure make sense.

Learn Python Foundations for free

20 short lessons with real code and instant checks.

See the whole course →