Search code examples
jsonnode-red

Transform a JSON in Node-RED


I have a JSON like:

{"ab":12,"cd":23,"ef":34,"gh":"xyz"}

I would like to transform it into:

[
{"key":"ab","value":12},
{"key":"cd","value":23},
{"key":"ef","value":34},
{"key":"gh","value":"xyz"}
]

How can I achieve this within Node-RED?


Solution

  • Assuming you have that JSON object in msg.payload, then you can add a Change node, configure it to set msg.payload and select expression from the list of types in the 'to' field. Then set the to value to:

    $each($.payload,function($v, $k) {{"key":$k,"value": $v}})
    

    This is a JSONata expression. The $each function will call the provided function to each key/value pair in the object ($.payload). The provided function maps the key ($k) and value ($v) to the required format.

    Note - if the object you want to map is not held under msg.payload, then you'll need to change the $.payload bit to point at the required property.