如何使用python解析json-object?

neb*_*lus 9 python json

我试图解析一个json对象并遇到问题.

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
Run Code Online (Sandbox Code Playgroud)

我可以弄清楚如何获得这些值.我可以得到钥匙.请帮忙.

Ign*_*ams 14

您不再拥有JSON对象,而是拥有Python 字典.迭代字典产生其键.

>>> for k in {'foo': 42, 'bar': None}:
...   print k
... 
foo
bar
Run Code Online (Sandbox Code Playgroud)

如果要访问这些值,则索引原始字典或使用返回不同内容的方法之一.

>>> for k in {'foo': 42, 'bar': None}.iteritems():
...   print k
... 
('foo', 42)
('bar', None)
Run Code Online (Sandbox Code Playgroud)


neb*_*lus 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
Run Code Online (Sandbox Code Playgroud)