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.
Identity: . (dot) in jq represent the entire input without any filters. JQ command followed by a dot will output the input as it is with some formatting to make it pretty. You can use jq . command to format the output of a curl command.
A jq program is a "filter": it takes an input, and produces an output. There are a lot of builtin filters for extracting a particular field of an object, or converting a number to a string, or various other standard tasks.
The filters key allows you to filter the query results for records matching specific values. You can string together multiple filters by constructing JSON arrays called filters, separating each filter by a comma, and joining them by the AND or the OR operator.
JSONPath distinguishes between the "root object or element" ($) and "the current object or element" (.). jq simply uses . to refer to the current JSON entity and so it is context-dependent: it can refer to items in the input stream of the jq process as a whole, or to the output of a filter.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With