How Can I parse out JSON in a Node-RED Function

Henryw4 picture Henryw4 · Oct 7, 2015 · Viewed 14.5k times · Source

I am working with Node-RED in Bluemix for IoT.

How can I parse out the individual pieces of information (like the cmdmsg and the tempr) in a function node so I can use it in other nodes in the flow? I'm getting an error when I try (see below)

I am receiving the JSON complete message object (from an IoT in Node) that I see in my "debug" node when I set it to look at the complete message object. see the object below.

It appears to me that the JSON is formatted correctly.

I tried putting the following in the function node, but I'm getting an error that says "TypeError: Cannot read property 'tempr' of undefined"

Here is what the function parameter is: return {payload:msg.payload.d.tempr};

and here is the message object

{
   "topic": "iot-2/type/Arduino-tempsensor/id/FFFFFFFFFFFF/evt/status/fmt/json", 
   "payload": "{\n\"d\": {\n\"myName\": \"Arduino CF\",\n\"cmdmsg\": \"Weekly\",\n\"tempr\": -3,\n}\n}", 
   "deviceId": "FFFFFFFFFFFF", 
   "deviceType": "Arduino-tempsensor", 
   "eventType": "status", 
   "format": "json", 
   "_msgid": "ffffffff.55555" 
}

note: I obfuscated the device ID (mac address) and msgid

Any ideas on how to parse the data out and why I'm getting an error?

Answer

Harald Uebele picture Harald Uebele · Oct 7, 2015

Sorry, but your JSON Payload is completely messed up, it should look like this: {"d": {"myName": "Arduino CF","cmdmsg": "Weekly","tempr": -3}} You shouldn't see any \or \nin the payload, they look like escape characters from the client side. I also believe that the last comma after the tempr value shouldn't be there for valid JSON.

I am not an Arduino expert but I have experimented with a Raspberry Pi and the Mosquitto client, this is how I can successfully send an event to IoTF: mosquitto_pub -h <org>.messaging.internetofthings.ibmcloud.com -p 1883 -u "use-token-auth" -P "<token>" -i d:<org>:raspi:raspi2 -t iot-2/evt/message/fmt/json -m {"d":{"text":"Hello World"}}

If the paylod is correct JSON your statement return {payload:msg.payload.d.tempr}; will work.

Have you seen this: http://www.ibm.com/developerworks/cloud/library/cl-bluemix-arduino-iot2/