I have the following JSON array:
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
In this case, I want to convert all the values in the ‘fruits’ string to a Python list. What is the correct way of doing this using Python JSON to list?
You already have what you need. After using json.loads(), the result is a dictionary, and accessing data[‘fruits’] will give you a Python list.
For example:
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
print(data['fruits'])
The output will be:
['apple', 'banana', 'orange']
You can directly access the list after parsing the JSON:
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
fruits_list = data.get('fruits', [])
print(fruits_list)
Another way is by using the json.load() function if you’re reading the data from a file:
import json
with open('data.json', 'r') as f:
data = json.load(f)
fruits_list = data['fruits']
print(fruits_list)