Home > OS >  Python (json) How to add every key of same name to the list
Python (json) How to add every key of same name to the list

Time:10-31

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"
            ]
        }
    ]
}

CodePudding user response:

for dog in jsondata["dogs"]:
    names.append(dog["name"])
    ages.append(dog["age"])

CodePudding user response:

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

CodePudding user response:

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

  • Related