+ 8

Python and json

Does anyone have experience using JSON in python? I have a webserver, which replies with a quite complex nested structure in JSON format. From that I need to extrace just one information... My question is: I have a complex JSON Data structure like this: print(json.dumps(data, sort_keys=True, indent=4)) { "DAY_ENERGY": { "Unit": "Wh", "Values": { "1": 472 } }, "PAC": { "Unit": "W", "Values": { "1": 0 } }, "TOTAL_ENERGY": { "Unit": "Wh", "Values": { "1": 8404830 } }, "YEAR_ENERGY": { "Unit": "Wh", "Values": { "1": 28358 } } } Now I want to have an easy and elegant way to extract e.g. the YEAR_ENERGY from the structure and store it in a int variable.

10th Jan 2017, 10:57 PM
CodingForFun
CodingForFun - avatar
3 Answers
+ 6
I got it. :-) The JSON-object is just a multiple-array so I can get the value like print(data["YEAR_ENERGY"]["Values"]["1"]) 28358
10th Jan 2017, 11:08 PM
CodingForFun
CodingForFun - avatar
+ 4
My complete code is now: from urllib import request import json # get data from Web: webdata = request.urlopen("http://xxx.xxx.xxx.xxx(IP-Adress)/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System").read() # set decoding and remove control sequences: d1 = webdata.decode('utf-8').strip('\n\t\r') # convert it to JSON Object: data_clear = json.loads(d1) # access data: (in real the structure is further nested as in my example ;-) print(data["Body"]["Data"]["YEAR_ENERGY"]["Values"]["1"]) Any idea to save some of the conversion?
10th Jan 2017, 11:12 PM
CodingForFun
CodingForFun - avatar
+ 2
I am familiar with Python and JavaScript but I don't really see a question here.
10th Jan 2017, 4:58 PM
James Durand
James Durand - avatar