Perform a look up on keys of an object to get it's value

Hello All,

I have a requirement to extract values of an object based on it’s key through a lookup.

For Example i have following json structure :

{
“A”:{
“B” : {“value” :“test”},
“C” : {“value” :“test”},
“D” : {“value” :“test”},
“E” : {“value” :“test”},
}
A,B,C,D,E all are objects.

i want to extract only B’s value when the key matches to B.

Regards,
Asheerbad

Do you mean for all B, C, D, E objects to be keys inside of Object A or Is that a typo? or are you just forgetting the closing brace at the end?

Yes all B,C,D,E objects are keys with in Object A. I forgot the closing brces for object A in above example.

the expression:

$.hasPath("[*].B") ? jsonPath($, '[*].B') : "B Not Found"

is a bit more generic, and every object in the input doc must have the ‘B’ or hasPath will return false, but this will collect Every B’s value for each Object in the input doc if there is more than one.

For your case if the object you are going to be looking at is always just going to be A. Then this will work and is more specific:

$.hasPath("A.B") ? $A.B : "B Not Found"

This will return either the value if found, or the default string ‘B Not Found’, which can be changed to whatever you’d like

Hope this solves your use case, let me know if not.

Thanks for the details.The B object key that we are trying to find inside object A is a dynamic value that is stored inside another variable. how can we replicate that variable in above expression instead of directly hard coding B.

For Ex.

value= B/C/D/E

how can we look up for B/C/D/E using value variable.

You can use bracket notation to do a lookup based on the value of an expression:

$A[$keyToLookup]

So, if $keyToLookup contained “B”, the above expression would drill down into the “A” object and get the value of the property named “B” .