首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何从json键创建列表: python3中的值

如何从json键创建列表: python3中的值
EN

Stack Overflow用户
提问于 2017-08-12 23:15:58
回答 1查看 4.2K关注 0票数 1

我希望从从python3 http://bulk.openweathermap.org/sample/city.list.json.gz下载的json文件city.list.json中创建一个位置列表。该文件传递http://json-validator.com/,但我不知道如何正确地打开文件并创建一个键值“name”的列表。我经常碰到json.loads关于io.TextIOWrapper等的错误。

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

代码语言:javascript
代码运行次数:0
运行
复制
[
    {
        "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"]

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-13 09:00:00

您应该使用json.load()而不是json.loads()。我将我的测试文件命名为file.json,下面是代码:

代码语言:javascript
代码运行次数:0
运行
复制
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_list.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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45655721

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档