API Navigator Logo

How to Parse JSON in Python

Author: Newtum

This guide covers how to parse a JSON string and convert it into a Python dictionary using the built-in `json` module. This is a fundamental task when working with APIs.

Using `json.loads()`

The `json.loads()` (load string) function takes a JSON formatted string as input and returns a Python object (usually a dictionary or a list).

import json

json_string = '{"name": "Alice", "age": 25, "city": "New York"}'

# Parse the JSON string into a Python dictionary
data = json.loads(json_string)

print(type(data))
print(data)
print('Name:', data['name'])

Handling JSON Arrays

If the JSON string represents an array, `json.loads()` will return a Python list.

import json

json_array_string = '[1, 2, 3, "apple", "banana"]'

# Parse the JSON array string into a Python list
data_list = json.loads(json_array_string)

print(type(data_list))
print(data_list)
print('First element:', data_list[0])

Parsing from a File

To parse JSON from a file, use `json.load()` (without the 's'), which reads from a file-like object.

import json

# Assume 'data.json' contains: {"key": "value"}
# with open('data.json', 'r') as f:
#     data = json.load(f)
#     print(data)

# This is a simulation since we can't read files here
from io import StringIO
file_content = '{"product": "Laptop", "price": 1200}'
data_from_file = json.load(StringIO(file_content))
print(data_from_file)