如何从json key创建一个列表:python3中的值

时间:2017-08-12 23:15:59

标签: json python-3.x

我正在寻找从OpenWeatherMaps http://bulk.openweathermap.org/sample/city.list.json.gz下载的json文件city.list.json创建一个python3列表。该文件传递http://json-validator.com/,但我无法弄清楚如何正确打开文件并创建键'name'的值列表。我一直在关于json.loads等的io.TextIOWrapper错误。

我创建了一个简短的测试文件

[
    {
        "id": 707860,
        "name": "Hurzuf",
        "country": "UA",
        "coord": {
            "lon": 34.283333,
            "lat": 44.549999
        }

    }
    ,
    {
        "id": 519188,
        "name": "Novinki",
        "country": "RU",
        "coord": {
            "lon": 37.666668,
            "lat": 55.683334
        }

    }
]

有没有办法解析它并创建列表["Hurzuf", "Novinki"]

1 个答案:

答案 0 :(得分:3)

您应该使用json.load()代替json.loads()。我将我的测试文件file.json命名为以下代码:

import json


with open('file.json', mode='r') as f:
    # At first, read the JSON file and store its content in an Python variable
    # By using json.load() function

    json_data = json.load(f)

    # So now json_data contains list of dictionaries
    # (because every JSON is a valid Python dictionary)

# Then we create a result list, in which we will store our names
result_list = []

# We start to iterate over each dictionary in our list
for json_dict in json_data:
    # We append each name value to our result list
    result.append(json_dict['name'])

print(result_list)  # ['Hurzuf', 'Novinki']

# Shorter solution
# By using list comprehension

result_list = [json_dict['name'] for json_dict in json_data]

print(result_list)  # ['Hurzuf', 'Novinki']

您只需遍历列表中的元素并检查密钥是否等于name