【问题标题】:How can I transform a JSON array of object contained in one message to multiple JSON object messages?如何将一条消息中包含的 JSON 对象数组转换为多个 JSON 对象消息?
【发布时间】:2016-03-03 14:55:23
【问题描述】:

目前正在创建一个在 Node-RED 中运行、在 Node.js 上运行、在 CloudFoundry 上运行的 Bluemix 上运行的 ETL 流。

我正在查询一个 Cloudant 数据库,并在单个 JSON 数组上返回查询结果,该数组包含所有作为 JSON 对象的文档。

不,我想以流水线方式单独处理它们。如何在 Node-RED 中存档?

非常感谢!

JSON

[{
  "id": "c8342b2a.bf0df",
  "type": "cloudant in",
  "z": "2f0a54f6.110ccc",
  "service": "nokeredrkie-cloudantNoSQLDB",
  "cloudant": "",
  "name": "",
  "database": "tweets",
  "search": "_all_",
  "design": "",
  "index": "",
  "x": 295.70001220703125,
  "y": 450.9333190917969,
  "wires": [
    ["5e83a34.48cdd5c"]
  ]
}, {
  "id": "c9411e75.2b1b7",
  "type": "debug",
  "z": "2f0a54f6.110ccc",
  "name": "",
  "active": true,
  "console": "false",
  "complete": "payload",
  "x": 646.699951171875,
  "y": 470.7333679199219,
  "wires": []
}, {
  "id": "3f1d2018.8f5ec8",
  "type": "inject",
  "z": "2f0a54f6.110ccc",
  "name": "",
  "topic": "",
  "payload": "",
  "payloadType": "date",
  "repeat": "",
  "crontab": "",
  "once": true,
  "x": 126.70001220703125,
  "y": 472.6666564941406,
  "wires": [
    ["c8342b2a.bf0df"]
  ]
}, {
  "id": "5e83a34.48cdd5c",
  "type": "function",
  "z": "2f0a54f6.110ccc",
  "name": "",
  "func": "//msg.payload = JSON.parse(msg.payload);\nmsg.payload = msg.payload[1].tweet.user.screen_name;\nreturn msg;",
  "outputs": 1,
  "noerr": 0,
  "x": 444.70001220703125,
  "y": 489.4000549316406,
  "wires": [
    ["c9411e75.2b1b7"]
  ]
}]

【问题讨论】:

  • JSON.parse 该字符串,然后使用数组方法
  • 如果我理解正确,您想将单个对象移动到一个新变量中。我说的对吗?

标签: javascript json node.js ibm-cloud node-red


【解决方案1】:

Cloudant 节点 输出到 Function 节点,如下所示:

var msgs = [];
for (var i = 0; i< msg.payload.length; i++) {
  msgs.push({payload: msg.payload[i]});
}

return [msgs]

这会将数组中的每个项目流式传输到流中的下一个节点

编辑:需要将数组包装在另一组 [] 中以使所有消息输出相同的输出。

【讨论】:

  • 你甚至可以试试msg.payload.map(function(item){ return {payload:item} })
  • 不确定这是否可以在 Node-RED 功能节点的沙箱上下文中工作,但您可以尝试一下
  • 我不确定 Node.js。我的评论是基于 JS 的
  • 亲爱的 hardillb 和 @Rajesh 非常感谢。两种建议的解决方案都有效!最紧凑的是:return [msg.payload.map(function(item){ return {payload:item} })]
  • 这几天应该换成分裂节点
猜你喜欢
  • 2016-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-26
  • 2020-10-04
  • 1970-01-01
  • 2019-05-20
相关资源
最近更新 更多