Reputation: 576
this is my json files
{
"people1": [
{
"name":"William",
"age": "20",
"location": "Bali"
},
{
"name":"Jose",
"age": "30",
"location": "Canada"
}
]
}
Lets say i want to get the age and location of ''William'' only. How would I do it? for now this is my code but I can't seem to get it.
code.py
import json
with open("names.json") as json_file:
data = json.load(json_file)
for item in data["people1"]:
print(item["name"])
Upvotes: 1
Views: 48
Reputation: 793
You do a simple for loop
for i in data['people1']:
if i['name'] == 'William':
print(i['age'])
Upvotes: 1
Reputation: 15478
You can try like this:
import json
j_ = '''{
"people1": [
{
"name":"William",
"age": "20",
"location": "Bali"
},
{
"name":"Jose",
"age": "30",
"location": "Canada"
}
]
}'''
j = json.loads(j_)
for x in j['people1']:
if x['name'] == 'William':
print(x['age'])
print(x['location'])
Upvotes: 1
Reputation: 123
Loop through your data looking for William and then do what you like with his data.
for item in data["people1"]:
if item["name"] == "William":
print(item["age"])
print(item["location"])
Upvotes: 3