Decoding json string in python

I have the following JSON line (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 the Python json library. I would like to access node

properties - > stock - > properties - > warehouse .

I understand that the json.loads() function stores the json string as a dictionary. But in this case, properties are my key, and everything under it is values. How to 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

+6
source share
1 answer

You can download json directly from the file as follows:

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

Based on your input string, data now a dictionary that contains other dictionaries. You can simply navigate the dictionaries as follows:

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

Source: https://habr.com/ru/post/918592/


All Articles