简体   繁体   English

在 Node-RED 中转换 JSON

[英]Transform a JSON in Node-RED

I have a JSON like:我有一个像这样的 JSON:

{"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?如何在 Node-RED 中实现这一点?

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.假设您在msg.payload有该 JSON 对象,那么您可以添加一个Change节点,将其配置为设置msg.payload并从“to”字段中的类型列表中选择expression Then set the to value to:然后将to值设置为:

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

This is a JSONata expression.这是一个 JSONata 表达式。 The $each function will call the provided function to each key/value pair in the object ( $.payload ). $each函数将对对象中的每个键/值对调用提供的函数( $.payload )。 The provided function maps the key ( $k ) and value ( $v ) to the required format.提供的函数将键 ( $k ) 和值 ( $v ) 映射到所需的格式。

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.注意 - 如果您要映射的对象不在msg.payload下,那么您需要更改$.payload位以指向所需的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM