sparky77
sparky77

Reputation: 7

url request from python code

import json
import urllib2    
response = urllib2.urlopen('http://www.energyhive.com/mobile_proxy/getCurrentValuesSummary?token=VtxgIC2UnhfUmXe_pBksov7-lguAQMZD')    
content = response.read()
print(content)

from the code i get

[{"cid":"PWER","data":[{"1437957635000":37}],"sid":"9271","units":"kWm","age":6},{"cid":"PWER_GAC","data":[{"1437957635000":0}],"sid":"9271","units":null,"age":6},{"cid":"FBAK_IMM","data":[{"1437957629000":0}],"sid":"9271","units":null,"age":12},{"cid":"PWER_IMM","data":[{"1437957629000":0}],"sid":"9271","units":null,"age":12}]

What i can't work out is getting the data from PWER_GAC

Upvotes: 0

Views: 76

Answers (2)

Edward Yu
Edward Yu

Reputation: 418

The data you are receiving is a string, and you can convert it into Python data structures with json.loads(). Then iterate through the dicts until the cid matches what you are looking for.

content = json.loads(content)
for i in content:
    if(i['cid'] == 'PWER_GAC'):
        print(i)

Upvotes: 1

dmargol1
dmargol1

Reputation: 415

You just need to load it as a JSON and go to the correct key:

for x in json.loads(content):
    if x["cid"] == "PWER_GAC":
        print(x["units"])
        print(x["age"])
        print(x["sid"])
        print(x["data"])
        print(x["cid"])

Upvotes: 1

Related Questions