Open In App

Python Json To List

JSON (JavaScript Object Notation) is a lightweight data-interchange format widely used in web development and data exchange. In Python, converting JSON to a list is a common task, and there are several methods available to achieve this. In this article, we will explore four simple and commonly used methods to convert JSON to a list in Python.

Convert Python JSON to List

Below, are the methods to convert Python JSON to List.



Convert Python Json To List Using JSON.loads() Method

In this example, the below code utilizes the `json.loads()` method to convert a JSON-formatted string `[1,2,3,4]` into a Python list named `array`. The `print` statements display the type of the original string, the first element of the resulting list, and the type of the converted list, respectively.




import json
#taking a string
string = "[1,2,3,4]"
 
#Passing the string into the json.loads() method
array = json.loads(string)
 
print(type(string))
print(array[0])
print(type(array))

Output

<type 'str'>
1
<type 'list'>

Convert Python Json To List Using Pandas library

In this example, below code uses the `pd.read_json()` method from the pandas library to read a JSON-formatted string into a DataFrame. The subsequent `print` statements display the type of the original string, the list of names extracted from the DataFrame, and the type of the resulting list, respectively.




import pandas as pd
#taking the json file .
 
string = '{"names":["Harsha","Krishna","Vardhan"],"subject":["Physics","Maths","Java"]}'
#using the read_json method in the pandas
dataFrame = pd.read_json(string)
#Converting into the list
 
print(type(string))
print(list(dataFrame["names"]))
print(type(list(dataFrame["names"])))

Output :

<class 'str'>
['Harsha', 'Krishna', 'Vardhan']
<class 'list'>

Convert Python Json To List Using List Comprehension

In this example, The code parses a JSON string containing a list of dictionaries using `json.loads()`. It then extracts the keys from the first dictionary in the list and prints the type of the original string, the extracted keys, and the type of the resulting list, respectively.




import json
#Parsing the JSON String
string = '[{"name" : "Harsha", "subject" : "Physics" , "Code" : "java" }]'
list1 = json.loads(string)
 
#Converting into the list
another_list = [ i for i in list1[0]]
 
#Extracting the keys in the dictionary
print(type(string))
print(another_list)
print(type(another_list))

Output
<class 'str'>
['name', 'subject', 'Code']
<class 'list'>

Article Tags :