Handling JSON Parsing Errors and Exceptions
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
JSON often arrives as text. The function json.loads() reads that JSON string and builds a corresponding Python data structure. The result might contain lists, dictionaries, and primitive values. The original string does not change, so you should assign the returned Python object to a variable before working with it.
Tracing Nested User Data
Reading the First User's Name
A JSON string represents a list of users. Each user has the fields id, x, and name. How do you reach the first user's name after parsing?
Parse the string: Pass the JSON string to json.loads(). The outer square brackets describe a list, so the result is a Python list.
Select the first item: Use index 0 to select the first dictionary in the list.
Select the name field: Use the key name on that dictionary to reach the user's name value.
The nested access pattern is info[0]['name']. For the generated example below, this produces Chuck.
import json data = '[{"id": 1, "x": 10, "name": "Chuck"}, {"id": 2, "x": 20, "name": "Ada"}]' info = json.loads(data) print(type(info).__name__) print(len(info)) print(info[0]) print(info[0]['name'])
JSON and Python Representations
A JSON string and the Python object produced from it are different representations. Before parsing, the data is text. After json.loads() returns, Python has built a new object that can be navigated with Python syntax. The text remains unchanged, while the returned object is the value you inspect and access.
| JSON form | Python structure after parsing |
|---|---|
| Object described by curly braces | Dictionary |
| Array described by square brackets | List |
| JSON string value | Python string value |
| JSON number value | Python numeric value |
| JSON boolean or null value | Python primitive value |
Diagnosing Parse and Access Failures
When parsing fails or the result is not what you expected, trace the operation in stages. First verify that the input is actually a string and contains valid JSON. Next confirm that you understand the structure of the parsed result. Finally check that your field names and indices match that structure. This separates a problem with parsing from a problem with accessing the parsed value.
Forgetting to import json
The name json has not been made available to the program.
Fix:
Import the json module before calling json.loads().Passing a non-string object to json.loads()
json.loads() is used to parse a JSON string.
Fix:
Verify that the input is a string containing JSON before parsing.Using a field name that does not exist
The access expression does not match the structure represented by the JSON data.
Fix:
Inspect the parsed structure and confirm the exact field names.Using the wrong navigation order
The access syntax must match the structure created by parsing.
Fix:
Determine whether each layer is a list or dictionary, then use an index or key accordingly.
Why Documentation Matters
JSON is more concise than XML, but it is also less self-describing. The text contains fewer clues about what each value represents. To navigate a parsed response correctly, you need to know whether the outer structure is a list or dictionary, what each nested item contains, and which keys are available. API documentation provides this expected structure.
Suppose parsing produces a list whose first element is a dictionary with the key name. Write the access expression that reaches the name value of the first element.
Hints
- Use index 0 for the first list element.
- Use the key name for the dictionary field.
- Combine the two access operations.
What do you think happens?
After parsing a JSON string whose outer value is a list of two user dictionaries, what does len(info) report?
Reveal answer
Answer: 2
The outer square brackets represent a list containing two user dictionaries, so the list has two elements.
A Reliable Parsing Routine
- Confirm that the json module is imported.
- Confirm that the value passed to json.loads() is a string containing JSON.
- Assign the return value of json.loads() to a variable.
- Determine whether the parsed result is organized as a list, dictionary, or another Python value.
- Use list indices and dictionary keys that match the documented structure.
- If an error occurs, inspect each layer step by step to find where your expectation differs from the actual structure.
Key Takeaways
- json.loads() parses a JSON string and returns a new Python data structure; the original string remains unchanged.
- The outer JSON shape determines whether the result begins as a Python list, dictionary, or another value.
- Nested access requires the correct combination of list indices and dictionary keys.
- JSON is concise but less self-describing, so documentation is important when navigating a response.
- Debug parsing problems in stages: verify the input, inspect the parsed structure, and then check each access key or index.