Iterate through JSON [Python] -


i reading 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 trying read properties , name of property (such "uuid") , each name want read type of object. far code lists of properties that:

property name: price property name: userid property name: uuid property name: lastupdated property name: address 

the code is:

import json  #json_file='a.json' json_file='common/models/property.json' open(json_file, 'r') json_data:     data = json.load(json_data)   propertyname = data["name"] properties = data["properties"]  # print (properties)  property in properties:     print ('property name: ' + property)     # propertytype = property["type"]     # print (propertytype) 

the problem when uncomment bottom 2 lines should type of property object error:

property name: price traceback (most recent call last): file "exportpropertytoandroid.py", line 19, in <module> propertytype = property["type"] typeerror: string indices must integers 

iterating on dictionary yields keys. properties dictionary:

properties = data["properties"] 

and when iterate on in:

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

property references each key in turn. dictionary represents json data, keys strings , error quite self explanatory. property["type"] trying character string @ indice "type".

instead should either use key property fetch additional values dictionary:

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

or iterate on keys , values:

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

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -