Search code examples
jsonnode.jsparsingnode-red

Parsing JSON with Node Red with telegram bot


I am trying to get JSON working with my telegram bot which I have already created. I can the bot send and receive message in the debug screen from telegram in Node Red.

I want to take the return api message from telegram and then parse it out to eventually have it do something like turn on the led if I send it "LED-ON" command or similar.

Currently I see this type of JSON format. And I want to basically parse the content field out from the JSON object to get me LED-ON.

{
  "chatId":64XXXXX7,
  "messageId":337,
  "type":"message",
  "content":"LED-ON",
  "date":"2017-09-09T07:07:38.000Z",
  "inbound":true
}

I used the JSON node but from the debug it only changes the message from json object to json string. But I still can't parse out LED-ON.

Also if once i get LED-ON filtered and send it out to a split node to generate a MQTT message to turn the LED, do I need it to be a object or string? Sorry I just am very new to programming.

I can share flow if it dosen't make sense.


Solution

  • There is no need for the JSON node if the content is already a JSON object.

    I'm at a loss as to why you would need a split node, a switch node or a function node should be all that is needed to test the value in msg.payload.content

    The MQTT node will always convert any outbound msg.payload to a string before publishing.

    EDIT:

    All nodes (including function nodes) need to return an object. The msg.payload should normally hold the "output" from a node, Also no need to declare msg as it is already in scope, so in the case of your example it should be:

    msg.payload = msg.payload.content;
    return msg;
    

    Also you may do better asking questions like this on the Node-RED Slack team (linked from the Node-RED home page) as it's likely to need a little back and forth, which Stack Overflow is not best suited to.