Concepts / Converting Python Objects to JSON with json.dumps()

Converting Python Objects to JSON with json.dumps()

The important change is the representation: JSON text becomes Python data that can be handled with lists, dictionaries, indexes, keys, and for loops.

  • 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 Text to Structures

A JSON string is text. Before you can work with the information inside it as Python data, json.loads() transforms that text into native Python structures. The result is not a special JSON object: it is made from ordinary Python lists and dictionaries.

JSON stringtextPython listnative structurePython dictionarynative structurejson.loads()json.loads()
What changes when json.loads() converts a JSON string into Python lists and dictionaries?
Key point

The important change is the representation: JSON text becomes Python data that can be handled with lists, dictionaries, indexes, keys, and for loops.

A Nested Python Shape

After parsing, the structure of the data matters. A list can contain dictionaries, and a dictionary can contain a list. You navigate by following that structure one step at a time. If a list contains several dictionary records, an index selects one record; a dictionary key then selects a value inside that record.

recordsPython listfirst recordPython dictionarynamedictionary keyskillsPython listskillsdictionary keyindex 0keykeyvalue
What contains what after JSON data is parsed into nested dictionaries and lists?

Following Indexes and Keys

Code walkthrough
import json

text = '[{"name": "Ari"}, {"name": "Bea"}]'
records = json.loads(text)
first_name = records[0]["name"]
print(first_name)
  1. 1
    The variable text holds JSON text.
  2. 2
    The call to json.loads() produces a Python list containing dictionaries.
  3. 3
    The index 0 selects the first dictionary in the list.
  4. 4
    The key name selects the value Ari from that dictionary.
  5. 5
    The selected value is printed.
  • json.loads(text) parses the JSON string into Python data.
  • records[0] selects the first element of the resulting list.
  • records[0]["name"] selects the value associated with the name key in that dictionary.
Output
Ari
recordslist0list indexfirst dictionaryrecords[0]namedictionary keyAriselected valueselectrecords[0]select keyrecords[0]["name"]
How does each index or dictionary key lead from the parsed structure to a specific value?

The expression records[0]["name"] is chained access. First, [0] operates on the list. The result is a dictionary, so ["name"] then operates on that dictionary. Each part of the expression matches the next container in the parsed structure.

Parsing Versus Serialization

OperationStarting dataResult
json.loads()JSON stringNative Python lists and dictionaries
json.dumps()Python objectJSON text

The two operations move data in opposite directions.

The names are easy to confuse. json.loads() is the operation used when JSON text must become Python structures that you can navigate. json.dumps() is the opposite direction: it converts a Python object to JSON text. This article's navigation steps begin after json.loads(), because the result is ordinary Python data.

python

Mistakes with Parsed Data

  • Common mistake

    Treating the parsed result as a special JSON type

    What it looks like

    Trying to find special JSON methods for moving through data after json.loads()

    Why it fails

    json.loads() translates the JSON string into native Python lists and dictionaries.

    Do this instead

    Use standard Python list indexing, dictionary keys, and for loops.

  • Common mistake

    Using only a dictionary key when the outer structure is a list

    What it looks like
    records["name"]
    Why it fails

    The first access must match the outer container. A list is navigated with an index.

    Do this instead

    Select an element first, then use its dictionary key, as in records[0]["name"].

  • Common mistake

    Stopping the access chain too early

    What it looks like
    records[0]
    Why it fails

    This selects the first dictionary but does not yet select the value stored under a key.

    Do this instead

    Add the dictionary key when a specific field is needed: records[0]["name"].

Best practice

Before writing an access expression, identify the current container. Ask whether it is a list or a dictionary. Use an index for a list and a key for a dictionary, then repeat the process for the next nested value.

Practice the Path

EASY

Suppose parsed_data is a Python list whose first element is a dictionary containing the key "city". Write the standard Python expression that selects the value for "city" in the first element.

Hints
  • The outer structure is a list, so begin with an index.
  • The first element uses index 0.
  • The selected dictionary uses the key "city".
Worked example

Selecting a Nested City

Find the value associated with the city key in the first dictionary of parsed_data.

  1. 1
    Identify the outer structure

    parsed_data is a list, so use a list index first.

  2. 2
    Select the first element

    The first element is selected with index 0, producing the first dictionary.

  3. 3
    Select the dictionary value

    Use the city key on that dictionary.

Result

parsed_data[0]["city"]

What to Remember

  1. 1
    json.loads() transforms a JSON string into native Python lists and dictionaries.
  2. 2
    After parsing, the data is navigated with standard Python syntax.
  3. 3
    Use list indexes to select list elements and dictionary keys to select dictionary values.
  4. 4
    Chained access follows nested structures one container at a time, such as info[0]["name"].
  5. 5
    json.loads() reads JSON text into Python structures, while json.dumps() converts Python objects into JSON text.

At a glance

  • json.loads() changes JSON text into ordinary Python lists and dictionaries.
  • Parsed JSON does not require special traversal methods.
  • Use indexes for lists, keys for dictionaries, and chained access for nested data.
  • The expression info[0]["name"] selects a key from the first dictionary in a list.
  • json.dumps() moves in the opposite direction by converting Python objects to JSON text.

Related concepts

More concepts starting with C