[英]Iterate through JSON [Python]
I am reading the following JSON file in 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": {}
}
I am trying to read the properties
and get the name of the property (such as "uuid") and for each name I want to read the type of the object. 我正在尝试读取
properties
并获取properties
的名称(例如“ uuid”),对于每个名称,我想读取对象的类型。 So far my code lists all of the properties like that: 到目前为止,我的代码列出了所有类似的属性:
Property name: price
Property name: userID
Property name: uuid
Property name: lastUpdated
Property name: address
The code that does that is: 这样做的代码是:
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)
The problem is when I uncomment the bottom 2 lines which should get the type of the property object I get an error: 问题是,当我取消注释应该获得属性对象类型的底部两行时,出现错误:
Property name: price
Traceback (most recent call last):
File "exportPropertyToAndroid.py", line 19, in <module>
propertyType = property["type"]
TypeError: string indices must be integers
Iterating over a dictionary yields its keys. 遍历字典会产生其键。
properties
is a dictionary: properties
是一个字典:
properties = data["properties"]
and when you iterate over it in: 当您遍历以下内容时:
for property in properties:
print ('Property name: ' + property)
# propertyType = property["type"]
# print (propertyType)
property
references each key in turn. property
依次引用每个键。 As your dictionary represents JSON data, the keys are strings and the error is quite self explanatory. 因为您的字典代表JSON数据,所以键是字符串,并且错误很容易说明。
property["type"]
is trying to get a character from the string at the indice "type"
. property["type"]
试图从索引"type"
处的字符串中获取字符。
Instead you should either use the key property
to fetch additional values from the dictionary: 相反,您应该使用key
property
从字典中获取其他值:
for property in properties:
print ('Property name: ' + property)
propertyType = properties[property]["type"]
print(propertyType)
or iterate over keys and values: 或遍历键和值:
for property, value in properties.items():
print ('Property name: ' + property)
propertyType = value["type"]
print(propertyType)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.