Reputation: 1
{
"a": [
{
"b": {
"c": [
{
"id": "123"
}
],
"d": {
"e": {
"f": [
{
"name": "abc",
"type": "in"
},
{
"name": "xyz",
"type": "out"
}
]
}
}
}
},
{
"b": {
"c": [
{
"id": "456"
}
],
"d": {
"e": {
"f": [
{
"name": "def",
"type": "out"
},
{
"name": "pqr",
"type": "out"
}
]
}
}
}
}
]
}
I am trying to extract the id's for which type='in'. So, as per the above example , the output should be 123 as only abc in the first element has the type 'in'. I tried multiple ways but not succeeded to extract it. Can someone please help on this?
With the following expression I am able to extract the node whose value is 'in' but how to extract the corresponding id/id's of the same object (i.e. 123)?
$.a[*].b.d[*].f[?(@.type=='in')]
Can try the json path here : JSON path online tool
UPDATE :
As per the suggestion from gregsdennis , I tried with the following by converting the IETF Json path mentioned to equivalent Jayway Json path which is not working :
$.a[?(@.b.d.e.f[?(@.type=='in')])].b.c[*].id
syntax error : jsonPath:
Unexpected token '?': _$_v.b.d.e.f[?(_$_v.type=='in'
Upvotes: 0
Views: 234
Reputation: 8428
You want
$.a[[email protected][[email protected] == 'in']].b.c.*.id
NOTE: .*
and [*]
are equivalent.
This will search for all elements in $.a
which contain a @.b.d.e.f
which contains @.type == 'in'
, then it queries the result of that to get .b.c.*.id
The key is using nested queries.
@.b.d.e.f[[email protected] == 'in']
acts on the elements of a
and is an existence test: it doesn't have any comparisons. If the test returns a non-empty result, then the element is selected.@.type == 'in'
acts on the elements of f
and checks for the condition that you want.The final piece is simply navigating to the information you want (.b.c.*.id
) from the elements of a
that are returned.
This is compliant with the pending IETF JSON Path specification, which can be tested in my playground https://json-everything.net/json-path.
Not all libraries will be compliant with the specification. You'll need to check with the library you're using to see what's supported.
Upvotes: 0