Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if element exists in array with jq

I have an array and I need to check if elements exists in that array or to get that element from the array using jq, fruit.json:

{     "fruit": [         "apple",          "orange",         "pomegranate",         "apricot",         "mango"     ] }   cat fruit.json | jq '.fruit .apple'  

does not work

like image 817
idmitriev Avatar asked Apr 06 '17 15:04

idmitriev


People also ask

Does jq have a function?

jQuery has() Method The has() method returns all elements that have one or more elements inside of them, that matches the specified selector. Tip: To select elements that have multiple elements inside of them, use comma (see example below).

What is a 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.

What is jq slurp?

“Slurp” tells jq to read every line of the input JSON lines and treat the entire group as one huge array of objects. With the Twitter data still in the input box on jq play, check the “Slurp” box, and just put . in the filter.

What is jq query?

jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed , awk , grep and friends let you play with text. jq is written in portable C, and it has zero runtime dependencies.


1 Answers

The semantics of 'contains' is not straightforward at all. In general, it would be better to use 'index' to test if an array has a specific value, e.g.

.fruit | index( "orange" ) 

However, if the item of interest is itself an array, the general form:

 ARRAY | index( [ITEM] ) 

should be used, e.g.:

[1, [2], 3] | index( [[2]] )  #=> 1 

IN/1

If your jq has IN/1 then a better solution is to use it:

.fruit as $f | "orange" | IN($f[]) 

If your jq has first/1 (as does jq 1.5), then here is a fast definition of IN/1 to use:

def IN(s): first((s == .) // empty) // false; 

any(_;_)

Another efficient alternative that is sometimes more convenient is to use any/2, e.g.

any(.fruit[]; . == "orange") 

or equivalently:

any(.fruit[] == "orange"; .) 
like image 66
peak Avatar answered Oct 16 '22 00:10

peak