How can I get discount value if brand_id=='983'.
Sample JSON:
{
"prods": [
{
"info": {
"rate": 100
},
"grocery": [
{
"brand": "A",
"brand_id": "983"
},
{
"brand": "B",
"brand_id": "253"
}
],
"discount": "20"
}
]
}
What I have tried till now is
$.prods[*].grocery[?(@.brand_id=='983')]
This returns me list/array of matched objects. But I am not able to traverse back into the tree. Any help on this?
Indeed, JSONPath isn't very good at that, so I tackled this kind of problem with my own small library; so, here's a fiddle for your example:
https://jsfiddle.net/YSharpLanguage/j9oetwnn/3
where:
gives:
Here are other examples / use cases:
JSON-to-some-markup
JSON transformations, revisited (XSLT look-alike)
(at: https://jsfiddle.net/YSharpLanguage/kj9pk8oz/10)
JSON-to-JSON
Super-lightweight JSON-to-JSON transformations
(at: https://jsfiddle.net/YSharpLanguage/ppfmmu15/10)
A JavaScript equivalent of...
XSLT 3.0 REC Section 14.4 Example: Grouping Nodes based on Common Values
(at: http://jsfiddle.net/YSharpLanguage/8bqcd0ey/1)
Cf. https://www.w3.org/TR/xslt-30/#grouping-examples
A JavaScript equivalent of...
JSONiq Use Cases Section 1.1.2. Grouping Queries for JSON
(at: https://jsfiddle.net/YSharpLanguage/hvo24hmk/3)
Cf. http://jsoniq.org/docs/JSONiq-usecases/html-single/index.html#jsongrouping
'Hope this helps,
You can write a function that returns the parent node. Once you have that, you should develop a function that walks (traverses) all the object and all its nodes and arrays, and when it finds the desired Id, well, you just get the parent and retrieve for the discount.
Here you have the simplest example of a function that returns the parent node: