pythonjsonapache-sparksparkcore

JSON read from sparkcore to python


I have searched the web but couldn't find a suitable answer so I will try and ask here.

I am experimenting with a spark core and parsing data through JSON. I have already managed to read the data and print it with the following code:

import urllib, json
from pprint import pprint

url = "https://api.spark.io/v1/devices/mycore/result?access_token=accesstoken"
response = urllib.urlopen(url);
data = json.loads(response.read())
pprint(data)

And now I am trying to print the value I am sending with this code:

data["result"]["data1"]

I found the above in another topic but I am probably to unexperienced to properly apply it to my own code.

This is what python prints:

{u'cmd': u'VarReturn',
 u'coreInfo': {u'connected': True,
           u'deviceID': u'1111111111111111111',
           u'last_app': u'',
           u'last_handshake_at': u'2015-03-09T12:28:20.271Z',
           u'last_heard': u'2015-03-09T12:56:42.780Z'},
 u'name': u'result',
 u'result': u'{"data1":2869}'}

the error I get says the following: TypeError: string indices must be integers

I used the example code from this topic:

https://community.spark.io/t/example-logging-and-graphing-data-from-your-spark-core-using-google/2929

I hope I am clear, can anyone enlighten me?


Solution

  • Try to print out data["result"]. From python print you have provided, the output should be '{"data1":2869}', which is another json object.

    Try something like this:

    import urllib, json
    from pprint import pprint
    
    url = "https://api.spark.io/v1/devices/mycore/result?access_token=accesstoken"
    response = urllib.urlopen(url);
    data = json.loads(response.read())
    pprint(data)
    
    new_data = json.loads(data["result"])
    print new_data["data1"]