JSON has become the standard format for data exchange on the web. So you’ll comfortably switch to JSON all the time when working with APIs, configuration files, database exports, and more. As a developer, you should know how to efficiently parse, manipulate, and generate JSON.
of the python Built-in JSON module JSON provides a straightforward interface for working with data. You’ll use it to convert JSON strings into Python dictionaries and lists that you can manipulate with familiar syntax, and then convert your Python data structures to JSON when you need to send data to an API or save it to a file.
Beyond basic analysis, you’ll often need to handle nested structures, validate data integrity, convert data formats. This guide covers practical JSON parsing techniques that you can use right now in your projects. Let’s begin!
🔗 You can find code examples on GitHub.
Conditions
To follow along with this tutorial, you should:
Python 3.7 or later installed on your system
Basic understanding of Python dictionaries and lists
Familiarity with Python file operations (opening and reading files)
A text editor or IDE for writing Python code
Table of Contents
Understanding JSON structure and basic parsing
JSON represents data using a simple syntax with six data types: Objects (key-value pairs), arrays, strings, numbers, booleans, And null.
When Python parses JSON, these types map directly to Python equivalents:
JSON objects become dictionaries,
Arrays became lists,
There are wires left in the wires,
The numbers become
intorfloatfor , for , for , .Became true and false
TrueAndFalseandbecomes NULL
None.
This direct mapping makes working with JSON intuitive once you understand the correspondence.
Before you begin, import json A module that is built into the Python standard library.
The basic operation in JSON parsing is converting a JSON string into a Python data structure that you can work with. Here’s how to perform this basic conversion:
import json
json_string = '{"name": "Sarah Chen", "age": 28, "city": "Portland"}'
person = json.loads(json_string)
print(person("name"))
print(person("age"))
print(type(person))
Output:
Sarah Chen
28
here, json.loads() The function takes a string containing JSON and returns a Python object. 's' i 'loads' stands for ‘string’, indicating that it works with string data. After parsing, you have a regular Python dictionary that you can access with bracket notation using JSON keys.
How to work with nested JSON objects
Real-world JSON data rarely comes in a flat structure. APIs typically return deeply nested objects that contain more than one level of data. Understanding how to navigate these structures is important to extracting the information you need.
Consider this example of analyzing the response of a weather API that includes location data and household objects for current conditions:
import json
weather_data = '''
{
"location": {
"city": "Seattle",
"state": "WA",
"coordinates": {
"latitude": 47.6062,
"longitude": -122.3321
}
},
"current": {
"temperature_f": 58,
"conditions": "Partly Cloudy",
"humidity": 72,
"wind": {
"speed_mph": 8,
"direction": "NW"
}
}
}
'''
weather = json.loads(weather_data)
After parsing with the JSON string json.loads()you can access nested values ​​by chaining dictionary keys together:
city = weather("location")("city")
temp = weather("current")("temperature_f")
wind_speed = weather("current")("wind")("speed_mph")
print(f"{city}: {temp}°F, Wind {wind_speed} mph")
Output:
Seattle: 58°F, Wind 8 mph
In this example, each level of nesting requires another set of brackets. expression weather("location")("city") Gets access first "location" object, then retrieves "city" value from within. You can drill down to as many levels as needed, eg weather("current")("wind")("speed_mph") which deepens three levels. This chaining syntax mirrors how you would access data in the original JSON structure.
How to parse json arrays
JSON arrays are represented by lists and often appear in API responses when returning collections of objects. Python converts JSON arrays into lists, which you can iterate through or access by index.
Here is an example of analyzing a product list from an inventory system:
import json
products_json = '''
(
{
"id": "PROD-001",
"name": "Wireless Mouse",
"price": 24.99,
"in_stock": true
},
{
"id": "PROD-002",
"name": "Mechanical Keyboard",
"price": 89.99,
"in_stock": false
},
{
"id": "PROD-003",
"name": "USB-C Hub",
"price": 34.99,
"in_stock": true
}
)
'''
products = json.loads(products_json)
A JSON string starts with a square bracket, which indicates an array at the root level. After parsing, the product is a Python list containing three dictionaries.
You can now use standard Python list operations on parsed data. len() The function returns the number of items, and you can iterate over the list for a loop. Each iteration gives you a dictionary containing a product representation, which you access using the dictionary syntax.
print(f"Total products: {len(products)}")
for product in products:
status = "Available" if product("in_stock") else "Out of stock"
print(f"{product('name')}: ${product('price')} - {status}")
Output:
Total products: 3
Wireless Mouse: $24.99 - Available
Mechanical Keyboard: $89.99 - Out of stock
USB-C Hub: $34.99 - Available
You can also access specific array elements by index and filter the data. List indexing works exactly as it does with any Python list, starting at zero.
first_product = products(0)
print(f"First product ID: {first_product('id')}")
Output:
First product ID: PROD-001
You can also use list comprehensions to filter the parsed data, creating a new list containing only products where the “in_stock” value is. True.
available_products = (p for p in products if p("in_stock"))
print(f"Available: {len(available_products)} products")
Output:
Available: 2 products
How to read JSON from files
Most applications read JSON from files rather than hardcoded strings. Configuration files, data exports, and cached API responses typically reside in JSON files that your application needs to load at runtime.
json Comes with module load A function for reading files that handles opening and parsing in one step.
This code creates a sample configuration file to demonstrate file reading:
import json
config_data = {
"api_url": "",
"timeout": 30,
"retry_attempts": 3,
"enable_logging": True
}
with open('config.json', 'w') as f:
json.dump(config_data, f, indent=2)
json.dump() The function writes Python data to a file, and indent=2 The parameter formats the JSON with 2-space indentation to make it human-readable. 'w' mode opens the file for writing, creating it if it does not exist or overwriting it if it does.
You can now read this file back into your application. json.load() function (without 's') reads from a file object and parses the JSON in one operation.
with open('config.json', 'r') as f:
config = json.load(f)
print(f"API URL: {config('api_url')}")
print(f"Timeout: {config('timeout')} seconds")
print(f"Logging: {'Enabled' if config('enable_logging') else 'Disabled'}")
Note the difference: json.loads() parse strings, while json.load() Reads from files.
with The statement ensures that the file is properly closed even if an error occurs during reading. After with block completes, you have a python dictionary containing all the parsed configuration data.
API URL:
Timeout: 30 seconds
Logging: Enabled
How to handle JSON parsing errors
JSON parsing can fail for many reasons: corrupted syntax when fetching from APIs, unexpected data types, corrupted files, or network issues. Your code must handle these errors gracefully instead of crashing.
json The module raises a JSONDecodeError When it runs in invalid JSON. Here’s how to properly catch and handle these errors.
try-except The block catches any JSON parsing errors:
JSONDecodeErrorThe exception provides detailed information about what went wrong:e.msgdescribes the error,e.linenoIndicates which line has the problem, ande.colnoIndicates the character’s position. This information helps you quickly debug JSON.The function returns
NoneWhen parsing fails, allows the calling code to check for it and handle the error appropriately.
Let’s test this with some JSON examples:
bad_json1 = '{"name": "Sarah, "age": 28}'
result1 = parse_json_safely(bad_json1)
print(f"Result 1: {result1}\n")
bad_json2 = '{"name": "Sarah", "age": 28'
result2 = parse_json_safely(bad_json2)
print(f"Result 2: {result2}\n")
bad_json3 = '{"name": "Sarah", "age": 28,}'
result3 = parse_json_safely(bad_json3)
print(f"Result 3: {result3}\n")
good_json = '{"name": "Sarah", "age": 28}'
result4 = parse_json_safely(good_json)
print(f"Result 4: {result4}")
Each corrupted JSON string triggers a different error message that indicates a specific syntax problem. Error messages indicate exactly where the JSON is incorrect. The final example shows that the valid JSON parses successfully and returns a dictionary instead None.
JSON parsing failed: Expecting ',' delimiter
Error at line 1, column 19
Result 1: None
JSON parsing failed: Expecting ',' delimiter
Error at line 1, column 28
Result 2: None
JSON parsing failed: Expecting property name enclosed in double quotes
Error at line 1, column 29
Result 3: None
Result 4: {'name': 'Sarah', 'age': 28}
When reading JSON files, you should also handle errors related to the file. The following function load_json_file_safely Handles three types of errors:
FileNotFoundErrorWhen the file does not exist,PermissionErrorWhen the application cannot read the file, andJSONDecodeErrorWhen the file contains invalid JSON. Each error type has its own exception block with an appropriate message.
The calling code checks if the result is None and returns to the default values, ensuring that the request will continue even when the file cannot be loaded.
import json
def load_json_file_safely(filepath):
try:
with open(filepath, 'r') as f:
return json.load(f)
except FileNotFoundError:
print(f"Error: File '{filepath}' not found")
return None
except PermissionError:
print(f"Error: Permission denied reading '{filepath}'")
return None
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON in '{filepath}'")
print(f" {e.msg} at line {e.lineno}")
return None
data = load_json_file_safely('missing_file.json')
if data is None:
print("Using default configuration")
data = {"timeout": 30, "retries": 3}
If you run the above code, you will get the following output:
Error: File 'missing_file.json' not found
Using default configuration
And it’s a wrap! Thank you for making it if you’re following along! 🥳
The result
json The module provides everything you need to work with JSON data in Python. Here’s a summary of what we covered:
Basic functions handle the most common tasks:
json.loads()Parse JSON into strings, and Python objectsjson.load()Reads and parses JSON from files.JSON parsing automatically converts between JSON and Python data types. This exchange lets you work with parsed JSON using standard Python syntax.
You can navigate nested JSON by chaining together dictionary keys and list indexes. Access the same as nested values
data('section')('subsection')('field')By following the structure below each level.Always wrap when parsing JSON
try-exceptblocks when working with external data.JSONDecodeErrorExceptions provide specific information about failures, including the location of the error, helping you quickly debug problems. When reading files, holdFileNotFoundErrorAndPermissionErrorTo gracefully handle common file access issues.
Get comfortable with these basics and you’ll be able to handle most of the JSON parsing tasks you’ll need for your Python projects. Happy coding!