Convert JSON array to a Python List

In this tutorial, you’ll learn how to convert JSON arrays to Python lists.

From using standard libraries like json and ast to leveraging third-party modules such as Pandas.

 

 

Using json Module

Python’s json module allows you to load JSON data from a file and convert it into a Python list.

First, ensure you have a JSON file. For this example, the file is named data.json and contains a JSON array:

["Call", "Message", "Data", "Network"]

Now, let’s write the Python code to load this JSON data from the file:

import json
with open('data.json', 'r') as file:
    json_data = json.load(file)
print(json_data)

Output:

['Call', 'Message', 'Data', 'Network']

In this code, open() is used to open the file in read mode ('r'). The json.load() function then reads the file and converts the JSON array into a Python list.

 

Using ast.literal_eval

Another method to convert a JSON array to a Python list is by using the ast.literal_eval function from the ast module.

This approach is useful when the JSON data is in a string format and you’re certain about its safety, as ast.literal_eval can evaluate a string containing a Python literal or container display.

import ast
json_like_data = '["Call", "Message", "Data", "Network"]'
python_list = ast.literal_eval(json_like_data)
print(python_list)

Output:

['Call', 'Message', 'Data', 'Network']

In this example, ast.literal_eval is used to safely evaluate the string containing a Python list-like structure. It parses the string and returns the Python list equivalent.

This function is safer than eval() as it only evaluates literals and not arbitrary code.

 

Using Pandas

Let’s assume we have a JSON file named data.json, which contains the following:

["Call", "Message", "Data", "Network"]

To convert this JSON array into a Python list using Pandas, follow these steps:

import pandas as pd
df = pd.read_json('data.json')
python_list = df[0].tolist()
print(python_list)

Output:

['Call', 'Message', 'Data', 'Network']

In this code, pd.read_json() reads the JSON file and converts it into a Pandas DataFrame. The tolist() method is then used to convert the DataFrame column into a Python list.

 

Using List Comprehension To Extract Value

Let’s say we have a JSON array containing like this:

[{"service": "Call", "active": true}, {"service": "Message", "active": false}, {"service": "Data", "active": true}, {"service": "Network", "active": true}]

To convert this JSON array into a Python list using list comprehension, the process is as follows:

import json
json_data = '[{"service": "Call", "active": true}, {"service": "Message", "active": false}, {"service": "Data", "active": true}, {"service": "Network", "active": true}]'
data = json.loads(json_data)
services_list = [item['service'] for item in data if item['active']]
print(services_list)

Output:

['Call', 'Data', 'Network']

In this example, list comprehension is used to iterate over each item in the data list (which was converted from JSON) and extract the value associated with the key 'service' only if the 'active' key is true.

 

Converting Nested JSON Array into Nested Python List

Converting these nested structures into nested Python lists can be done using recursive functions or list comprehension.

Suppose we have a JSON array representing a hierarchical structure like this:

[["Call", ["International", "Local"]], ["Data", ["4G", "5G"]], ["Message", []]]

To convert this nested JSON array into a nested Python list, we’ll use a recursive function:

import json
json_data = '[["Call", ["International", "Local"]], ["Data", ["4G", "5G"]], ["Message", []]]'
data = json.loads(json_data)
def convert_to_nested_list(data):
    if isinstance(data, list):
        return [convert_to_nested_list(item) for item in data]
    else:
        return data
nested_list = convert_to_nested_list(data)
print(nested_list)

Output:

[['Call', ['International', 'Local']], ['Data', ['4G', '5G']], ['Message', []]]

In this code, convert_to_nested_list is a recursive function that checks whether an element is a list. If it is, the function is called recursively for each element within that list.

This process converts each level of the nested JSON array into a corresponding nested Python list.

Leave a Reply

Your email address will not be published. Required fields are marked *