我有一个JSON
文件Python
。文件内容如下。
{
"cities": [
"NY",
"SFO",
"LA",
"NJ"
],
"companies": [
"Apple",
"Samsung",
"Walmart"
],
"devices": [
"iphone",
"ipad",
"ipod",
"watch"
]
}
我想Python
从该JSON
文件创建列表。我做了如下。
# Open JSON file in Python
with open('test.json') as out_file:
test_data = json.load(out_file)
# Query the output variable test_data
test_data
{u'cities': [u'NY', u'SFO', u'LA', u'NJ'], u'companies': [u'Apple', u'Samsung', u'Walmart'], u'devices': [u'iphone', u'ipad', u'ipod', u'watch']}
# find type of test_data
type(test_data)
<type 'dict'>
# create list from test_data
device = test_data['devices']
# Check content of list created
device
[u'iphone', u'ipad', u'ipod', u'watch']
现在,如您所见,列表是一个unicode list
我希望它是纯Python
列表。
我可以像下面这样
device_list = [str(x) for x in device]
device_list
['iphone', 'ipad', 'ipod', 'watch']
有一个更好的方法吗?
我认为,如果将json.load更改为json.loads,它将解决您的问题。删除任何需要的地图。
试试这个。
import jason
import yaml
f = open('temp.json', 'r')
json_str = f.read()
content = json.loads(json_str)
# this should remove all the unicode and return a dictionary
content = yaml.load(json.dumps(content))
content
{'cities': ['NY', 'SFO', 'LA', 'NJ'], 'companies': ['Apple', 'Samsung', 'Walmart'], 'devices': ['iphone', 'ipad', 'ipod', 'watch']}
content['devices']
['iphone', 'ipad', 'ipod', 'watch']
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句