如果brand_id =='983',我怎样才能获得折扣价值.
示例JSON:
{
"prods": [
{
"info": {
"rate": 100
},
"grocery": [
{
"brand": "A",
"brand_id": "983"
},
{
"brand": "B",
"brand_id": "253"
}
],
"discount": "20"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我到现在为止尝试的是
$.prods[*].grocery[?(@.brand_id=='983')]
Run Code Online (Sandbox Code Playgroud)
这将返回匹配对象的列表/数组.但我无法回到树上.对此有何帮助?
事实上,JSONPath 在这方面并不是很擅长,所以我用我自己的小库解决了这类问题;所以,这是你的例子的小提琴:
https://jsfiddle.net/YSharpLanguage/j9oetwnn/3
在哪里:
var products = {
"prods": [
{
"info": {
"rate": 85
},
"grocery": [
{
"brand": "C",
"brand_id": "984"
},
{
"brand": "D",
"brand_id": "254"
}
],
"discount": "15"
},
{
"info": {
"rate": 100
},
"grocery": [
{
"brand": "A",
"brand_id": "983"
},
{
"brand": "B",
"brand_id": "253"
}
],
"discount": "20"
}
]
};
function GroceryItem(obj) {
return (typeof obj.brand === "string") && (typeof obj.brand_id === "string");
}
// last parameter set to "true", to grab all the "GroceryItem" instances
// at any depth:
var itemsAndDiscounts = [ products ].nodeset(GroceryItem, true).
map(
function(node) {
var item = node.value, // node.value: the current "GroceryItem" (aka "$.prods[*].grocery[*]")
discount = node.parent. // node.parent: the array of "GroceryItem" (aka "$.prods[*].grocery")
parent. // node.parent.parent: the product (aka "$.prods[*]")
discount; // node.parent.parent.discount: the product discount
// finally, project into an easy-to-filter form:
return { id: item.brand_id, discount: discount };
}
),
discountOfItem983;
discountOfItem983 = itemsAndDiscounts.
filter
(
function(mapped) {
return mapped.id === "983";
}
)
[0].discount;
console.log("All items and discounts: " + JSON.stringify(itemsAndDiscounts, null, 2));
console.log("Discount of #983: " + discountOfItem983);
Run Code Online (Sandbox Code Playgroud)
给出:
All items and discounts: [
{
"id": "984",
"discount": "15"
},
{
"id": "254",
"discount": "15"
},
{
"id": "983",
"discount": "20"
},
{
"id": "253",
"discount": "20"
}
]
Discount of #983: 20
Run Code Online (Sandbox Code Playgroud)
以下是其他示例/用例:
(位于: https: //jsfiddle.net/YSharpLanguage/kj9pk8oz/10)
(位于: https: //jsfiddle.net/YSharpLanguage/ppfmmu15/10)
XSLT 3.0 REC 第 14.4 节示例:根据公共值对节点进行分组
(位于: http: //jsfiddle.net/YSharpLanguage/8bqcd0ey/1)
比照。https://www.w3.org/TR/xslt-30/#grouping-examples
(位于: https: //jsfiddle.net/YSharpLanguage/hvo24hmk/3)
比照。http://jsoniq.org/docs/JSONiq-usecases/html-single/index.html#jsongrouping
'希望这可以帮助,