Can you explain the Json in this get Particle.published code

If anyone would be kind enough to explain the commented out json code in the following, I’d be grateful.
I’ve managed to get the code to work (taken from another forum post click to see original post but only with the json lines commented out.
I think I can decipher the rest of the code but no idea what the json stuff is for/doing here.
When I run the code in idle I get the odd ‘message’ printed, what is this?

 from sseclient import SSEClient
    import requests
    ##import json
    messages = SSEClient('')
    for msg in messages:
        event = str(msg.event).encode('utf-8')
        data = str('utf-8')
        print event
        print data
    ##    dataJson = json.loads(data)

The data field in a Particle SSE event message contains a JSON encoded block. It might look something like this:


The import line adds the JSON functionality to your program.
The dataJson line reads the data and converts from JSON to an object.

Once you’ve done that, you can access (the original data from Particle.publish) and the other items like dataJson.published_at.

1 Like

You’re the man Rickkas, appreciate all your efforts responding.
It’s tough when you’re on the beginners ladder and this kind of help is so useful.
If I wanted to get the Json side working (no specific need at the moment but keen to learn)…
I’m getting the following when I uncomment the code:

Traceback (most recent call last):
  File "/home/pi/Documents/TreatMachine/WorkingRPi/", line 14, in <module>
    dataJson = json.loads(data)
  File "/usr/lib/python2.7/json/", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

I’m not positive about this, as I’ve never used the Python SSE client before, but I think you might need to check to make sure data is not an empty string before you call json.loads on it. An empty string is not valid JSON (hence the error) but you may get empty data from keepalive messages. Just guessing after reading this: