Constructing JSON with Python Dictionaries and Lists
json.loads() transforms a JSON string into a Python data structure by parsing the text and building corresponding lists, dictionaries, and primitive values.
From Text to Structure
A JSON document often arrives as text, but your Python program needs a usable data structure. The function json.loads() parses a JSON string and returns a new Python object built from the structure represented in that text. The original string is unchanged, so assign the returned object to a variable before trying to access its contents.
The Container Relationship
The shape of the JSON determines the shape of the returned Python data. A JSON object becomes a Python dictionary, and a JSON array becomes a Python list. Nested objects and arrays remain nested after parsing. Primitive values remain values inside those containers. This means the brackets and braces in the original text provide a map for understanding the Python structure that json.loads() creates.
A User List Step by Step
import json data = '[{"id": 1, "x": 10, "name": "Ari"}, {"id": 2, "x": 20, "name": "Bea"}]' info = json.loads(data) print(len(info)) print(info[0]['name']) print(info[1]['x'])
Reading the Nested Shape
Accessing parsed JSON is a structure-tracing task. At every level, first determine what kind of container you are holding. If the current value is a list, use an index such as [0] or [1]. If it is a dictionary, use a key such as ['name'] or ['x']. In the user example, the path info[0]['name'] means: start with the top-level list, select its first element, then select the name field from the resulting dictionary.
Tracing a Deeper Path
viewerThe access path crosses several levels. parsed is a dictionary, so ['users'] selects its users field. That field contains a list, so [0] selects the first user dictionary. The user dictionary contains a roles field, so ['roles'] selects another list. Finally, [1] selects the second element of that list. The correct access expression follows the actual container type at each step.
Knowing the Expected Shape
- Check the input before parsing: confirm that the value passed to json.loads() is a string containing JSON text.
- Read the outermost symbols: square brackets indicate a list structure, while curly braces indicate a dictionary structure.
- Map each nested level: record whether the next access requires a list index or a dictionary key.
- Use keys and indices that actually exist in the parsed structure.
- If access fails, inspect the structure layer by layer instead of guessing at a longer access expression.
import json data = '{"users": [{"name": "Ari"}]}' parsed = json.loads(data) print(parsed) print(parsed['users']) print(parsed['users'][0]) print(parsed['users'][0]['name'])
Mistakes During Parsing
Forgetting to import json before calling json.loads().
The name json has not been made available to the program.
Fix:
Import the json module before using json.loads().Passing a non-string object to json.loads().
json.loads() is used to parse a JSON string, not an already-created Python object.
Fix:
Verify that the input is a string containing JSON text before calling json.loads().Using a dictionary key where the current value is a list.
If users contains a list, the next step must select a list element before selecting a field.
Fix:
Follow the structure one level at a time, such as parsed['users'][0]['name'] when that path matches the actual data.Using a list index where the current value is a dictionary.
A dictionary is accessed through keys, not list positions.
Fix:
Use the appropriate dictionary key, such as parsed['users'], when the top-level value is a dictionary.Accessing a field that does not exist.
The requested key may not be present in the parsed dictionary.
Fix:
Compare the requested key with the documented structure and inspect the parsed value to confirm its available fields.
Practice the Access Path
Given this code, identify the type of container at each step and predict the value printed by the final line: import json data = '{"groups": [{"members": ["Ari", "Bea"]}]}' parsed = json.loads(data) print(parsed['groups'][0]['members'][1])
Hints
- Start by identifying the top-level container.
- After selecting groups, determine whether the next step needs a key or an index.
- The final index selects the second element of the members list.
What do you think happens?
What will the final print statement output?
Reveal answer
Answer: Bea
parsed is a dictionary, groups contains a list, index 0 selects the first group dictionary, members contains a list, and index 1 selects its second element.
Key Takeaways
- json.loads() parses a JSON string and returns a new Python data structure; the original string remains unchanged.
- JSON objects correspond to Python dictionaries, and JSON arrays correspond to Python lists in the parsed structure.
- Use dictionary keys for dictionary levels and list indexes for list levels.
- Reliable access requires knowing the expected structure, which is why API documentation matters.
- When debugging, check the input, identify the parsed structure, and trace each access step separately.
Key Takeaways
- json.loads() transforms JSON text into a new Python object.
- The JSON shape guides the Python shape: objects become dictionaries and arrays become lists.
- Nested access combines dictionary keys and list indexes according to the structure at each level.
- You need advance knowledge of the expected data structure to navigate parsed JSON effectively.
- Layer-by-layer inspection is a practical way to diagnose parsing and access errors.