How to filter an array of JSON objects with jq?

Rehan Ch picture Rehan Ch · Sep 6, 2017 · Viewed 17.3k times · Source

I have the following JSON input:

{
  "zk_kafka": [
    {
      "InstanceType": "t2.medium",
      "zkMemory": "16",
      "kafkaMemory": "8"
    },
    {
      "InstanceType": "t2.small",
      "zkMemory": "8",
      "kafkaMemory": "4"
    }
  ],
  "es_hdfs": [
    {
      "InstanceType": "t2.medium",
      "esMemory": "16",
      "hdfsMemory": "8"
    },
    {
      "InstanceType": "t2.small",
      "esMemory": "8",
      "hdfsMemory": "4"
    }
  ]
}

First I want to select an array by a property name. And then I want to select an object of the array by the value of the property InstanceType.

Example for the property zk_kafka and the value t2.medium:

{
  "InstanceType": "t2.medium",
  "zkMemory": "16",
  "kafkaMemory": "8"
}

I know how to select the array:

jq .zk_kafka

But I do not know how to filter the array of object by a property value.

Answer

ceving picture ceving · Sep 6, 2017

Use the select filter of jq:

jq '.zk_kafka | .[] | select(.InstanceType == "t2.medium")'

Use the --arg option to pass an argument to the query to avoid injections.

jq --arg instance "t2.medium" '.zk_kafka | .[] | select(.InstanceType == $instance)'

jq has a manual, a tutorial and a cookbook.