1

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

1
  • Use data[i]['size'] on your print line. Commented May 16, 2016 at 19:26

2 Answers 2

2

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')
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Mauro! but I'm wondering why I can't get the same result if I print i.get('size')? without using data again as in your second example?
As I said in answer, when you iterate over a dict, it retrieves the key. So you are tring to use get method in a string.
0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.