Search code examples
jsonnode-red

Merging two JSON Objects in Node-Red


I am having some trouble trying to merge two JSON objects retrieved from my SQL Server database into a single object in Node-Red.

The flow I have created is the following: enter image description here

For each call to the database I am receiving the following objects:

Plans:

[{"PlanID":2,"Status":0,"EndTime":"0001-01-01T00:00:00.000Z"}]

Goals:

[{"GoalID":1,"PlanID":2, "Type":2,"Message":"Walk 1000 km","Difficulty":0}]

I have created two functions which assign these objects into flow variables ('plans' and 'goals'), and now I was trying to merge both objects into a single JSON object.

I don't know if I have to use the Join node for this purpose and if so how to configure it, but my idea was to create a JSON object in this format:

[{"GoalID":1,"Plan":{"PlanID":2,"Status":0,"EndTime":"0001-01-01T00:00:00.000Z"}, "Type":2,"Message":"Walk 1000 km","Difficulty":0}]

Solution

  • First I wouldn't set them as flow variables as these will get over written if you get a second request in to the http-in node while the Database look ups are happening. Better to add them as msg variables then they flow with the msg and can't be overwritten.

    Given you are not just combining the 2 objects to get the super set of keys and values you are probably best off just using either a function node or the change to assemble to the output object yourself.

    Assuming the input looks something like:

    msg.plans = [{"PlanID":2,"Status":0,"EndTime":"0001-01-01T00:00:00.000Z"}]
    msg.goals = [{"GoalID":1,"PlanID":2, "Type":2,"Message":"Walk 1000 km","Difficulty":0}]
    

    then the function node would look something like:

    msg.payload = msg.goals[0];
    msg.payload.plan = msg.plans[0];
    delete msg.goals;
    delete msg.plans;
    return msg;
    

    The change node rules would looks something like

    enter image description here

    The join node would work to get the 2 objects into an array or an object using the topics as keys to hold the 2 input messages.