How Can I parse out JSON in a Node-RED Function
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 \n
in 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/
Henryw4
Updated on June 04, 2022Comments
-
Henryw4 almost 2 years
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?
-
Henryw4 over 8 yearsThanks for the input. The payload shown above is when the debug node is set to show the whole message object (which I assume shows the individual formatting including newline characters and such). When I change the debug node to show the payload, I see this: { "d": { "myName": "Arduino CF", "": "CMD", "tempr": -3, } } which looks almost like valid JSON except as you mentioned the comma after the tempr which I will remove and see if that addresses it.
-
Henryw4 over 8 yearsyes, the comma at the end was the issue. I had my browser showing everything in small fonts and though that was a period after the temp. Thanks for sort of proof-reading my JSON for me!