如何从json文件中检索所有名称和id。这是我的json文件的一个简短版本。我想检索所有的名称和id,这样我就可以将它们与我的变量进行匹配。然后我可以触发一些工作。所以请帮我检索所有的Id和名称。我在谷歌上搜索了一下,但找不到。每个例子都是一个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 = # retrieve delhi's id
您需要检查名称并应用一个条件:
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
不确定您的输出。但这会在一个新变量中提取id和name。
ids=[]
for p_id in data:
ids.append((p_id['id'], p_id['name']))
print(ids)
输出:
[(707860, 'Hurzuf'), (519188, 'Novinki'), (1283378, 'Gorkhā')]
我建议一种不同的方法,将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
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]