从python中的JSON文件创建纯python列表的更好方法

Question_bank

我有一个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']

有一个更好的方法吗?

ak_slick

我认为,如果将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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章