tkyass
tkyass

Reputation: 3186

how to parse json nested dict in python?

I'm trying to work with json file stored locally. That is formatted as below:

{  
   "all":{  
      "variables":{  
         "items":{  
            "item1":{  
               "one":{  
                  "size":"1"
               },
               "two":{  
                  "size":"2"
               }
            }
         }
      }
   }
}

I'm trying to get the value of the size key using the following code.

with open('path/to/file.json','r') as file:
  data = json.load(file)
itemParse(data["all"]["variables"]["items"]["item1"])

def itemParse(data):
   for i in data:
   # also tried for i in data.iterkeys():
       # data has type dict while i has type unicode
       print i.get('size')
       # also tried print i['size']

got different errors and nothing seems to work. any suggestions?

also, tried using json.loads got error expect string or buffer

Upvotes: 1

Views: 3803

Answers (2)

AndrewSmiley
AndrewSmiley

Reputation: 1963

First, use json.loads().

data = json.loads(open('path/to/file.json','r').read())

Second, your for loop should be changed to this

for k,v in data.iteritems():
    print data[k]['size']

Regarding the error expect string or buffer, do you have permissions to read the json file?

Upvotes: 0

Mauro Baraldi
Mauro Baraldi

Reputation: 6550

When you iterate over data you are getting the key only. There is 2 ways to solve it.

def itemParse(data):
   for i, j in data.iteritems():
       print j.get('size')

or

def itemParse(data):
   for i in data:
       print data[i].get('size')

Upvotes: 2

Related Questions