Python Json To List
Last Updated :
08 Feb, 2024
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.
Python
import json
string = "[1,2,3,4]"
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.
Python
import pandas as pd
string = '{"names":["Harsha","Krishna","Vardhan"],"subject":["Physics","Maths","Java"]}'
dataFrame = pd.read_json(string)
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.
Python3
import json
string = '[{"name" : "Harsha", "subject" : "Physics" , "Code" : "java" }]'
list1 = json.loads(string)
another_list = [ i for i in list1[ 0 ]]
print ( type (string))
print (another_list)
print ( type (another_list))
|
Output
<class 'str'>
['name', 'subject', 'Code']
<class 'list'>
Share your thoughts in the comments
Please Login to comment...