我正在寻找从 OpenWeatherMaps http://bulk.openweathermap.org/sample/city.list.json.gz下载的 json 文件 city.list.json 创建位置的 python3 列表。该文件通过http://json-validator.com/,但我无法弄清楚如何正确打开文件并创建键“名称”的值列表。我不断遇到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
}
}
]
Run Code Online (Sandbox Code Playgroud)
有没有办法解析这个并创建一个列表["Hurzuf", "Novinki"]
?
你应该使用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']
Run Code Online (Sandbox Code Playgroud)
您只需简单地遍历列表中的元素并检查键是否等于name
。
归档时间: |
|
查看次数: |
3315 次 |
最近记录: |