user1447941
user1447941

Reputation: 3905

Convert JSON array to Python list

import json

array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)

That is my JSON array, but I would want to convert all the values in the 'fruits' string to a Python list. What would be the correct way of doing this?

Upvotes: 106

Views: 452841

Answers (4)

Sagar Hatekar
Sagar Hatekar

Reputation: 8790

Tested on Ideone.

import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)
fruits_list = data['fruits']
print fruits_list

Upvotes: 15

cottontail
cottontail

Reputation: 23391

ast.literal_eval() from the Python standard library ast may be used to parse json strings as well.

It's especially useful if the string looks like a json but is actually a string representation of a Python object. In such cases, json.loads won't work but ast.literal_eval works.

import ast
array = '{"fruits": ("apple", "banana", "orange")}'
a = ast.literal_eval(array)  # {'fruits': ('apple', 'banana', 'orange')}
j = json.loads(array)        # JSONDecodeError

Upvotes: 3

noobprogrammer
noobprogrammer

Reputation: 109

data will return you a string representation of a list, but it is actually still a string. Just check the type of data with type(data). That means if you try using indexing on this string representation of a list as such data['fruits'][0], it will return you "[" as it is the first character of data['fruits']

You can do json.loads(data['fruits']) to convert it back to a Python list so that you can interact with regular list indexing. There are 2 other ways you can convert it back to a Python list suggested here

Upvotes: 0

jdi
jdi

Reputation: 92637

import json

array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)
print data['fruits']
# the print displays:
# [u'apple', u'banana', u'orange']

You had everything you needed. data will be a dict, and data['fruits'] will be a list

Upvotes: 165

Related Questions