2012-06-11 150 views
35
import json 

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

这是我的JSON数组,但我想将水果串中的所有值转换为Python列表。这样做的正确方法是什么?将JSON数组转换为Python列表

+2

你是什么意思? 'data ['fruits']'将成为一个列表 – jdi

+3

你有一个包含_Array_的JSON _Object_。 JSON数组与Python的'list'是同源的。 JSON _Object_与Python'dict'同源。从技术上讲,你有一个'dict'包含一个键值对,其中的值是一个字符串'list'。 –

回答

62
import json 

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

你有你需要的一切。 data将是一个字典,并data['fruits']将是一个列表

+1

哦,对。我认为只会从对象中获取单个字符串,而不是数组。谢谢! – user1447941

+0

@ user1447941:没问题。解码器将把所有json对象翻译成它们的python内置对象对象。 – jdi

+0

你是不是指'print(data ['fruits'])',因为你的代码只适用于()我的数据:)( –

10

Tested on Ideone.


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