Jq - How to print the parent value of an object when I am already deeply immersed in the object?

Let's say I have the following JSON stored in my jsonVariable variable.

{ "id": 1, "details": { "username": "jamesbrown", "name": "James Brown" } } 

I am analyzing this JSON with jq using the following:

 echo $jsonVariable | jq '.details.name | select(.name == "James Brown")' 

It will give me a way out

James brown

But what if I also want to get this person’s ID? Now I know that this is a crude and simple example - the program I'm working with now has a depth of 5 or 6 levels with many different JQ functions besides select. I need a way to select the parent field when I am already 5 or 6 layers deep after performing various filtering methods.

Can anybody help? Is there any way to "go back" to the parent? (Not sure I make sense!)

+11
json jq
source share
4 answers

For a more general approach, save the value of the "parent" element at the desired level of detail, then swipe it at the end of your filter:

jq '. as $parent | .details.name | select(. == "James Brown") | $parent'

Of course, for the trivial case that you reveal, you can completely omit this:

jq 'select(.details.name == "James Brown")'

Also note that if your selection filters return many matches for one parent, you will get a copy of the parent for each match. You may want to make sure that the filters you select return only one element at the parent level, wrapping all matches below the parent level in an array or deduplicating the final result with unique .

+24
source share

Take a picture:

 echo $jsonVariable | jq '{Name: .details.name, Id: .Id} | select(.name == "James Brown")' 
+1
source share

Instead of asking for the value you are testing, query to the root object that contains the requested value and the values ​​you want to select.

You need an object that contains both id and name .

 $ jq --arg name 'James Brown' 'select(.details.name == $name).id' input.json 
+1
source share

alternatively, jtc makes it easy to find a solution - a call to the parent (parent of parent, etc.) occurs inside the path that you are building:

 bash $ echo $jsonVariable | jtc -w'<James Brown> [-2] [id]' 1 bash $ 
0
source share

All Articles