Oboe.js - 如何使用可链接方法并检索祖先值

Oboe.js - how to work with chainable method and retrieving ancestor value

我正在使用 oboe.js 并且我想从节点 "sections" 检索数据并将祖先 profile_namespace 和 owner_name 映射到从部分检索的数据节点(参见下面的 json 文件摘录)。

JSON 文件摘录 (myjson.json):

{
  "data": [{
    "profile_namespace": "DS",
    "tutorial": {
      "owner_name": "Dominic",
      "picture_url": "/picture.jpg",
      "title": "The code",
      "url": "/Dominic/thecode/",
      "sections": [{
        "episode_url": "/tutorial/intro/symphony-of-war/",
        "artist": "MasterOrchestra",
        "title": "Symphony of War"
      }, {
        "episode_url": "/tutorial/mainshow/musicproductiontip1/",
        "artist": "DStone",
        "title": "Music production tip 1"
      }, {
        "episode_url": "/tutorial/outrothe/nextshow/",
        "artist": "MasterOrchestra",
        "title": "Next show"
      }]
    }
  }]
}

现在我只能从节点 "sections" 检索数据,但我在文档中看到 .node return 可链接方法并且可以使用 "ancestors" 从父级检索数据。

有谁能解释一下如何使用这个方法(见下面我的代码)?

代码

var oboe = require('oboe');
var fs = require('fs');
var SetList = require('fs');
var setList = [];
var showInfo = require('fs');

oboe(fs.createReadStream('/myjson.json'))
    .node({
        'sections': function(node) {
            setList.push(node);
            showInfo = fs.createWriteStream('/showInfo.json');
            showInfo.write(JSON.stringify(setList));
        }
    });

感谢您的帮助!

多米尼克

如果我误解了你问题的某些部分,请告诉我,我会更新我的答案。

在双簧管中使用祖先

您传递给节点侦听器的回调函数将使用三个参数触发。第一个是树中已匹配的节点,第二个是表示该节点路径的数组,第三个是表示该节点祖先的对象数组。这记录在 API 的 node-event section 末尾附近。

.node({
    'sections': function(sections, path, ancestors) {

      var grandparent = ancestors[ancestors.length - 2];
      console.log(grandparent.owner_name); // Dominic

      var greatGrandparent = ancestors[ancestors.length - 3];
      console.log(greatGrandparent.profile_namespace); // DS

    }
});

其他

以下是我认为值得一提的一些不相关的事情

  • 您可以删除这一行,因为变量 SetList 未被使用。

    var SetList = require('fs');

  • 您不需要将 setList 初始化为 fs 模块的实例。因为您稍后要重新定义它,所以您可以只声明该变量而不实例化它。更好的是,您可以在回调中定义它,因为它是唯一使用它的地方。

  • 如果在以 '/' 开头的字符串上调用 fs.createReadStreamfs.createWriteStream
  • Node(至少 v0.10.41)会抛出错误。我建议用 './myjson.json''showInfo.json'

  • 给他们打电话
  • 我建议使用 shorthand 方式在 Oboe 中注册节点侦听器。这只是一种风格偏好。如果您要注册多个侦听器,其他语法可能会有用,但我认为在这种情况下链接同样好。

我对您发布的代码的建议实现

var oboe = require('oboe');
var fs = require('fs');

oboe(fs.createReadStream('./myjson.json'))
  .node('sections', function(sections, path, ancestors) {

      var mutatedSections = sections;
      // change mutatedSections however you want

      var showInfo = fs.createWriteStream('./showInfo.json');
      showInfo.write(JSON.stringify(mutatedSections));

    }
  });