[英]Oboe.js - how to work with chainable method and retrieving ancestor value
我正在使用oboe.js,並且我想從節點“ sections”中檢索數據,還將祖先profile_namespace和owner_name映射到從sections節點檢索的數據(請參閱下面的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返回可鏈接方法,並且可以使用“祖先”概念從父級檢索數據。
有誰可以向我解釋如何使用此方法(請參見下面的代碼)?
碼
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({
'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.createReadStream
或fs.createWriteStream
,則節點(至少v0.10.41)會引發錯誤。 我建議用'./myjson.json'
和'showInfo.json'
稱呼他們
我建議使用在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));
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.