jq - How do I print a parent value of an object when I am already deep into the object's children?

后端 未结 3 1899
生来不讨喜
生来不讨喜 2020-12-15 03:37

Say I have the following JSON, stored in my variable jsonVariable.

{
    \"id\": 1,
    \"details\": {
        \"username\": \"jamesbrown\",
                


        
相关标签:
3条回答
  • 2020-12-15 03:55

    For a more generic approach, save the value of the "parent" element at the detail level you want, then pipe it at the end of your filter:

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

    Of course, for the trivial case you expose, you could omit this entirely:

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

    Also, consider that if your selecting filters return many matches for a single parent object, you will receive a copy of the parent object for each match. You may wish to make sure your select filters only return one element at the parent level by wrapping all matches below parent level into an array, or to deduplicate the final result with unique.

    0 讨论(0)
  • 2020-12-15 04:02

    Rather than querying up to the value you're testing for, query up to the root object that contains the value you're querying on and the values you wish to select.

    You need the object that contains both the id and the name.

    $ jq --arg name 'James Brown' 'select(.details.name == $name).id' input.json
    
    0 讨论(0)
  • 2020-12-15 04:05

    Give this a shot:

    echo $jsonVariable | jq '{Name: .details.name, Id: .Id}  | select(.name == "James Brown")'
    
    0 讨论(0)
提交回复
热议问题