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.
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
- The scanner reads the next token: a brace or bracket, a string in double quotes, a number, true / false / null, or a ',' / ':' delimiter.
- '{' starts a Python dict and '[' a list; both are pushed on a parse stack until their closing '}' or ']'.
- Inside a dict every key must be a double-quoted string followed by ':' and a value; items are separated by ','.
- Anything else stops the parse with JSONDecodeError, reporting the message, line, column and character position.
- 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).
- 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.
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.
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.
Following Indexes and Keys
import json
text = '[{"name": "Ari"}, {"name": "Bea"}]'
records = json.loads(text)
first_name = records[0]["name"]
print(first_name)- 1The variable text holds JSON text.
- 2The call to
json.loads()produces a Python list containing dictionaries. - 3The index 0 selects the first dictionary in the list.
- 4The key name selects the value Ari from that dictionary.
- 5The 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.
AriThe 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
| Operation | Starting data | Result |
|---|---|---|
| json.loads() | JSON string | Native Python lists and dictionaries |
| json.dumps() | Python object | JSON 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.
Mistakes with Parsed Data
Common mistake Treating the parsed result as a special JSON type
What it looks likeTrying to find special JSON methods for moving through data after json.loads()
Why it failsjson.loads()translates the JSON string into native Python lists and dictionaries.Do this insteadUse 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 likerecords["name"]Why it failsThe first access must match the outer container. A list is navigated with an index.
Do this insteadSelect an element first, then use its dictionary key, as in records[0]["name"].
Common mistake Stopping the access chain too early
What it looks likerecords[0]Why it failsThis selects the first dictionary but does not yet select the value stored under a key.
Do this insteadAdd the dictionary key when a specific field is needed: records[0]["name"].
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
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".
Selecting a Nested City
Find the value associated with the city key in the first dictionary of parsed_data.
- 1Identify the outer structure
parsed_datais a list, so use a list index first. - 2Select the first element
The first element is selected with index 0, producing the first dictionary.
- 3Select the dictionary value
Use the city key on that dictionary.
parsed_data[0]["city"]
What to Remember
- 1
json.loads()transforms a JSON string into native Python lists and dictionaries. - 2After parsing, the data is navigated with standard Python syntax.
- 3Use list indexes to select list elements and dictionary keys to select dictionary values.
- 4Chained access follows nested structures one container at a time, such as info[0]["name"].
- 5
json.loads()reads JSON text into Python structures, whilejson.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.