Create msg with nested object fields

I am new to NodeRed and I'm having trouble with parsing and generating msg. I have a nested object message that I am tried to parse into a new msg. The message is coming from an MQTT In node. In the debug window I see:

Here is the payload from the MQTT IN Node:

   topic: "sensor/pushnotification"
   payload: "
   {"topic":"sensor.basement_hall.battery","payload":"Battery Low Warning","subtext":"10/9/2022 
   09:55:47 AM","count":null,"percent":null}"
   qos: 2
   retain: false
   _msgid: "7042e909d390b98f"  

I run that msg through a JSON node and here is the msg output:

   topic: "sensor/pushnotification"
   payload: object
        topic: "sensor.basement_hall.battery"
        payload: "Battery Low Warning"
        subtext: "10/9/2022 09:55:47 AM"
        count: null
        percent: null
  qos: 2
  retain: false
  _msgid: "7042e909d390b98f"

I want to generate a new msg with some of the nested object fields and I can't seem to figure out how to reference them in a function. For example :

 var sTopic = msg.topic.payload.topic;
 var sPayload = msg.topic.payload.payload;
 var sSubtext = msg.topic.payload.subtext;
 msg = {
     payload : sPayload,
     topic : sTopic,
     subtext : sSubtext
 return msg;

That results in:
function: (error) TypeError: Cannot read properties of undefined (reading 'subtext')

Try msg.payload.< property > instead

Use the tools the editor provides...

There’s a great page in the docs (Working with messages : Node-RED) that will explain how to use the debug panel to find the right path to any data item.

Pay particular attention to the part about the buttons that appear under your mouse pointer when you over hover a debug message property in the sidebar.


1 Like

Thanks Steve,
I tried using the copy path button for the nested payload value and it returned
which returned

I replaced it with
in the function and which resulted in

Thanks very much for your help

It might simplify things if you set your MQTT-In node to output a parsed JSON object rather than the default autodetect. Possibly you can dispense with the JSON Parser.

Yes that got rid of the JSON node. I think I had that set like that initially before my learning curve grief with msg.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.