{
"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
2
Answers
$.a is gives you an array and you want to access first item of array and the c object is also has an array value.
So the way is like;
$.a[0].b.c[0].id
will give you the result123
You want
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 ofa
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 off
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 ofa
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.