How to Get Values from a JSON Array in Python?

In this tutorial, I will explain how to extract values from a JSON array using Python. JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. Python provides a built-in module called json that allows you to work with JSON data effortlessly.

As a developer for a client based in the USA, I recently faced a challenge where I needed to parse a large JSON dataset and extract specific key-value pairs from each object within an array. In this article, I will share how to get values from a JSON array in Python using different methods and examples.

What is JSON Arrays?

Let me explain first what a JSON array looks like. A JSON array is represented by square brackets [] and contains a list of values. These values can be of various types, such as strings, numbers, objects, or even nested arrays. Here’s an example of a JSON array containing information:

[
  {
    "name": "California",
    "capital": "Sacramento",
    "population": 39512223
  },
  {
    "name": "Texas",
    "capital": "Austin",
    "population": 28995881
  },
  {
    "name": "Florida",
    "capital": "Tallahassee",
    "population": 21477737
  }
]

Read How to Convert a Tuple to JSON in Python?

Parsing JSON Data in Python

To work with JSON data in Python, we need to use the json module. This module provides functions to parse JSON strings and convert them into Python objects. Let’s see how to load JSON data from a file and parse it using Python.

First, make sure you have the JSON file saved on your local machine. For this example, let’s assume the JSON data is stored in a file named states.json.

import json

# Load JSON data from file
with open('C:/Users/fewli/Downloads/Python/states.json') as file:
    data = json.load(file)

# Print the parsed JSON data
print(data)

In this code snippet, we open the states.json file using the with statement, which ensures that the file is properly closed after reading. We then use the json.load() function to parse the JSON data and store it in the data variable. Finally, we print the parsed data to verify that it has been loaded correctly.

I executed the above Python code; you can see the output in the screenshot.

Get Values from a JSON Array in Python

Read Python Nested Dictionary to JSON

Accessing Values from a JSON Array

Now that we have the JSON data loaded into a Python variable let’s explore how to access specific values from the array. Python provides various ways to iterate through an array and extract the desired information.

Using a For Loop

One common approach to iterate through a JSON array is using a for loop. This allows you to access each object in the array one by one. Here’s an example:

import json

# Load JSON data from file
with open('C:/Users/fewli/Downloads/Python/states.json') as file:
    data = json.load(file)

for state in data:
    print("State:", state['name'])
    print("Capital:", state['capital'])
    print("Population:", state['population'])
    print('---')

In this code, we use a for loop to iterate over each object in the data array. We can access the individual values of each object using the corresponding keys, such as state['name'], state['capital'], and state['population']. The output will be:

State: California
Capital: Sacramento
Population: 39512223
---
State: Texas
Capital: Austin
Population: 28995881
---
State: Florida
Capital: Tallahassee
Population: 21477737
---

Here is the exact output in the screenshot below:

Accessing Values from a JSON Array in Python

Check out How to Convert a DataFrame to JSON Array in Python

Using List Comprehension

Let me show you another way to extract values from a JSON array is: by using list comprehension. List comprehension allows you to create a new list based on an existing list or iterable. Here’s an example:

import json

# Load JSON data from file
with open('C:/Users/fewli/Downloads/Python/states.json') as file:
    data = json.load(file)

state_names = [state['name'] for state in data]
print("State Names:", state_names)

In this code, we use list comprehension to create a new list called state_names that contains only the names of the states. The output will be:

State Names: ['California', 'Texas', 'Florida']

Here is the exact output in the screenshot below:

Python Get Values from a JSON Array

Read How to Convert a DataFrame to JSON in Python?

Handling Nested JSON Arrays

Sometimes, JSON data can have nested arrays, meaning an array inside another array. Accessing values from nested arrays requires an additional level of iteration. Let’s consider an example where we have a JSON array of US cities, and each city object contains an array of popular landmarks:

[
  {
    "name": "New York City",
    "landmarks": [
      "Statue of Liberty",
      "Central Park",
      "Empire State Building"
    ]
  },
  {
    "name": "Los Angeles",
    "landmarks": [
      "Hollywood Sign",
      "Griffith Observatory",
      "Venice Beach"
    ]
  }
]

To access the landmarks for each city, we can use nested loops:

for city in data:
    print("City:", city['name'])
    print("Landmarks:")
    for landmark in city['landmarks']:
        print("- ", landmark)
    print('---')

In this code, we first iterate over each city object in the data array using a for loop. Then, for each city, we access the landmarks array and use another for loop to iterate over each landmark. The output will be:

City: New York City
Landmarks:
-  Statue of Liberty
-  Central Park
-  Empire State Building
---
City: Los Angeles
Landmarks:
-  Hollywood Sign
-  Griffith Observatory
-  Venice Beach
---

Read Python Pretty Print JSON

Filtering JSON Data

In some cases, you may want to filter the JSON data based on certain conditions. Python provides several ways to filter arrays, such as using conditional statements or the filter() function. Let’s see an example of filtering states based on their population:

# Filter states with population greater than 30 million
filtered_states = [state for state in data if state['population'] > 30000000]

for state in filtered_states:
    print("State:", state['name'])
    print("Population:", state['population'])
    print('---')

In this code, we use list comprehension with a conditional statement to create a new list called filtered_states that contains only the states with a population greater than 30 million. We then iterate over the filtered_states list and print the state name and population. The output will be:

State: California
Population: 39512223
---

Conclusion

In this tutorial, I explained how to get values from a JSON array using Python. We learned how to parse JSON data, access values using loops and list comprehension, handle nested arrays, and filter data based on conditions.

JSON is a widely used data format, and Python provides powerful tools to work with it efficiently. By mastering these techniques, you can easily extract and manipulate data from JSON arrays in your Python projects.

I hope this tutorial has helped demonstrate how to get values from a JSON array using Python.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.