SKTLZ
SKTLZ

Reputation: 183

Python and Json

I'm trying out json since I have to work with Cisco API and I can't figure out how to loop through the json object.I can get my keys but i can't get the values.

I am using http://www.jsoneditoronline.org/ to me understand json format but this is what I have so far..

json file :

{
  "queryResponse" : {
    "@rootUrl" : "\/webacs\/data",
    "@requestUrl" : "https : \/\/192.168.116.207\/webacs\/api\/v1\/data\/DeviceGroups\/42",
    "@responseType" : "getEntity",
    "entity" : {
      "@url" : "\/webacs\/data\/className\/15",
      "@type" : "className",
      "@dtoType" : "deviceGroupsDTO_$$_javassist_5196",
      "deviceGroupsDTO" : {
        "@id" : "15",
        "@displayName" : "String value",
        "clearedAlarms" : 1,
        "criticalAlarms" : 1,
        "groupId" : 2,
        "groupName" : "String value",
        "informationAlarms" : 1,
        "majorAlarms" : 1,
        "minorAlarms" : 1,
        "name" : "String value",
        "warningAlarms" : 1
      }
    }
  }
}

My python script :

import json

jsondata = json.load(open('data.json'))

for rows in jsondata['queryResponse']['entity']['deviceGroupsDTO']:
    print(rows)

it print's :

name
@id
warningAlarms
@displayName
informationAlarms
clearedAlarms
majorAlarms
groupId
groupName
criticalAlarms
minorAlarms

not sure what i'm doing wrong...

Upvotes: 2

Views: 107

Answers (1)

alecxe
alecxe

Reputation: 474221

jsondata['queryResponse']['entity']['deviceGroupsDTO'] is a dictionary.

Iterate over items() to get key, value pairs:

for key, value in jsondata['queryResponse']['entity']['deviceGroupsDTO'].items():
    print(key, value)

Note that, in case of python2, you would better use iteritems() in place of items().

See also: What is the difference between dict.items() and dict.iteritems()?

Upvotes: 2

Related Questions