skip to Main Content

I have this sort of json:

[
    {
        "source": 
        {
            "file": "test",
            "baz": "now"
        }
    },
    {
        "source": {
            "dev": "foo"
        }
    },
    
    {
        "source": {
            "bar": "bar"
        }
    }
]

and I would like to get a list of all values for file or dev. So the expected outcome of the above should be: ["test", "foo"]

I am stuck somewhere here:

.[].source | select(.file? or .dev?)

But that yield the complete objects. How to access only the attribute values than??

2

Answers


  1. Instead of using ? or other operators, using getpath/1 is one option, where you can just filter paths and get their value

    [ getpath(paths | select(.[-1] == "file" or .[-1] == "dev")) ]
    

    Or even combine with another condition to check for source key, if you want to be completely sure i.e. .[-2] == "source"

    Demo – https://jqplay.org/s/IddhVIbUenj

    Login or Signup to reply.
  2. You can traverse to .file and .dev at once using .source | .file, .dev or .source["file", "dev"], then filter out null values using values (not ?).

    map(.source | .file, .dev | values)
    # or
    map(.source["file", "dev"] | values)
    
    [
      "test",
      "foo"
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search