[英]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.