Reducing JSON objects with JQ

I was recently playing around with Salt stack and its JSON output mode but needed a way to make the data more manageable. By default Salt returns data as separate JSON objects for each server that you query, so you end up with something like this:

{
  "server-1": {
    "ping": "pong"
  }
}
{
  "server-2": {
    "ping": "pong"
  }
}

This isn't useful when trying to filter for specific values across multiple servers or trying to parse the data in a quick bash script. Thankfully JQ comes to the rescue with its add functionality and the -s flag.

In short, you need something like this:

cat json | jq -s 'add | .ping'

-s reads the full input stream before running filters and add combines all the arrays it receives together. You can now run filters across your data as if JQ received it like this:

{
  "server-1": {
    "ping": "pong"
  },
  "server-2": {
    "ping": "pong"
  }
}
Tagged: JQ, JSON

Share this post