迭代JSON [Python]

时间:2016-06-28 09:27:27

标签: python json

我正在python中阅读以下JSON文件:

    {
  "name": "Property",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "uuid": {
      "type": "string"
    },
    "userID": {
      "type": "number"
    },
    "address": {
      "type": "string"
    },
    "price": {
      "type": "number"
    },
    "lastUpdated": {
      "type": "string"
    }
  },
  "validations": [],
  "relations": {
    "rooms": {
      "type": "hasMany",
      "model": "Room",
      "foreignKey": "id"
    },
    "addedByUser": {
      "type": "hasMany",
      "model": "User_ESPC",
      "foreignKey": "id"
    }
  },
  "acls": [],
  "methods": {}
}

我正在尝试阅读properties并获取属性的名称(例如" uuid"),并且我想要读取每个名称的对象类型。到目前为止,我的代码列出了所有类似的属性:

Property name: price
Property name: userID
Property name: uuid
Property name: lastUpdated
Property name: address

执行此操作的代码是:

import json

#json_file='a.json'
json_file='common/models/property.json'
with open(json_file, 'r') as json_data:
    data = json.load(json_data)


propertyName = data["name"]
properties = data["properties"]

# print (properties)

for property in properties:
    print ('Property name: ' + property)
    # propertyType = property["type"]
    # print (propertyType)

问题是,当我取消注释应该获取属性对象类型的底部2行时,我得到一个错误:

Property name: price
Traceback (most recent call last):
File "exportPropertyToAndroid.py", line 19, in <module>
propertyType = property["type"]
TypeError: string indices must be integers

1 个答案:

答案 0 :(得分:1)

迭代字典会产生密钥。 properties是一本字典:

properties = data["properties"]

当你在以下地方迭代它时:

for property in properties:
    print ('Property name: ' + property)
    # propertyType = property["type"]
    # print (propertyType)

property依次引用每个密钥。由于您的字典代表JSON数据,因此键是字符串,错误是非常自我解释的。 property["type"]正试图从indice "type"的字符串中获取一个字符。

相反,您应该使用密钥property从字典中获取其他值:

for property in properties:
    print ('Property name: ' + property)
    propertyType = properties[property]["type"]
    print(propertyType)

或迭代键和值:

for property, value in properties.items():
    print ('Property name: ' + property)
    propertyType = value["type"]
    print(propertyType)