11

I am trying to parse a json object and having problems.

import json

record= '{"shirt":{"red":{"quanitity":100},"blue":{"quantity":10}},"pants":{"black":{"quantity":50}}}'
inventory = json.loads(record)
#HELP NEEDED HERE
for item in inventory:
    print item

I can figure out how to obtain the values. I can get keys. Please help.

1
  • If you can get keys, then you can certainly get the values. That example shows a nested dictionary. Loop through it, checking if the value is a dictionary before displaying it Commented Sep 26, 2012 at 2:02

2 Answers 2

15

You no longer have a JSON object, you have a Python dictionary. Iterating over a dictionary produces its keys.

>>> for k in {'foo': 42, 'bar': None}:
...   print k
... 
foo
bar

If you want to access the values then either index the original dictionary or use one of the methods that returns something different.

>>> for k in {'foo': 42, 'bar': None}.iteritems():
...   print k
... 
('foo', 42)
('bar', None)
Sign up to request clarification or add additional context in comments.

Comments

9
import json

record = '{"shirts":{"red":{"quantity":100},"blue":{"quantity":10}},"pants":{"black":{"quantity":50}}}'
inventory = json.loads(record)

for key, value in dict.items(inventory["shirts"]):
    print key, value

for key, value in dict.items(inventory["pants"]):
    print key, value

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.