簡體   English   中英

遍歷JSON [Python]

[英]Iterate through JSON [Python]

我正在用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並獲取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)

問題是,當我取消注釋應該獲得屬性對象類型的底部兩行時,出現錯誤:

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

遍歷字典會產生其鍵。 properties是一個字典:

properties = data["properties"]

當您遍歷以下內容時:

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

property依次引用每個鍵。 因為您的字典代表JSON數據,所以鍵是字符串,並且錯誤很容易說明。 property["type"]試圖從索引"type"處的字符串中獲取字符。

相反,您應該使用key 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM