Reputation: 156
How can i retrieve all name and id from json file.This is a short version of my json file. I want to retrieve all names and id's so that i can match them with my variable. Then i can triger some work on it.So please help me to retrieve all Id and name. I searched in google but couldn't find. Every example was of single 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
}
}
]
Here's My Code:
import json
with open('city.list.json') as f:
data = json.load(f)
for p_id in data:
hay = p_id.get('name')
suppose,i got a word delhi, now i am comparing it with name in dictionary above. when it hits i want to retrieve it's id.
if hay == delhi:
ga = # retrieve delhi's id
Upvotes: 2
Views: 12545
Reputation: 411
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")
gives
519188
[Program finished]
Upvotes: 0
Reputation: 995
I would suggest a different approach, process the JSON data into a dict
and get the information you want from that. For example:
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])
And the results:
>>> print(id_by_name['Hurzuf'])
707860
>>> print(name_by_id['519188'])
Novinki
Upvotes: 0
Reputation: 1707
You need to check for name and apply a condition:
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
Upvotes: 3
Reputation: 1234
Not sure exactly on your output. But this extracts id and name in a new variable.
ids=[]
for p_id in data:
ids.append((p_id['id'], p_id['name']))
print(ids)
Output:
[(707860, 'Hurzuf'), (519188, 'Novinki'), (1283378, 'Gorkhā')]
Upvotes: 0