0

Sample of the database:

"metros" : [
        {
            "code" : "SCL" ,
            "name" : "Santiago" ,
            "country" : "CL" ,
            "continent" : "South America" ,
            "timezone" : -4 ,
            "coordinates" : {"S" : 33, "W" : 71} ,
            "population" : 6000000 ,
            "region" : 1
        } , {
            "code" : "LIM" ,
            "name" : "Lima" ,
            "country" : "PE" ,
            "continent" : "South America" ,
            "timezone" : -5 ,
            "coordinates" : {"S" : 12, "W" : 77} ,
            "population" : 9050000 ,
            "region" : 1
        } 

I'm trying to print all city names. My code is:

Jdata = json.loads(self.data)
for i in Jdata["metros"]:
    print Jdata["name"]

But when I run this I'm getting "KeyError: 'name'"

What's the correct syntax to get the name of the cities?

2 Answers 2

4

Try:

for city in Jdata['metros']:
    print city['name']

When you use Jdata['name'], it tries to look for the key in metros, which obviously does not exist.

Sign up to request clarification or add additional context in comments.

Comments

1
{"metros":[{"code":"SCL","name":"Santiago","Region":"1"},{"code":"LIM","name":"Lima","Region":"1"}],
}

Then you can use your code:

import json
from pprint import pprint
json_data=open('json_data')

data = json.load(json_data)
pprint(data)
json_data.close()
With data, you can now also find values in like so:

data["metros"][1]["name"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.