eclipse / paho.mqtt.javascript

paho.mqtt.javascript
Other
1.14k stars 468 forks source link

Parsing JSON payloads #110

Closed sjorsvanheuveln closed 6 years ago

sjorsvanheuveln commented 7 years ago

I'm trying to parse a JSON payload published by a device to the web client. How do I access the data inside the object. The JSON.parse() function is not working and results in the client losing its connection. How do I overcome this?

Doing console.log() on message.payload, I get the following: {"type":"info","firmware":"v1.5","deviceName":"ESP8266-1953434","chipid":1953434,"topic":"woonkamer/lamp"}

So the message is coming in, but I cannot parse it whatsover. E.g. message.payload['type'] fails, same goes for message.payload.type. Also trying JSON.parse(message.payload) fails. What am I doing wrong?

sjorsvanheuveln commented 7 years ago

I already understand. It threw errors at messages that weren't JSON, I had to do this first in order to distinguish between json payload and non-json payloads:

var IS_JSON = true;
try { var json = $.parseJSON(message.payloadString) }
catch(err) { IS_JSON = false}