我使用Defiant.js,您可以在其中使用XPATH表达式查询json数据。现在,我想选择搜索结果的根节点。
源代码
var data = [{
"id": 1,
"categories": [{
"id": 1,
"title": "Category1"
}, {
"id": 2,
"title": "Category2"
}]
}, {
"id": 2,
"categories": [{
"id": 1,
"title": "Category1"
}]
}, {
"id": 3,
"categories": [{
"id": 2,
"title": "Category2"
}, {
"id": 3,
"title": "Category3"
}]
}];
var result = JSON.search(data, '//categories[contains(id, "2")]')
通过该表达式,我得到了两个类别对象的数组
[{
"id": 2,
"title": "Category2"
}, {
"id": 2,
"title": "Category2"
}]
但是我想得到流行歌曲的根源
[{
"id": 1,
"categories": [{
"id": 1,
"title": "Category1"
}, {
"id": 2,
"title": "Category2"
}]
}, {
"id": 3,
"categories": [{
"id": 2,
"title": "Category2"
}, {
"id": 3,
"title": "Category3"
}]
}]
有可能这样做吗?提前致谢!
最佳答案
基本上,有效的XML中总是只有一个根节点,选择根应该和选择文档中的第一个节点一样简单:
/*
我认为使用defiant.js时,相同的概念也适用于JSON。始终只有一个JSON对象充当根。
无论如何,如果您真的想从后代节点上下文开始,则可以使用
ancestor
轴任意向上爬树。假设我们当前在后代节点之一(例如categories
)中,则可以通过以下方式进入根节点:ancestor::*[not(parent::*)]
基于JSON数据的示例如下所示:
var xpath1 = '//categories[contains(id, "2")]/ancestor::*[not(parent::*)]';
var result1 = JSON.search(data, xpath1)
var xpath2 = '/*[not(parent::*) and .//categories[contains(id, "2")]]';
var result2 = JSON.search(data, xpath2)
更新:
在此上下文中,“根”似乎是指此xpath引用的元素:
/*/*
。如果是正确的话,您可能想要这样的东西(您也可以将
descendant::
替换为缩写版本.//
):/*/*[descendant::subcategories[contains(id, '4')]]
更普遍 :
/*/*[descendant::{some filter here}]
或者,如果您的过滤器也需要检查“ root” JSON对象的属性,则可以使用
descendant-or-self
代替descendant
:/*/*[descendant-or-self::{some filter here}]
关于javascript - XPATH获取所选节点的根节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29778173/