Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter an array of JSON objects with jq?

Tags:

json

jq

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.

like image 416
Rehan Ch Avatar asked Sep 06 '17 08:09

Rehan Ch


People also ask

How does jq filter data?

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.

What is jq filter?

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.

Can I filter JSON?

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.

Does jq use JSONPath?

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.


Video Answer


1 Answers

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.

like image 182
ceving Avatar answered Oct 18 '22 07:10

ceving