Search code examples
jsonjqjson-query

How to extract some value from diff fields of an object in one command


there is json data like this

➜  ~ cat foo.json | jq
{
  "data": {
    "foo": [
      {
        "table": "aaa"
      },
      {
        "table": "bbb"
      }
    ],
    "bar": [
      {
        "table": "ccc"
      },
      {
        "table": "ddd"
      }
    ]
  }
}

Could get table of foo or bar separately,

➜  ~ cat foo.json | jq '.data.foo[].table'
"aaa"
"bbb"
➜  ~ cat foo.json | jq '.data.bar[].table'
"ccc"
"ddd"

how could get all table values in one command?


Solution

  • Use the comma operator.

    $ jq '.data["foo", "bar"][].table' foo.json
    

    or

    $ jq '.data | .foo, .bar | .[].table' foo.json
    

    Or assuming you want to grab any property of the data object.

    $ jq '.data[][].table' foo.json