Python (json) 如何将同名的每个键添加到列表中

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

我需要将键名和键龄的每个值添加到列表中

但是在这段代码开始之后有:

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

但是你看我有 "name": "husky","name": "shiba inu",第二个。那么你会重写什么?

谢谢

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 文件:

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

您需要获取嵌套顺序。如您所见,键'name'在'dogs'下,那么键'name'下不存在。因此,您需要将其称为

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

如果你想获取条目

您应该在 dogs 元素上应用循环

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') 语句将作为 if-else 语句在 JSON

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