我正在尝试解析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
我可以弄清楚如何获取这些值。我可以得到钥匙。请帮忙。
答案 0 :(得分:14)
您不再拥有JSON对象,而是拥有Python dictionary。迭代字典会产生密钥。
>>> for k in {'foo': 42, 'bar': None}:
... print k
...
foo
bar
如果要访问这些值,则索引原始字典或使用返回不同内容的方法之一。
>>> for k in {'foo': 42, 'bar': None}.iteritems():
... print k
...
('foo', 42)
('bar', None)
答案 1 :(得分:7)
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