Georgi Koemdzhiev Georgi Koemdzhiev - 5 months ago 45
JSON Question

Iterate through JSON [Python]

I am reading the following JSON file in python:

{
"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. 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

Answer

Iterating over a dictionary yields its keys. properties is a dictionary:

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. As your dictionary represents JSON data, the keys are strings and the error is quite self explanatory. property["type"] is trying to get a character from the string at the indice "type".

Instead you should either use the key property to fetch additional values from the dictionary:

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)
Comments