Concepts / Importing and Using Python Modules

Importing and Using Python Modules

json.loads() transforms a JSON string into native Python structures—lists and dictionaries—not a special JSON type.

  • Programming
Interactive lab

Try it: Parsing JSON into Python

How json.loads() reads JSON text token by token and builds Python dicts, lists, strings, numbers, True/False and None, how an access path like data["users"][0]["name"] walks that structure, and what json.dumps() writes back.

How it works

  1. The scanner reads the next token: a brace or bracket, a string in double quotes, a number, true / false / null, or a ',' / ':' delimiter.
  2. '{' starts a Python dict and '[' a list; both are pushed on a parse stack until their closing '}' or ']'.
  3. Inside a dict every key must be a double-quoted string followed by ':' and a value; items are separated by ','.
  4. Anything else stops the parse with JSONDecodeError, reporting the message, line, column and character position.
  5. The access path is applied one subscript at a time: dicts take keys (KeyError if missing), lists take integer indexes (IndexError if out of range).
  6. json.dumps() turns the Python objects back into JSON text (True → true, None → null), optionally indented.

Default run (43 steps): json.loads() receives 105 characters of text. The scanner starts at char 0 and reads one token at a time. … json.dumps(data, indent=2) turns the Python objects back into JSON text (171 characters): True → true, None → null, and strings get double quotes.

Simplified: Written from scratch to match CPython 3.12's json module (messages and positions checked against it); input is limited to 400 characters and 24 nesting levels, and the access path accepts only ["key"] and [index] subscripts. Python 3.13 reports a trailing comma in an object with a different message.

Educational simulation

Loading the simulation…

From JSON Text to Python Data

A JSON string is text. Before you can work with its contents as a Python list or dictionary, you parse it with json.loads(). The result is native Python data: lists and dictionaries, not a special JSON type. That change determines how you work with the result afterward.

Definition

json.loads() transforms a JSON string into native Python structures—lists and dictionaries—not a special JSON type.

JSON string[{"name": "Ada"}]Python dictionaryname: Adajson.loads()parsePython listfirst element: dictionaryinputreturnscontains
What changes when json.loads() converts a JSON string into Python lists and dictionaries?

The Parsing Step

The parsing process has one important boundary. Before json.loads(), the data is a JSON string. After json.loads(), the result is made of Python lists and dictionaries. The outer shape of the example below is a list, and the item inside that list is a dictionary.

python

In this example, text holds the JSON string and info holds the result of parsing it. The useful mental model is not that info remains JSON. Instead, info is now a Python list whose first element is a Python dictionary.

infolistfirst elementdictionarynamekeyAdavaluecontainshas keymaps to
What contains what after parsing the JSON string?

Indexing Through Nested Values

Once the JSON text has been parsed, navigate the result with ordinary Python syntax. Use a list index to select an element from a list, then use a dictionary key to select a value from that dictionary. When structures are nested, chain the operations together.

Code walkthrough
import json

text = '[{"name": "Ada"}, {"name": "Grace"}]'
info = json.loads(text)
name = info[0]['name']
print(name)
  1. 1
    info[0] selects the first element of the list.
  2. 2
    info[0]['name'] selects the value associated with the name key in that dictionary.
  3. 3
    name receives the selected value.
  4. 4
    print(name) displays Ada.
Output
Ada
infolist0first elementdictionaryname: Adanamedictionary keyAdaselected valueindexselectskeyvalue
How do the list index and dictionary key map to the specific value Ada?
Key point

The expression info[0]['name'] is a two-step path: first select list element 0, then select the dictionary value under the name key.

Traversing Without JSON Methods

Parsing is the part that uses the json module. Traversing is different. After parsing, you do not need special JSON methods to reach values. Use standard Python operations such as list indexing, dictionary keys, and for loops.

python
Output
Ada
Grace

The for loop visits the elements of the parsed list. Each person is a dictionary, so person['name'] uses ordinary dictionary-key syntax. The loop does not need a JSON-specific traversal operation.

Common Navigation Mistakes

  • Common mistake

    Treating the parsed result as if it were still JSON text.

    What it looks like

    Looking for special JSON traversal methods after assigning the result of json.loads().

    Why it fails

    json.loads() has already translated the JSON string into native Python lists and dictionaries.

    Do this instead

    Use standard Python syntax: list indexes, dictionary keys, and for loops.

  • Common mistake

    Using only the dictionary key and forgetting that the outer structure is a list.

    What it looks like

    Trying to access the name value directly from info when info is a list of dictionaries.

    Why it fails

    The name key belongs to a dictionary inside the list, not to the outer list itself.

    Do this instead

    Select the list element first, then use the dictionary key, as in info[0]['name'].

  • Common mistake

    Stopping the access path before reaching the value.

    What it looks like

    Using info[0] when the goal is the value under the name key.

    Why it fails

    info[0] selects the dictionary but does not yet select a value from that dictionary.

    Do this instead

    Chain the dictionary-key operation after the list index: info[0]['name'].

Practice the Access Path

EASY

Given the parsed value info from the example below, write the Python expression that extracts Grace.

info = [{"name": "Ada"}, {"name": "Grace"}]

Hints
  • info is a list, so begin with a list index.
  • Grace is in the second dictionary, whose list index is 1.
  • After selecting that dictionary, use the name key.
Worked example

Selecting the Second Name

Extract Grace from info = [{"name": "Ada"}, {"name": "Grace"}].

  1. 1
    Select the list element

    The second dictionary is at list index 1, so begin with info[1].

  2. 2
    Select the dictionary value

    The desired value is associated with the name key, so add ['name'].

  3. 3
    Combine the operations

    The complete access path is info[1]['name'].

Result

info[1]['name'] produces Grace.

Working Rule

  1. 1
    Use json.loads() to convert a JSON string into native Python lists and dictionaries.
  2. 2
    After parsing, the result is not a special JSON type.
  3. 3
    Use list indexing to select elements and dictionary keys to select values.
  4. 4
    For nested data, chain access operations such as info[0]['name'].
  5. 5
    Use ordinary Python syntax, including for loops, to traverse parsed data.

Key Takeaways

  • json.loads() translates JSON text into native Python lists and dictionaries.
  • The parsed result does not require special JSON traversal methods.
  • Use list indexes and dictionary keys to follow a path through nested data.
  • Chained indexing such as info[0]['name'] extracts a specific nested value.
  • Standard Python for loops can traverse the resulting lists.

Related concepts

More concepts starting with I