Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse json-object using python?

Tags:

python

json

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.

like image 873
masterial Avatar asked Sep 26 '12 01:09

masterial


People also ask

How do you parse a JSON object in Python?

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.

Can we parse JSON in Python?

If you have a JSON string, you can parse it by using the json. loads() method. The result will be a Python dictionary.

How do you parse a JSON list in Python?

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.


1 Answers

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)
like image 182
Ignacio Vazquez-Abrams Avatar answered Oct 24 '22 13:10

Ignacio Vazquez-Abrams