Server Side Events JSON parsing

I’ve been work with server side events and I noticed something that I’m not sure is completely normal. It might be normal and it just might be that I’m too inexperienced to realize how to deal with this but I’m noticing some strange things in the JSON data that comes back from openHAB.

I have some code that subscribes to and I can successfully connect and retreive that data. But the response I get is something like this:

event: message
data: {"topic":"smarthome/items/PorchLight/state","payload":"{\"type\":\"OnOff\",\"value\":\"OFF\"}","type":"ItemStateEvent"}

I can parse it with a standard JSON parser but what I don’t know how to handle is the “/” in the payload before Type and Value. Enough other people have done this that I must be missing something. Can someone comment who has worked with SSE before?


It means the payload itself is a string so you need parse it again to convert it to an object. Are you using JavaScript? If so, parse the entire string when you get the event from the event source. Once you do that, parse the payload again:

var wholeThing = JSON.parse(.....);
var payload = JSON.parse(wholeThing.payload);

Great! That’s really helpful. I am using JavaScript so that’s perfect. I’m still learning so I appreciate the help!