我希望从从python3 http://bulk.openweathermap.org/sample/city.list.json.gz下载的json文件city.list.json中创建一个位置列表。该文件传递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"]
?
发布于 2017-08-13 01:00:00
您应该使用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_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
。
https://stackoverflow.com/questions/45655721
复制