47

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.

2
  • 2
    Show us your input and expected output, rather than stating an X-Y problem Commented Sep 6, 2017 at 8:17
  • This time I wrote the question for you, but next time read stackoverflow.com/help/mcve Commented Sep 6, 2017 at 11:09

2 Answers 2

76

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.

Sign up to request clarification or add additional context in comments.

11 Comments

The quoting works fine. But keep in mind that you have to escape the regular expression according to the requirements of sed.
{ "InstanceType": "t2.medium", "zkMemory": "16", "kafkaMemory": "8" }, { "InstanceType": "t2.small", "zkMemory": "8", "kafkaMemory": "4" } this is my block.If matches t2.medium then it should give me entire block and t2.medium will come from variable.In pattern I gave manually t2.medium and it worked but not accepting from variable.
Why do you want to use sed, if you have already jq? Forget sed. jq is all you need. Edit your question. Show complete input and complete command and expected output.
{ "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" } ] } I want a block from zk_kafka when matches t2.medium.
expected output is { "InstanceType": "t2.medium", "zkMemory": "16", "kafkaMemory": "8" },
|
0

Alternatively, you can also use map():

jq '.zk_kafka | map(select(.InstanceType == "t2.medium"))' input.json

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.