decoding json string in python

json, python

Solution

You can load json straight from the file like this:

 f = open("c:/dir/jsondec.json")
 data = json.load(f)

Based on your input string, `data` is now a dictionary that contains other dictionaries. You can just navigate up the dictionaries like so:

 node = data['properties']['stock']['properties']['warehouse']
 print str(node)

Problem

I have the following JSON string (from wikipedia http://en.wikipedia.org/wiki/JSON) ``` { "name":"Product", "properties": { "id": { "type":"number", "description":"Product identifier", "required":true }, "name": { "type":"string", "description":"Name of the product", "required":true }, "price": { "type":"number", "minimum":0, "required":true }, "tags": { "type":"array", "items": { "type":"string" } }, "stock": { "type":"object", "properties": { "warehouse": { "type":"number" }, "retail": { "type":"number" } } } } } ``` I am trying to decode this string using Python json library. I would like to access the node `properties - > stock - > properties - > warehouse`. I understand that `json.loads()` function stores the json string as a dictionary. But in this case properties is my key and everything under that are values. How do I access the above node. ``` import json jsonText="" file = open("c:/dir/jsondec.json") for line in file.xreadlines(): jsonText+=line data = json.loads(jsonText) for k,v in data.items(): print k // shows name and properties file.close(); ``` Thanks

Original source