Jq Usage: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 23: Line 23:


{{Internal|jq Concepts#Expressions|jq Concepts - Expressions}}
{{Internal|jq Concepts#Expressions|jq Concepts - Expressions}}
Example:
<syntaxhighlight lang='bash'>
jq '... | select(.Name == "something")'
</syntaxhighlight>
.Name extracts the value of a map key value pair whose key is "Name".


=Map Filters=
=Map Filters=

Revision as of 15:01, 28 April 2019

Internal

Command Line Options

-r

Output raw strings, not JSON content. This is very useful when jq is used as part of shell pipelines and the results feed other shell commands.

Universal Filters

Identity Filter .

select() Filter

select(boolean-expression)

The select() filter lets its input pass through unchanged if the boolean expression evaluates to true, and produces no output (swallows the input) otherwise.

For more details about expressions, see:

jq Concepts - Expressions

Example:

jq '... | select(.Name == "something")'

.Name extracts the value of a map key value pair whose key is "Name".

Map Filters

Object Identifier-Index Filter .key

.key

The filter expects a map and produces the value associated with the key given as argument of the filter, or null if there is no such object. The value, if exists, can be a primitive, a map or an array.

The key is case sensitive.

cat example.json | jq '.color'

This syntax only works for "identifier-like" keys: keys that are all made of alphanumeric characters and underscore, and which do not start with a digit.

The .key syntax is actually an alias for the more generic syntax:

.["key"]

If the key contains special characters, the .key alias cannot be used, and the complete .["key"] syntax should be used:

jq '.["complex::key"]'

For:

{
  "complex::color": "something"
}
jq '.complex::color'

will fail:

jq: error: syntax error, unexpected ':', expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.complex::color

while

jq '.["complex::color"]' 

will work.

Array Filters

Array Index Filter .[index]

.[zero-based-index]

selects the corresponding array element, or null if the index does not designate an element that exists.

For:

[
  "blue",
  "red",
  "green"
]
jq '.[0]'

return "blue"

while

jq '.[5]'

returns null.

If the input is not an array, the filter fails:

echo \"blah\" | jq '.[]'
jq: error (at <stdin>:1): Cannot iterate over string ("blah")

Array-to-Iterator Filter []

The filter expects and array and produces the array's elements as an iteration.

echo "[\"red\", \"blue\"]" | jq '.[]'

has the same result as:

echo "\"red\"" "\"blue\"" | jq '.'

Interestingly enough, and somewhat counterintuitively, the filter also works on maps. The effect is equivalent with Java's Map#values().

echo "{\"a\": 1, \"b\": 2}" | jq '.[]'

produces:

1 
2

The filter does not work on primitives:

echo \"blah\" | jq '.[]'
jq: error (at <stdin>:1): Cannot iterate over string ("blah")