如何使此JSON结构按预期工作?

时间:2019-04-12 08:11:04

标签: python json

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

这不是我将要使用的数据,但是它具有相同的结构,“官方”数据是一些临时信息,因此我将其更改为一些随机值。我无法更改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

2 个答案:

答案 0 :(得分:1)

您需要的是

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

答案 1 :(得分:0)

Python for循环不会返回键,而是返回一个对象:

for x in data:

将对象作为键

print(data['persons'][x]['name'])

正在导致错误

您需要使用返回的json对象,并像这样遍历它们:

for x in data['persons']:
print(x['name'])
for vehicle in x['things']['Vehicles']:
    print(vehicle['type']['name'])
print('\n')