如何从json文件中检索所有名称和ID。这是json文件的简短版本。我想检索所有名称和ID,以便我可以将它们与变量匹配。然后,我可以对它进行一些工作。因此,请帮助我检索所有ID和名称。我在Google中搜索,但找不到。每个示例都是单个json。
[
{
"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
}
},
{
"id": 1283378,
"name": "Gorkhā",
"country": "NP",
"coord": {
"lon": 84.633331,
"lat": 28
}
}
]
这是我的代码:
import json
with open('city.list.json') as f:
data = json.load(f)
for p_id in data:
hay = p_id.get('name')
假设我有一个单词德里,现在我将它与上面词典中的名称进行比较。当它命中时,我想检索它的ID。
if hay == delhi:
ga = # retrive delhi's id
答案 0 :(得分:1)
您需要检查姓名并应用条件:
for p_id in data:
u_id = p_id.get('id')
u_name = p_id.get('name')
if(u_id == 1283378 and u_name == "Gorkha"):
# dosomthing
答案 1 :(得分:0)
不确定确切的输出。但这会在新变量中提取id和name。
ids=[]
for p_id in data:
ids.append((p_id['id'], p_id['name']))
print(ids)
输出:
[(707860, 'Hurzuf'), (519188, 'Novinki'), (1283378, 'Gorkhā')]
答案 2 :(得分:0)
我建议采用另一种方法,将JSON数据处理为dict
,然后从中获取所需的信息。例如:
import json
with open('city.list.json') as f:
data = json.load(f)
name_by_id = dict([(str(p['id']), p['name']) for p in data])
id_by_name = dict([(p['name'], p['id']) for p in data])
结果:
>>> print(id_by_name['Hurzuf'])
707860
>>> print(name_by_id['519188'])
Novinki
答案 3 :(得分:0)
import json
with open('citylist.json') as f:
data = json.load(f)
list1 = list ((p_id.get('id') for p_id in data if p_id.get('name') == "Novinki"))
# you can put this in print statement,
# but since goal is to save and not just print,
# you can store in a variable
print(*list1, sep="\n")
给予
519188
[Program finished]