Skip to main content
 首页 » 编程设计

python之我如何使这个 JSON 结构按预期工作

2024年11月24日8lautakyan007

我有一个项目的一些数据,其中变量可以从摩托车和汽车改变。我需要从它们中获取名称,并且该值在变量中。

这不是我要使用的数据,但它具有相同的结构,“官方”数据是一些个人信息,因此我将其更改为一些随机值。我无法更改 JSON 数据的结构,因为这是服务器管理员出于某种原因决定构建它的方式。

这是我的 python 代码:

import json 
with open('exampleData.json') as j: 
    data = json.load(j) 
 
name = 0 
Vehicle = 0 
for x in data: 
    print(data['persons'][x]['name']) 
    for i in data['persons'][x]['things']["Vehicles"]: 
        print(data['persons'][x]['things']['Vehicles'][i]['type']['name']) 
    print("\n") 

这是我从“ExampleData.json”文件中提取的 Json 数据(很抱歉,它有点复杂,是理解问题所必需的):

{ 
  "total": 2, 
  "persons": [ 
    { 
      "name": "Sven Svensson", 
      "things": { 
        "House": "apartment", 
        "Vehicles": [ 
          { 
            "id": "46", 
            "type": { 
              "name": "Kawasaki ER6N", 
              "type": "motorcyle" 
            }, 
            "Motorcycle": { 
              "plate": "aaa111", 
              "fields": { 
                "brand": "Kawasaki", 
                "status": "in shop" 
              } 
            } 
          }, 
          { 
            "id": "44", 
            "type": { 
              "name": "BMW m3", 
              "type": "Car" 
            }, 
            "Car": { 
              "plate": "bbb222", 
              "fields": { 
                "brand": "BMW", 
                "status": "in garage" 
              } 
            } 
          } 
        ] 
      } 
    }, 
    { 
      "name": "Eric Vivian Matthews", 
      "things": { 
        "House": "House", 
        "Vehicles": [ 
          { 
            "id": "44", 
            "type": { 
              "name": "Volvo XC90", 
              "type": "Car" 
            }, 
            "Car": { 
              "plate": "bbb222", 
              "fields": { 
                "brand": "Volvo", 
                "status": "in garage" 
              } 
            } 
          } 
        ] 
      } 
    } 
  ] 
} 

我想让它打印出这样的东西:

Sven Svensson 
Bmw M3 
Kawasaki ER6n 
 
Eric Vivian Matthews 
Volvo XC90 

但是我得到这个错误:

    print(data['persons'][x]['name']) 
TypeError: list indices must be integers or slices, not str 
 
Process finished with exit code 1 

请您参考如下方法:

你需要的是

for person in data["persons"]: 
    for vehicle in person["things"]["vehicles"]: 
        print(vehicle["type"]["name"]) 
        type = vehicle["type"]["type"] 
        print(vehicle[type]["plate"])