The absolute simplest filter is `.` . This filter takes its
input and produces the same value as output. That is, this
is the identity operator.
The simplest *useful* filter has the form `.foo`. When given a
JSON object (aka dictionary or hash) as input, `.foo` produces
the value at the key "foo" if the key is present, or null otherwise.
A filter of the form `.foo.bar` is equivalent to `.foo | .bar`.
The `.foo` syntax only works for simple, identifier-like keys, that
is, keys that are all made of alphanumeric characters and
underscore, and which do not start with a digit.
If the key contains special characters or starts with a digit,
you need to surround it with double quotes like this:
`."foo$"`, or else `.["foo$"]`.
Just like `.foo`, but does not output an error when `.` is not an
object.
You can also look up fields of an object using syntax like
`.["foo"]` (`.foo` above is a shorthand version of this, but
only for identifier-like strings).
When the index value is an integer, `.[]` can index
arrays. Arrays are zero-based, so `.[2]` returns the third
element.
Negative indices are allowed, with -1 referring to the last
element, -2 referring to the next to last element, and so on.
The `.[:]` syntax can be used to return a
subarray of an array or substring of a string. The array
returned by `.[10:15]` will be of length 5, containing the
elements from index 10 (inclusive) to index 15 (exclusive).
Either index may be negative (in which case it counts
backwards from the end of the array), or omitted (in which
case it refers to the start or end of the array).
Indices are zero-based.
If you use the `.[index]` syntax, but omit the index
entirely, it will return *all* of the elements of an
array. Running `.[]` with the input `[1,2,3]` will produce the
numbers as three separate results, rather than as a single
array. A filter of the form `.foo[]` is equivalent to
`.foo | .[]`.
You can also use this on an object, and it will return all
the values of the object.
Like `.[]`, but no errors will be output if . is not an array
or object. A filter of the form `.foo[]?` is equivalent to
`.foo | .[]?`.
If two filters are separated by a comma, then the
same input will be fed into both and the two filters' output
value streams will be concatenated in order: first, all of the
outputs produced by the left expression, and then all of the
outputs produced by the right.
The | operator combines two filters by feeding the output(s) of
the one on the left into the input of the one on the right. It's
similar to the Unix shell's pipe, if you're used to that.
If the one on the left produces multiple results, the one on
the right will be run for each of those results.
Parenthesis work as a grouping operator just as in any typical
programming language.
jq supports the same set of datatypes as JSON - numbers,
strings, booleans, arrays, objects (which in JSON-speak are
hashes with only string keys), and "null".
Booleans, null, strings and numbers are written the same way as
in JSON. Just like everything else in jq, these simple
values take an input and produce an output - `42` is a valid jq
expression that takes an input, ignores it, and returns 42
instead.
Numbers in jq are internally represented by their IEEE754 double
precision approximation. Any arithmetic operation with numbers,
whether they are literals or results of previous filters, will
produce a double precision floating point result.
However, when parsing a literal jq will store the original literal
string. If no mutation is applied to this value then it will make
to the output in its original form, even if conversion to double
would result in a loss.
As in JSON, `[]` is used to construct arrays, as in
`[1,2,3]`. The elements of the arrays can be any jq
expression, including a pipeline. All of the results produced
by all of the expressions are collected into one big array.
You can use it to construct an array out of a known quantity
of values (as in `[.foo, .bar, .baz]`) or to "collect" all the
results of a filter into an array (as in `[.items[].name]`)
Like JSON, `{}` is for constructing objects (aka
dictionaries or hashes), as in: `{"a": 42, "b": 17}`.
If the keys are "identifier-like", then the quotes can be left
off, as in `{a:42, b:17}`. Variable references as key
expressions use the value of the variable as the key. Key
expressions other than constant literals, identifiers, or
variable references, need to be parenthesized, e.g.,
`{("a"+"b"):59}`.
The value can be any expression (although you may need to wrap
it in parentheses if, for example, it contains colons), which
gets applied to the {} expression's input (remember, all
filters have an input and an output).
Because that is so common, there's a shortcut syntax for it:
`{user, title}`.
If one of the expressions produces multiple results,
multiple dictionaries will be produced.
Recursively descends `.`, producing every value. This is the
same as the zero-argument `recurse` builtin (see below).
Some jq operators (for instance, `+`) do different things
depending on the type of their arguments (arrays, numbers,
etc.). However, jq never does implicit type conversions. If you
try to add a string to an object you'll get an error message and
no result.
The operator `+` takes two filters, applies them both
to the same input, and adds the results together. What
"adding" means depends on the types involved:
- **Numbers** are added by normal arithmetic.
- **Arrays** are added by being concatenated into a larger array.
- **Strings** are added by being joined into a larger string.
- **Objects** are added by merging, that is, inserting all
the key-value pairs from both objects into a single
combined object. If both objects contain a value for the
same key, the object on the right of the `+` wins. (For
recursive merge use the `*` operator.)
`null` can be added to any value, and returns the other
value unchanged.
As well as normal arithmetic subtraction on numbers, the `-`
operator can be used on arrays to remove all occurrences of
the second array's elements from the first array.
These infix operators behave as expected when given two numbers.
Division by zero raises an error. `x % y` computes x modulo y.
Multiplying a string by a number produces the concatenation of
that string that many times. `"x" * 0` produces `""`.
Dividing a string by another splits the first using the second
as separators.
Multiplying two objects will merge them recursively: this works
like addition but if both objects contain a value for the
same key, and the values are objects, the two are merged with
the same strategy.
The builtin function `abs` is defined naively as: `if . < 0 then - . else . end`.
The builtin function `length` gets the length of various
different types of value:
- The length of a **string** is the number of Unicode
codepoints it contains (which will be the same as its
JSON-encoded length in bytes if it's pure ASCII).
- The length of a **number** is its absolute value.
- The length of an **array** is the number of elements.
- The length of an **object** is the number of key-value pairs.
- The length of **null** is zero.
- It is an error to use `length` on a **boolean**.
The builtin function `utf8bytelength` outputs the number of
bytes used to encode a string in UTF-8.
The builtin function `keys`, when given an object, returns
its keys in an array.
The keys are sorted "alphabetically", by unicode codepoint
order. This is not an order that makes particular sense in
any particular language, but you can count on it being the
same for any two objects with the same set of keys,
regardless of locale settings.
When `keys` is given an array, it returns the valid indices
for that array: the integers from 0 to length-1.
The `keys_unsorted` function is just like `keys`, but if
the input is an object then the keys will not be sorted,
instead the keys will roughly be in insertion order.
The builtin function `has` returns whether the input object
has the given key, or the input array has an element at the
given index.
The builtin function `in` returns whether or not the input key is in the
given object, or the input index corresponds to an element
in the given array. It is, essentially, an inversed version
of `has`.
For any filter `f`, `map(f)` and `map_values(f)` apply `f`
to each of the values in the input array or object, that is,
to the values of `.[]`.
In the absence of errors, `map(f)` always outputs an array
whereas `map_values(f)` outputs an array if given an array,
or an object if given an object.
When the input to `map_values(f)` is an object, the output
object has the same keys as the input object except for
those keys whose values when piped to `f` produce no values
at all.
The key difference between `map(f)` and `map_values(f)` is
that the former simply forms an array from all the values of
`($x|f)` for each value, `$x`, in the input array or object,
but `map_values(f)` only uses `first($x|f)`.
Emit the projection of the input object or array defined by the
specified sequence of path expressions, such that if `p` is any
one of these specifications, then `(. | p)` will evaluate to the
same value as `(. | pick(pathexps) | p)`. For arrays, negative
indices and `.[m:n]` specifications should not be used.
Outputs array representations of the given path expression
in `.`. The outputs are arrays of strings (object keys)
and/or numbers (array indices).
Path expressions are jq expressions like `.a`, but also `.[]`.
There are two types of path expressions: ones that can match
exactly, and ones that cannot. For example, `.a.b.c` is an
exact match path expression, while `.a[].b` is not.
`path(exact_path_expression)` will produce the array
representation of the path expression even if it does not
exist in `.`, if `.` is `null` or an array or an object.
`path(pattern)` will produce array representations of the
paths matching `pattern` if the paths exist in `.`.
The builtin function `del` removes a key and its corresponding
value from an object.
The builtin function `getpath` outputs the values in `.` found
at each path in `PATHS`.
The builtin function `setpath` sets the `PATHS` in `.` to `VALUE`.
The builtin function `delpaths` deletes the `PATHS` in `.`.
`PATHS` must be an array of paths, where each path is an array
of strings and numbers.
These functions convert between an object and an array of
key-value pairs. If `to_entries` is passed an object, then
for each `k: v` entry in the input, the output array
includes `{"key": k, "value": v}`.
`from_entries` does the opposite conversion, and `with_entries(f)`
is a shorthand for `to_entries | map(f) | from_entries`, useful for
doing some operation to all keys and values of an object.
`from_entries` accepts `"key"`, `"Key"`, `"name"`, `"Name"`,
`"value"`, and `"Value"` as keys.
The function `select(f)` produces its input unchanged if
`f` returns true for that input, and produces no output
otherwise.
These built-ins select only inputs that are arrays, objects,
iterables (arrays or objects), booleans, numbers, normal
numbers, finite numbers, strings, null, non-null values, and
non-iterables, respectively.
`empty` returns no results. None at all. Not even `null`.
Produces an error with the input value, or with the message
given as the argument. Errors can be caught with try/catch;
see below.
Stops the jq program with no further outputs. jq will exit
with exit status `0`.
Stops the jq program with no further outputs. The input will
be printed on `stderr` as raw output (i.e., strings will not
have double quotes) with no decoration, not even a newline.
The given `exit_code` (defaulting to `5`) will be jq's exit
status.
Produces an object with a "file" key and a "line" key, with
the filename and line number where `$__loc__` occurs, as
values.
`paths` outputs the paths to all the elements in its input
(except it does not output the empty list, representing .
itself).
`paths(f)` outputs the paths to any values for which `f` is `true`.
That is, `paths(type == "number")` outputs the paths to all numeric
values.
The filter `add` takes as input an array, and produces as
output the elements of the array added together. This might
mean summed, concatenated or merged depending on the types
of the elements of the input array - the rules are the same
as those for the `+` operator (described above).
If the input is an empty array, `add` returns `null`.
`add(generator)` operates on the given generator rather than
the input.
The filter `any` takes as input an array of boolean values,
and produces `true` as output if any of the elements of
the array are `true`.
If the input is an empty array, `any` returns `false`.
The `any(condition)` form applies the given condition to the
elements of the input array.
The `any(generator; condition)` form applies the given
condition to all the outputs of the given generator.
The filter `all` takes as input an array of boolean values,
and produces `true` as output if all of the elements of
the array are `true`.
The `all(condition)` form applies the given condition to the
elements of the input array.
The `all(generator; condition)` form applies the given
condition to all the outputs of the given generator.
If the input is an empty array, `all` returns `true`.
The filter `flatten` takes as input an array of nested arrays,
and produces a flat array in which all arrays inside the original
array have been recursively replaced by their values. You can pass
an argument to it to specify how many levels of nesting to flatten.
The `range` function produces a range of numbers. `range(4; 10)`
produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers
are produced as separate outputs. Use `[range(4; 10)]` to get a range as
an array.
The one argument form generates numbers from 0 to the given
number, with an increment of 1.
The two argument form generates numbers from `from` to `upto`
with an increment of 1.
The three argument form generates numbers `from` to `upto`
with an increment of `by`.
The `floor` function returns the floor of its numeric input.
The `sqrt` function returns the square root of its numeric input.
The `tonumber` function parses its input as a number. It
will convert correctly-formatted strings to their numeric
equivalent, leave numbers alone, and give an error on all other input.
The `toboolean` function parses its input as a boolean. It
will convert correctly-formatted strings to their boolean
equivalent, leave booleans alone, and give an error on all other input.
The `tostring` function prints its input as a
string. Strings are left unchanged, and all other values are
JSON-encoded.
The `type` function returns the type of its argument as a
string, which is one of null, boolean, number, string, array
or object.
Some arithmetic operations can yield infinities and "not a
number" (NaN) values. The `isinfinite` builtin returns `true`
if its input is infinite. The `isnan` builtin returns `true`
if its input is a NaN. The `infinite` builtin returns a
positive infinite value. The `nan` builtin returns a NaN.
The `isnormal` builtin returns true if its input is a normal
number.
The `sort` functions sorts its input, which must be an
array. Values are sorted in the following order:
* `null`
* `false`
* `true`
* numbers
* strings, in alphabetical order (by unicode codepoint value)
* arrays, in lexical order
* objects
The ordering for objects is a little complex: first they're
compared by comparing their sets of keys (as arrays in
sorted order), and if their keys are equal then the values
are compared key by key.
`sort_by` may be used to sort by a particular field of an
object, or by applying any jq filter. `sort_by(f)` compares
two elements by comparing the result of `f` on each element.
When `f` produces multiple values, it firstly compares the
first values, and the second values if the first values are
equal, and so on.
`group_by(.foo)` takes as input an array, groups the
elements having the same `.foo` field into separate arrays,
and produces all of these arrays as elements of a larger
array, sorted by the value of the `.foo` field.
Any jq expression, not just a field access, may be used in
place of `.foo`. The sorting order is the same as described
in the `sort` function above.
Find the minimum or maximum element of the input array.
The `min_by(path_exp)` and `max_by(path_exp)` functions allow
you to specify a particular field or property to examine, e.g.
`min_by(.foo)` finds the object with the smallest `foo` field.
The `unique` function takes as input an array and produces
an array of the same elements, in sorted order, with
duplicates removed.
The `unique_by(path_exp)` function will keep only one element
for each value obtained by applying the argument. Think of it
as making an array by taking one element out of every group
produced by `group`.
This function reverses an array.
The filter `contains(b)` will produce true if b is
completely contained within the input. A string B is
contained in a string A if B is a substring of A. An array B
is contained in an array A if all elements in B are
contained in any element in A. An object B is contained in
object A if all of the values in B are contained in the
value in A with the same key. All other types are assumed to
be contained in each other if they are equal.
Outputs an array containing the indices in `.` where `s`
occurs. The input may be an array, in which case if `s` is an
array then the indices output will be those where all elements
in `.` match those of `s`.
Outputs the index of the first (`index`) or last (`rindex`)
occurrence of `s` in the input.
The filter `inside(b)` will produce true if the input is
completely contained within b. It is, essentially, an
inversed version of `contains`.
Outputs `true` if . starts with the given string argument.
Outputs `true` if . ends with the given string argument.
Outputs all combinations of the elements of the arrays in the
input array. If given an argument `n`, it outputs all combinations
of `n` repetitions of the input array.
Outputs its input with the given prefix string removed, if it
starts with it.
Outputs its input with the given suffix string removed, if it
ends with it.
Outputs its input with the given string removed at both ends, if it
starts or ends with it.
`trim` trims both leading and trailing whitespace.
`ltrim` trims only leading (left side) whitespace.
`rtrim` trims only trailing (right side) whitespace.
Whitespace characters are the usual `" "`, `"\n"` `"\t"`, `"\r"`
and also all characters in the Unicode character database with the
whitespace property. Note that what considers whitespace might
change in the future.
Converts an input string into an array of the string's
codepoint numbers.
The inverse of explode.
Splits an input string on the separator argument.
`split` can also split on regex matches when called with
two arguments (see the regular expressions section below).
Joins the array of elements given as input, using the
argument as separator. It is the inverse of `split`: that is,
running `split("foo") | join("foo")` over any input string
returns said input string.
Numbers and booleans in the input are converted to strings.
Null values are treated as empty strings. Arrays and objects
in the input are not supported.
Emit a copy of the input string with its alphabetic characters (a-z and A-Z)
converted to the specified case.
The `while(cond; update)` function allows you to repeatedly
apply an update to `.` until `cond` is false.
The `repeat(exp)` function allows you to repeatedly
apply expression `exp` to `.` until an error is raised.
The `until(cond; next)` function allows you to repeatedly
apply the expression `next`, initially to `.` then to its own
output, until `cond` is true.
When called without an argument, `recurse` is equivalent to
`recurse(.[]?)`.
`recurse(f)` is identical to `recurse(f; true)` and can be
used without concerns about recursion depth.
`recurse(f; condition)` is a generator which begins by
emitting . and then emits in turn .|f, .|f|f, .|f|f|f, ... so long
as the computed value satisfies the condition.
The `walk(f)` function applies f recursively to every
component of the input entity. When an array is
encountered, f is first applied to its elements and then to
the array itself; when an object is encountered, f is first
applied to all the values and then to the object.
This builtin returns true if jq's build configuration
includes support for preservation of input number literals.
This builtin returns true if jq was built with "decnum",
which is the current literal number preserving numeric
backend implementation for jq.
This builtin binding shows the jq executable's build
configuration. Its value has no particular format, but
it can be expected to be at least the `./configure`
command-line arguments, and may be enriched in the
future to include the version strings for the build
tooling used.
`$ENV` is an object representing the environment variables as
set when the jq program started.
`env` outputs an object representing jq's current environment.
Transpose a possibly jagged matrix (an array of arrays).
Rows are padded with nulls so the result is always rectangular.
`bsearch(x)` conducts a binary search for x in the input
array. If the input is sorted and contains x, then
`bsearch(x)` will return its index in the array; otherwise, if
the array is sorted, it will return (-1 - ix) where ix is an
insertion point such that the array would still be sorted
after the insertion of x at ix. If the array is not sorted,
`bsearch(x)` will return an integer that is probably of no
interest.
Inside a string, you can put an expression inside parens
after a backslash. Whatever the expression returns will be
interpolated into the string.
The `tojson` and `fromjson` builtins dump values as JSON texts
or parse JSON texts into values, respectively. The `tojson`
builtin differs from `tostring` in that `tostring` returns strings
unmodified, while `tojson` encodes strings as JSON strings.
The `@foo` syntax is used to format and escape strings,
which is useful for building URLs, documents in a language
like HTML or XML, and so forth. `@foo` can be used as a
filter on its own, the possible escapings are:
* `@text`:
Calls `tostring`, see that function for details.
* `@json`:
Serializes the input as JSON.
* `@html`:
Applies HTML/XML escaping, by mapping the characters
`<>&'"` to their entity equivalents `<`, `>`,
`&`, `'`, `"`.
* `@uri`:
Applies percent-encoding, by mapping all reserved URI
characters to a `%XX` sequence.
* `@urid`:
The inverse of `@uri`, applies percent-decoding, by mapping
all `%XX` sequences to their corresponding URI characters.
* `@csv`:
The input must be an array, and it is rendered as CSV
with double quotes for strings, and quotes escaped by
repetition.
* `@tsv`:
The input must be an array, and it is rendered as TSV
(tab-separated values). Each input array will be printed as
a single line. Fields are separated by a single
tab (ascii `0x09`). Input characters line-feed (ascii `0x0a`),
carriage-return (ascii `0x0d`), tab (ascii `0x09`) and
backslash (ascii `0x5c`) will be output as escape sequences
`\n`, `\r`, `\t`, `\\` respectively.
* `@sh`:
The input is escaped suitable for use in a command-line
for a POSIX shell. If the input is an array, the output
will be a series of space-separated strings.
* `@base64`:
The input is converted to base64 as specified by RFC 4648.
* `@base64d`:
The inverse of `@base64`, input is decoded as specified by RFC 4648.
Note\: If the decoded string is not UTF-8, the results are undefined.
This syntax can be combined with string interpolation in a
useful way. You can follow a `@foo` token with a string
literal. The contents of the string literal will *not* be
escaped. However, all interpolations made inside that string
literal will be escaped.
The `fromdateiso8601` builtin parses datetimes in the ISO 8601
format to a number of seconds since the Unix epoch
(1970-01-01T00:00:00Z). The `todateiso8601` builtin does the
inverse.
The `fromdate` builtin parses datetime strings. Currently
`fromdate` only supports ISO 8601 datetime strings, but in the
future it will attempt to parse datetime strings in more
formats.
The `todate` builtin is an alias for `todateiso8601`.
The `now` builtin outputs the current time, in seconds since
the Unix epoch.
Low-level jq interfaces to the C-library time functions are
also provided: `strptime`, `strftime`, `strflocaltime`,
`mktime`, `gmtime`, and `localtime`.
This builtin produces an object whose keys are computed by
the given index expression applied to each value from the
given stream.
This builtin joins the values from the given stream to the
given index. The index's keys are computed by applying the
given index expression to each value from the given stream.
An array of the value in the stream and the corresponding
value from the index is fed to the given join expression to
produce each result.
* `IN(s)`:
This builtin outputs `true` if `.` appears in the given
stream, otherwise it outputs `false`.
* `IN(source; s)`:
This builtin outputs `true` if any value in the source stream
appears in the second stream, otherwise it outputs `false`.
Returns a list of all builtin functions in the format `name/arity`.
Since functions with the same name but different arities are considered
separate functions, `all/0`, `all/1`, and `all/2` would all be present
in the list.
The expression 'a == b' will produce 'true' if the results of evaluating
a and b are equal (that is, if they represent equivalent JSON values) and
'false' otherwise. In particular, strings are never considered equal
to numbers. In checking for the equality of JSON objects, the ordering of keys
is irrelevant. If you're coming from JavaScript, please note that jq's `==` is like
JavaScript's `===`, the "strict equality" operator.
!= is "not equal", and 'a != b' returns the opposite value of 'a == b'
`if A then B else C end` will act the same as `B` if `A`
produces a value other than false or null, but act the same
as `C` otherwise.
`if A then B end` is the same as `if A then B else . end`.
That is, the `else` branch is optional, and if absent is the
same as `.`. This also applies to `elif` with absent ending `else` branch.
If the condition `A` produces multiple results, then `B` is evaluated
once for each result that is not false or null, and `C` is evaluated
once for each false or null.
More cases can be added to an if using `elif A then B` syntax.
The comparison operators `>`, `>=`, `<=`, `<` return whether
their left argument is greater than, greater than or equal
to, less than or equal to or less than their right argument
(respectively).
The ordering is the same as that described for `sort`, above.
jq supports the normal Boolean operators `and`, `or`, `not`.
They have the same standard of truth as if expressions -
`false` and `null` are considered "false values", and
anything else is a "true value".
If an operand of one of these operators produces multiple
results, the operator itself will produce a result for each input.
`not` is in fact a builtin function rather than an operator,
so it is called as a filter to which things can be piped
rather than with special syntax, as in `.foo and .bar |
not`.
The `//` operator produces all the values of its left-hand
side that are neither `false` nor `null`. If the
left-hand side produces no values other than `false` or
`null`, then `//` produces all the values of its right-hand
side.
Errors can be caught by using `try EXP catch EXP`. The first
expression is executed, and if it fails then the second is
executed with the error message. The output of the handler,
if any, is output as if it had been the output of the
expression to try.
The `try EXP` form uses `empty` as the exception handler.
jq has a syntax for named lexical labels to "break" or "go (back) to":
label $out | ... break $out ...
The `break $label_name` expression will cause the program to
act as though the nearest (to the left) `label $label_name`
produced `empty`.
The relationship between the `break` and corresponding `label`
is lexical: the label has to be "visible" from the break.
The `?` operator, used as `EXP?`, is shorthand for `try EXP`.
jq uses the
[Oniguruma regular expression library](https://github.com/kkos/oniguruma/blob/master/doc/RE),
as do PHP, TextMate, Sublime Text, etc, so the
description here will focus on jq specifics.
Oniguruma supports several flavors of regular expression, so it is important to know
that jq uses the ["Perl NG" (Perl with named groups)](https://github.com/kkos/oniguruma/blob/master/doc/SYNTAX.md) flavor.
FLAGS is a string consisting of one of more of the supported flags:
* `g` - Global search (find all matches, not just the first)
* `i` - Case insensitive search
* `m` - Multi line mode (`.` will match newlines)
* `n` - Ignore empty matches
* `p` - Both s and m modes are enabled
* `s` - Single line mode (`^` -> `\A`, `$` -> `\Z`)
* `l` - Find longest possible matches
* `x` - Extended regex format (ignore whitespace and comments)
Like `match`, but does not return match objects, only `true` or `false`
for whether or not the regex matches the input.
**match** outputs an object for each match it finds. Matches have
the following fields:
* `offset` - offset in UTF-8 codepoints from the beginning of the input
* `length` - length in UTF-8 codepoints of the match
* `string` - the string that it matched
* `captures` - an array of objects representing capturing groups.
Capturing group objects have the following fields:
* `offset` - offset in UTF-8 codepoints from the beginning of the input
* `length` - length in UTF-8 codepoints of this capturing group
* `string` - the string that was captured
* `name` - the name of the capturing group (or `null` if it was unnamed)
Capturing groups that did not match anything return an offset of -1
Collects the named captures in a JSON object, with the name
of each capture as the key, and the matched string as the
corresponding value.
Emit a stream of the non-overlapping substrings of the input
that match the regex in accordance with the flags, if any
have been specified. If there is no match, the stream is empty.
To capture all the matches for each input string, use the idiom
`[ expr ]`, e.g. `[ scan(regex) ]`. If the regex contains capturing
groups, the filter emits a stream of arrays, each of which contains
the captured strings.
Splits an input string on each regex match.
For backwards compatibility, when called with a single argument,
`split` splits on a string, not a regex.
These provide the same results as their `split` counterparts,
but as a stream instead of an array.
Emit the string obtained by replacing the first match of
regex in the input string with `tostring`, after
interpolation. `tostring` should be a jq string or a stream
of such strings, each of which may contain references to
named captures. The named captures are, in effect, presented
as a JSON object (as constructed by `capture`) to
`tostring`, so a reference to a captured variable named "x"
would take the form: `"\(.x)"`.
`gsub` is like `sub` but all the non-overlapping occurrences of the regex are
replaced by `tostring`, after interpolation. If the second argument is a stream
of jq strings, then `gsub` will produce a corresponding stream of JSON strings.
The expression `exp as $x | ...` means: for each value of expression
`exp`, run the rest of the pipeline with the entire original input, and
with `$x` set to that value. Thus `as` functions as something of a
foreach loop.
Multiple variables may be declared using a single `as` expression by
providing a pattern that matches the structure of the input
(this is known as "destructuring"):
. as {realnames: $names, posts: [$first, $second]} | ...
The variable declarations in array patterns (e.g., `. as
[$first, $second]`) bind to the elements of the array in from
the element at index zero on up, in order. When there is no
value at the index for an array pattern element, `null` is
bound to that variable.
The destructuring alternative operator provides a concise mechanism
for destructuring an input that can take one of several forms.
Each alternative need not define all of the same variables, but all named
variables will be available to the subsequent expression. Variables not
matched in the alternative that succeeded will be `null`:
Additionally, if the subsequent expression returns an error, the
alternative operator will attempt to try the next binding. Errors
that occur during the final alternative are passed through.
You can give a filter a name using "def" syntax:
def increment: . + 1;
From then on, `increment` is usable as a filter just like a
builtin function (in fact, this is how many of the builtins
are defined). A function may take arguments:
def map(f): [.[] | f];
Arguments are passed as _filters_ (functions with no
arguments), _not_ as values. The same argument may be
referenced multiple times with different inputs (here `f` is
run for each element of the input array).
If you want the value-argument behaviour for defining simple
functions, you can just use a variable:
def addvalue(f): f as $f | map(. + $f);
Or use the short-hand:
def addvalue($f): ...;
Multiple definitions using the same function name are allowed.
Each re-definition replaces the previous one for the same
number of function arguments, but only for references from
functions (or main program) subsequent to the re-definition.
There are two types of symbols in jq: value bindings (a.k.a.,
"variables"), and functions. Both are scoped lexically,
with expressions being able to refer only to symbols that
have been defined "to the left" of them. The only exception
to this rule is that functions can refer to themselves so as
to be able to create recursive functions.
Returns true if `exp` produces no outputs, false otherwise.
The `limit` function extracts up to `n` outputs from `expr`.
The `skip` function skips the first `n` outputs from `expr`.
The `first(expr)` and `last(expr)` functions extract the first
and last values from `expr`, respectively.
The `nth(n; expr)` function extracts the nth value output by `expr`.
Note that `nth(n; expr)` doesn't support negative values of `n`.
The `first` and `last` functions extract the first
and last values from any array at `.`.
The `nth(n)` function extracts the nth value of any array at `.`.
The `reduce` syntax allows you to combine all of the results of
an expression by accumulating them into a single answer.
The form is `reduce EXP as $var (INIT; UPDATE)`.
The `foreach` syntax is similar to `reduce`, but intended to
allow the construction of `limit` and reducers that produce
intermediate results.
The form is `foreach EXP as $var (INIT; UPDATE; EXTRACT)`.
When `EXTRACT` is omitted, the identity filter is used.
That is, it outputs the intermediate values as they are.
Tail calls are optimized whenever the expression to the left of
the recursive call outputs its last value. In practice this
means that the expression to the left of the recursive call
should not produce more than one output for each input.
Besides simple arithmetic operators such as `+`, jq also has most
standard math functions from the C math library. C math functions
that take a single input argument (e.g., `sin()`) are available as
zero-argument jq functions. C math functions that take two input
arguments (e.g., `pow()`) are available as two-argument jq
functions that ignore `.`. C math functions that take three input
arguments are available as three-argument jq functions that ignore
`.`.
Availability of standard math functions depends on the
availability of the corresponding math functions in your operating
system and C math library. Unavailable math functions will be
defined but will raise an error.
Outputs one new input.
Outputs all remaining inputs, one by one.
These two filters are like `.` but have as a side-effect the
production of one or more messages on stderr.
The message produced by the `debug` filter has the form
["DEBUG:",]
where `` is a compact rendition of the input
value. This format may change in the future.
The `debug(msgs)` filter is defined as `(msgs | debug | empty), .`
thus allowing great flexibility in the content of the message,
while also allowing multi-line debugging statements to be created.
Prints its input in raw and compact mode to stderr with no
additional decoration, not even a newline.
Returns the name of the file whose input is currently being
filtered. Note that this will not work well unless jq is
running in a UTF-8 locale.
Returns the line number of the input currently being filtered.
Consumes a number as input and truncates the corresponding
number of path elements from the left of the outputs of the
given streaming expression.
Outputs values corresponding to the stream expression's
outputs.
The `tostream` builtin outputs the streamed form of its input.
All the assignment operators in jq have path expressions on the
left-hand side (LHS). The right-hand side (RHS) provides values
to set to the paths named by the LHS path expressions.
Values in jq are always immutable. Internally, assignment works
by using a reduction to compute new, replacement values for `.` that
have had all the desired assignments applied to `.`, then
outputting the modified value.
This is the "update" operator `|=`. It takes a filter on the
right-hand side and works out the new value for the property
of `.` being assigned to by running the old value through this
expression. For instance, `(.foo, .bar) |= .+1` will build an
object with the `foo` field set to the input's `foo` plus 1,
and the `bar` field set to the input's `bar` plus 1.
The left-hand side can be any general path expression; see `path()`.
If the right-hand side outputs no values (i.e., `empty`), then
the left-hand side path will be deleted, as with `del(path)`.
If the right-hand side outputs multiple values, only the first
one will be used (COMPATIBILITY NOTE: in jq 1.5 and earlier
releases, it used to be that only the last one was used).
jq has a few operators of the form `a op= b`, which are all
equivalent to `a |= . op b`. So, `+= 1` can be used to
increment values, being the same as `|= . + 1`.
This is the plain assignment operator. Unlike the others, the
input to the right-hand side (RHS) is the same as the input to
the left-hand side (LHS) rather than the value at the LHS
path, and all values output by the RHS will be used (as shown
below).
If the RHS of `=` produces multiple values, then for each such
value jq will set the paths on the left-hand side to the value
and then it will output the modified `.`.
When jq encounters an assignment like 'a = b', it records the "path"
taken to select a part of the input document while executing a. This
path is then used to find which part of the input to change while
executing the assignment. Any filter may be used on the
left-hand side of an equals - whichever paths it selects from the
input will be where the assignment is performed.
A `#` character (not part of a string) starts a comment.
All characters from `#` to the end of the line are ignored.
If the end of the line is preceded by an odd number of backslash
characters, the following line is also considered part of the
comment and is ignored.
Modules imported by a program are searched for in a default search
path (see below). The `import` and `include` directives allow the
importer to alter this path.
Paths in the search path are subject to various substitutions.
Imports a module found at the given path relative to a
directory in a search path. A `.jq` suffix will be added to
the relative path string. The module's symbols are prefixed
with `NAME::`.
Imports a module found at the given path relative to a
directory in a search path as if it were included in place. A
`.jq` suffix will be added to the relative path string. The
module's symbols are imported into the caller's namespace as
if the module's content had been included directly.
Imports a JSON file found at the given path relative to a
directory in a search path. A `.json` suffix will be added to
the relative path string. The file's data will be available
as `$NAME::NAME`.
This directive is entirely optional. It's not required for
proper operation. It serves only the purpose of providing
metadata that can be read with the `modulemeta` builtin.
Takes a module name as input and outputs the module's metadata
as an object, with the module's imports (including metadata)
as an array value for the `deps` key and the module's defined
functions as an array value for the `defs` key.