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.
Python has a built in module that allows you to work with JSON data. At the top of your file, you will need to import the json module. If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method.
If you have a JSON string, you can parse it by using the json. loads() method. The result will be a Python dictionary.
Parse JSON - Convert from JSON to Python If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With