3

I need to add every value from key name and from key age to the list

But after start of this code there is:

for i in len(jsondata['name']): builtins.KeyError: 'name'

But you see that I have "name": "husky", and "name": "shiba inu", in second one. So what would you rewrite?

Thank you

import json

names=[]
ages=[] 


#f = open('jsondata.json')

with open('jsondata.json') as fp:
    jsondata = json.load(fp)


for i in len(jsondata['name']):
    names.add(jsondata['name'])

for i in len(jsondata['age']):
    ages.add(jsondata['age'])

f.close()

Json file:

{
    "dogs": [
        {
            "name": "husky",
            "age": "12",
            "urls": [
                "https://www.dailypaws.com/dogs-puppies/dog-names/husky-names",
                "https://www.tonbridgehuskymalamutewalkinggroup.co.uk/"
            ]
        },
        {
            "name": "shiba inu",
            "age": "3",
            "urls": [
                "https://www.cryptoglobe.com/latest/2021/10/shiba-inu-shib-listed-on-trading-app-with-over-one-million-users/",
                "https://www.purina.co.uk/find-a-pet/dog-breeds/japanese-shibu-inu"
            ]
        }
    ]
}

3 Answers 3

1
for dog in jsondata["dogs"]:
    names.append(dog["name"])
    ages.append(dog["age"])
Sign up to request clarification or add additional context in comments.

Comments

0

You need to get the nested order. As you see, the key 'name' is under 'dogs', then the key 'name' does not exist under . Thus, you need to call it as

for i in range(len(jsondata['dogs'])):
    names.append(jsondata['dogs'][i]['name'])

If you want to get the entries

3 Comments

The 'dogs' field contains a list?
To which line do you think?
Edited that. The 'dogs' field is indeed contains a list.
0

You should apply the loop over dogs element

name = []
age = []
data = """{
  "dogs": [
    {
      "name": "husky",
      "age": "12",
      "urls": [
        "https://www.dailypaws.com/dogs-puppies/dog-names/husky-names",
        "https://www.tonbridgehuskymalamutewalkinggroup.co.uk/"
      ]
    },
    {
      "name": "shiba inu",
      "age": "3",
      "urls": [
        "https://www.cryptoglobe.com/latest/2021/10/shiba-inu-shib-listed-on-trading-app-with-over-one-million-users/",
        "https://www.purina.co.uk/find-a-pet/dog-breeds/japanese-shibu-inu"
      ]
    }
  ]
}"""
    for m in data['dogs']:
        u_name= name.append(m.get('name','N/A'))
        u_age = age.append(m.get('age','N/A'))

m.get('age','N/A') statement will work as an if-else statement in JSON

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.