I am trying to parse a json object and having problems.
我试图解析一个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
I can figure out how to obtain the values. I can get keys. Please help.
我可以弄清楚如何获取这些值。我可以得到钥匙。请帮忙。
2 个解决方案
#1
13
You no longer have a JSON object, you have a Python dictionary. Iterating over a dictionary produces its keys.
您不再拥有JSON对象,而是拥有Python字典。迭代字典产生其键。
>>> 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)
#2
4
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
#1
13
You no longer have a JSON object, you have a Python dictionary. Iterating over a dictionary produces its keys.
您不再拥有JSON对象,而是拥有Python字典。迭代字典产生其键。
>>> 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)
#2
4
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