Skip to content
Myr

website: Make latest release (1.7) be default manual (#3130)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Fixes issue with confusion about features that has not been released yet. Move deveopment manual.yml to dev/manual.yml Symlink manual.yml to v1.7/manual.yml Refactor to share history header with links to other manual versions. Change man.test and man page generation to use dev/manual.yml Related to #3078 #3127

authored by Mattias Wadman · committed by GitHub · parent 2ee20ca · Browse files · 12 files+3818 added−3840 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

12 files+3818 added−3840 removed

  • other:+3818 added−3840 removed

12 files+3818 added−3840 removed

added:docs/content/manual/dev/manual.yml+3800 added
1---2headline: jq Manual (development version)34body: |56 A jq program is a "filter": it takes an input, and produces an7 output. There are a lot of builtin filters for extracting a8 particular field of an object, or converting a number to a string,9 or various other standard tasks.1011 Filters can be combined in various ways - you can pipe the output of12 one filter into another filter, or collect the output of a filter13 into an array.1415 Some filters produce multiple results, for instance there's one that16 produces all the elements of its input array. Piping that filter17 into a second runs the second filter for each element of the18 array. Generally, things that would be done with loops and iteration19 in other languages are just done by gluing filters together in jq.2021 It's important to remember that every filter has an input and an22 output. Even literals like "hello" or 42 are filters - they take an23 input but always produce the same literal as output. Operations that24 combine two filters, like addition, generally feed the same input to25 both and combine the results. So, you can implement an averaging26 filter as `add / length` - feeding the input array both to the `add`27 filter and the `length` filter and then performing the division.2829 But that's getting ahead of ourselves. :) Let's start with something30 simpler:3132manpage_intro: |33 jq(1) -- Command-line JSON processor34 ====================================3536 ## SYNOPSIS3738 `jq` [<options>...] <filter> [<files>...]3940 `jq` can transform JSON in various ways, by selecting, iterating,41 reducing and otherwise mangling JSON documents. For instance,42 running the command `jq 'map(.price) | add'` will take an array of43 JSON objects as input and return the sum of their "price" fields.4445 `jq` can accept text input as well, but by default, `jq` reads a46 stream of JSON entities (including numbers and other literals) from47 `stdin`. Whitespace is only needed to separate entities such as 148 and 2, and true and false. One or more <files> may be specified, in49 which case `jq` will read input from those instead.5051 The <options> are described in the [INVOKING JQ] section; they52 mostly concern input and output formatting. The <filter> is written53 in the jq language and specifies how to transform the input54 file or document.5556 ## FILTERS5758manpage_epilogue: |59 ## BUGS6061 Presumably. Report them or discuss them at:6263 https://github.com/jqlang/jq/issues6465 ## AUTHOR6667 Stephen Dolan `<mu@netsoc.tcd.ie>`6869sections:70 - title: Invoking jq71 body: |7273 jq filters run on a stream of JSON data. The input to jq is74 parsed as a sequence of whitespace-separated JSON values which75 are passed through the provided filter one at a time. The76 output(s) of the filter are written to standard output, as a77 sequence of newline-separated JSON data.7879 The simplest and most common filter (or jq program) is `.`,80 which is the identity operator, copying the inputs of the jq81 processor to the output stream. Because the default behavior of82 the jq processor is to read JSON texts from the input stream,83 and to pretty-print outputs, the `.` program's main use is to84 validate and pretty-print the inputs. The jq programming85 language is quite rich and allows for much more than just86 validation and pretty-printing.8788 Note: it is important to mind the shell's quoting rules. As a89 general rule it's best to always quote (with single-quote90 characters on Unix shells) the jq program, as too many characters with special91 meaning to jq are also shell meta-characters. For example, `jq92 "foo"` will fail on most Unix shells because that will be the same93 as `jq foo`, which will generally fail because `foo is not94 defined`. When using the Windows command shell (cmd.exe) it's95 best to use double quotes around your jq program when given on the96 command-line (instead of the `-f program-file` option), but then97 double-quotes in the jq program need backslash escaping. When using98 the Powershell (`powershell.exe`) or the Powershell Core99 (`pwsh`/`pwsh.exe`), use single-quote characters around the jq100 program and backslash-escaped double-quotes (`\"`) inside the jq101 program.102103 * Unix shells: `jq '.["foo"]'`104 * Powershell: `jq '.[\"foo\"]'`105 * Windows command shell: `jq ".[\"foo\"]"`106107 Note: jq allows user-defined functions, but every jq program108 must have a top-level expression.109110 You can affect how jq reads and writes its input and output111 using some command-line options:112113 * `--null-input` / `-n`:114115 Don't read any input at all. Instead, the filter is run once116 using `null` as the input. This is useful when using jq as a117 simple calculator or to construct JSON data from scratch.118119 * `--raw-input` / `-R`:120121 Don't parse the input as JSON. Instead, each line of text is122 passed to the filter as a string. If combined with `--slurp`,123 then the entire input is passed to the filter as a single long124 string.125126 * `--slurp` / `-s`:127128 Instead of running the filter for each JSON object in the129 input, read the entire input stream into a large array and run130 the filter just once.131132 * `--compact-output` / `-c`:133134 By default, jq pretty-prints JSON output. Using this option135 will result in more compact output by instead putting each136 JSON object on a single line.137138 * `--raw-output` / `-r`:139140 With this option, if the filter's result is a string then it141 will be written directly to standard output rather than being142 formatted as a JSON string with quotes. This can be useful for143 making jq filters talk to non-JSON-based systems.144145 * `--raw-output0`:146147 Like `-r` but jq will print NUL instead of newline after each output.148 This can be useful when the values being output can contain newlines.149 When the output value contains NUL, jq exits with non-zero code.150151 * `--join-output` / `-j`:152153 Like `-r` but jq won't print a newline after each output.154155 * `--ascii-output` / `-a`:156157 jq usually outputs non-ASCII Unicode codepoints as UTF-8, even158 if the input specified them as escape sequences (like159 "\u03bc"). Using this option, you can force jq to produce pure160 ASCII output with every non-ASCII character replaced with the161 equivalent escape sequence.162163 * `--sort-keys` / `-S`:164165 Output the fields of each object with the keys in sorted order.166167 * `--color-output` / `-C` and `--monochrome-output` / `-M`:168169 By default, jq outputs colored JSON if writing to a170 terminal. You can force it to produce color even if writing to171 a pipe or a file using `-C`, and disable color with `-M`.172 When the `NO_COLOR` environment variable is not empty, jq disables173 colored output by default, but you can enable it by `-C`.174175 Colors can be configured with the `JQ_COLORS` environment176 variable (see below).177178 * `--tab`:179180 Use a tab for each indentation level instead of two spaces.181182 * `--indent n`:183184 Use the given number of spaces (no more than 7) for indentation.185186 * `--unbuffered`:187188 Flush the output after each JSON object is printed (useful if189 you're piping a slow data source into jq and piping jq's190 output elsewhere).191192 * `--stream`:193194 Parse the input in streaming fashion, outputting arrays of path195 and leaf values (scalars and empty arrays or empty objects).196 For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]`197 becomes `[[0],[]]`, `[[1],"a"]`, and `[[2,0],"b"]`.198199 This is useful for processing very large inputs. Use this in200 conjunction with filtering and the `reduce` and `foreach` syntax201 to reduce large inputs incrementally.202203 * `--stream-errors`:204205 Like `--stream`, but invalid JSON inputs yield array values206 where the first element is the error and the second is a path.207 For example, `["a",n]` produces `["Invalid literal at line 1,208 column 7",[1]]`.209210 Implies `--stream`. Invalid JSON inputs produce no error values211 when `--stream` without `--stream-errors`.212213 * `--seq`:214215 Use the `application/json-seq` MIME type scheme for separating216 JSON texts in jq's input and output. This means that an ASCII217 RS (record separator) character is printed before each value on218 output and an ASCII LF (line feed) is printed after every219 output. Input JSON texts that fail to parse are ignored (but220 warned about), discarding all subsequent input until the next221 RS. This mode also parses the output of jq without the `--seq`222 option.223224 * `-f filename` / `--from-file filename`:225226 Read filter from the file rather than from a command line, like227 awk's -f option.228229 * `-L directory`:230231 Prepend `directory` to the search list for modules. If this232 option is used then no builtin search list is used. See the233 section on modules below.234235 * `--arg name value`:236237 This option passes a value to the jq program as a predefined238 variable. If you run jq with `--arg foo bar`, then `$foo` is239 available in the program and has the value `"bar"`. Note that240 `value` will be treated as a string, so `--arg foo 123` will241 bind `$foo` to `"123"`.242243 Named arguments are also available to the jq program as244 `$ARGS.named`.245246 * `--argjson name JSON-text`:247248 This option passes a JSON-encoded value to the jq program as a249 predefined variable. If you run jq with `--argjson foo 123`, then250 `$foo` is available in the program and has the value `123`.251252 * `--slurpfile variable-name filename`:253254 This option reads all the JSON texts in the named file and binds255 an array of the parsed JSON values to the given global variable.256 If you run jq with `--slurpfile foo bar`, then `$foo` is available257 in the program and has an array whose elements correspond to the258 texts in the file named `bar`.259260 * `--rawfile variable-name filename`:261262 This option reads in the named file and binds its contents to the given263 global variable. If you run jq with `--rawfile foo bar`, then `$foo` is264 available in the program and has a string whose contents are to the texts265 in the file named `bar`.266267 * `--args`:268269 Remaining arguments are positional string arguments. These are270 available to the jq program as `$ARGS.positional[]`.271272 * `--jsonargs`:273274 Remaining arguments are positional JSON text arguments. These275 are available to the jq program as `$ARGS.positional[]`.276277 * `--exit-status` / `-e`:278279 Sets the exit status of jq to 0 if the last output value was280 neither `false` nor `null`, 1 if the last output value was281 either `false` or `null`, or 4 if no valid result was ever282 produced. Normally jq exits with 2 if there was any usage283 problem or system error, 3 if there was a jq program compile284 error, or 0 if the jq program ran.285286 Another way to set the exit status is with the `halt_error`287 builtin function.288289 * `--binary` / `-b`:290291 Windows users using WSL, MSYS2, or Cygwin, should use this option292 when using a native jq.exe, otherwise jq will turn newlines (LFs)293 into carriage-return-then-newline (CRLF).294295 * `--version` / `-V`:296297 Output the jq version and exit with zero.298299 * `--build-configuration`:300301 Output the build configuration of jq and exit with zero.302 This output has no supported format or structure and may change303 without notice in future releases.304305 * `--help` / `-h`:306307 Output the jq help and exit with zero.308309 * `--`:310311 Terminates argument processing. Remaining arguments are not312 interpreted as options.313314 * `--run-tests [filename]`:315316 Runs the tests in the given file or standard input. This must317 be the last option given and does not honor all preceding318 options. The input consists of comment lines, empty lines, and319 program lines followed by one input line, as many lines of320 output as are expected (one per output), and a terminating empty321 line. Compilation failure tests start with a line containing322 only `%%FAIL`, then a line containing the program to compile,323 then a line containing an error message to compare to the324 actual.325326 Be warned that this option can change backwards-incompatibly.327328 - title: Basic filters329 entries:330 - title: "Identity: `.`"331 body: |332333 The absolute simplest filter is `.` . This filter takes its334 input and produces the same value as output. That is, this335 is the identity operator.336337 Since jq by default pretty-prints all output, a trivial338 program consisting of nothing but `.` can be used to format339 JSON output from, say, `curl`.340341 Although the identity filter never modifies the value of its342 input, jq processing can sometimes make it appear as though343 it does. For example, using the current implementation of344 jq, we would see that the expression:345346 1E1234567890 | .347348 produces `1.7976931348623157e+308` on at least one platform.349 This is because, in the process of parsing the number, this350 particular version of jq has converted it to an IEEE754351 double-precision representation, losing precision.352353 The way in which jq handles numbers has changed over time354 and further changes are likely within the parameters set by355 the relevant JSON standards. Moreover, build configuration356 options can alter how jq processes numbers.357358 The following remarks are therefore offered with the359 understanding that they are intended to be descriptive of the360 current version of jq and should not be interpreted as being361 prescriptive:362363 (1) Any arithmetic operation on a number that has not364 already been converted to an IEEE754 double precision365 representation will trigger a conversion to the IEEE754366 representation.367368 (2) jq will attempt to maintain the original decimal369 precision of number literals (if the `--disable-decnum`370 build configuration option was not used), but in expressions371 such `1E1234567890`, precision will be lost if the exponent372 is too large.373374 (3) In jq programs, a leading minus sign will trigger the375 conversion of the number to an IEEE754 representation.376377 (4) Comparisons are carried out using the untruncated378 big decimal representation of numbers if available, as379 illustrated in one of the following examples.380381 The examples below use the builtin function `have_decnum` in382 order to demonstrate the expected effects of using / not383 using the `--disable-decnum` build configuration option, and384 also to allow automated tests derived from these examples to385 pass regardless of whether that option is used.386387 examples:388 - program: '.'389 input: '"Hello, world!"'390 output: ['"Hello, world!"']391392 - program: '.'393 input: '0.12345678901234567890123456789'394 output: ['0.12345678901234567890123456789']395396 - program: '[., tojson] | . == if have_decnum then [12345678909876543212345,"12345678909876543212345"] else [12345678909876543000000,"12345678909876543000000"] end'397 input: '12345678909876543212345'398 output: ['true']399400 - program: '. < 0.12345678901234567890123456788'401 input: '0.12345678901234567890123456789'402 output: ['false']403404 - program: 'map([., . == 1]) | tojson | . == if have_decnum then "[[1,true],[1.000,true],[1.0,true],[1.00,true]]" else "[[1,true],[1,true],[1,true],[1,true]]" end'405 input: '[1, 1.000, 1.0, 100e-2]'406 output: ['true']407408 - program: '. as $big | [$big, $big + 1] | map(. > 10000000000000000000000000000000) | . == if have_decnum then [true, false] else [false, false] end'409 input: '10000000000000000000000000000001'410 output: ['true']411412 - title: "Object Identifier-Index: `.foo`, `.foo.bar`"413 body: |414415 The simplest *useful* filter has the form `.foo`. When given a416 JSON object (aka dictionary or hash) as input, `.foo` produces417 the value at the key "foo" if the key is present, or null otherwise.418419 A filter of the form `.foo.bar` is equivalent to `.foo | .bar`.420421 The `.foo` syntax only works for simple, identifier-like keys, that422 is, keys that are all made of alphanumeric characters and423 underscore, and which do not start with a digit.424425 If the key contains special characters or starts with a digit,426 you need to surround it with double quotes like this:427 `."foo$"`, or else `.["foo$"]`.428429 For example `.["foo::bar"]` and `.["foo.bar"]` work while430 `.foo::bar` does not.431432 examples:433 - program: '.foo'434 input: '{"foo": 42, "bar": "less interesting data"}'435 output: ['42']436437 - program: '.foo'438 input: '{"notfoo": true, "alsonotfoo": false}'439 output: ['null']440441 - program: '.["foo"]'442 input: '{"foo": 42}'443 output: ['42']444445 - title: "Optional Object Identifier-Index: `.foo?`"446 body: |447448 Just like `.foo`, but does not output an error when `.` is not an449 object.450451 examples:452 - program: '.foo?'453 input: '{"foo": 42, "bar": "less interesting data"}'454 output: ['42']455 - program: '.foo?'456 input: '{"notfoo": true, "alsonotfoo": false}'457 output: ['null']458 - program: '.["foo"]?'459 input: '{"foo": 42}'460 output: ['42']461 - program: '[.foo?]'462 input: '[1,2]'463 output: ['[]']464465 - title: "Object Index: `.[<string>]`"466 body: |467468 You can also look up fields of an object using syntax like469 `.["foo"]` (`.foo` above is a shorthand version of this, but470 only for identifier-like strings).471472 - title: "Array Index: `.[<number>]`"473 body: |474475 When the index value is an integer, `.[<number>]` can index476 arrays. Arrays are zero-based, so `.[2]` returns the third477 element.478479 Negative indices are allowed, with -1 referring to the last480 element, -2 referring to the next to last element, and so on.481482 examples:483 - program: '.[0]'484 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'485 output: ['{"name":"JSON", "good":true}']486487 - program: '.[2]'488 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'489 output: ['null']490491 - program: '.[-2]'492 input: '[1,2,3]'493 output: ['2']494495 - title: "Array/String Slice: `.[<number>:<number>]`"496 body: |497498 The `.[<number>:<number>]` syntax can be used to return a499 subarray of an array or substring of a string. The array500 returned by `.[10:15]` will be of length 5, containing the501 elements from index 10 (inclusive) to index 15 (exclusive).502 Either index may be negative (in which case it counts503 backwards from the end of the array), or omitted (in which504 case it refers to the start or end of the array).505 Indices are zero-based.506507 examples:508 - program: '.[2:4]'509 input: '["a","b","c","d","e"]'510 output: ['["c", "d"]']511512 - program: '.[2:4]'513 input: '"abcdefghi"'514 output: ['"cd"']515516 - program: '.[:3]'517 input: '["a","b","c","d","e"]'518 output: ['["a", "b", "c"]']519520 - program: '.[-2:]'521 input: '["a","b","c","d","e"]'522 output: ['["d", "e"]']523524 - title: "Array/Object Value Iterator: `.[]`"525 body: |526527 If you use the `.[index]` syntax, but omit the index528 entirely, it will return *all* of the elements of an529 array. Running `.[]` with the input `[1,2,3]` will produce the530 numbers as three separate results, rather than as a single531 array. A filter of the form `.foo[]` is equivalent to532 `.foo | .[]`.533534 You can also use this on an object, and it will return all535 the values of the object.536537 Note that the iterator operator is a generator of values.538539 examples:540 - program: '.[]'541 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'542 output:543 - '{"name":"JSON", "good":true}'544 - '{"name":"XML", "good":false}'545546 - program: '.[]'547 input: '[]'548 output: []549550 - program: '.foo[]'551 input: '{"foo":[1,2,3]}'552 output: ['1','2','3']553554 - program: '.[]'555 input: '{"a": 1, "b": 1}'556 output: ['1', '1']557558 - title: "`.[]?`"559 body: |560561 Like `.[]`, but no errors will be output if . is not an array562 or object. A filter of the form `.foo[]?` is equivalent to563 `.foo | .[]?`.564565 - title: "Comma: `,`"566 body: |567568 If two filters are separated by a comma, then the569 same input will be fed into both and the two filters' output570 value streams will be concatenated in order: first, all of the571 outputs produced by the left expression, and then all of the572 outputs produced by the right. For instance, filter `.foo,573 .bar`, produces both the "foo" fields and "bar" fields as574 separate outputs.575576 The `,` operator is one way to construct generators.577578 examples:579 - program: '.foo, .bar'580 input: '{"foo": 42, "bar": "something else", "baz": true}'581 output: ['42', '"something else"']582583 - program: ".user, .projects[]"584 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'585 output: ['"stedolan"', '"jq"', '"wikiflow"']586587 - program: '.[4,2]'588 input: '["a","b","c","d","e"]'589 output: ['"e"', '"c"']590591 - title: "Pipe: `|`"592 body: |593594 The | operator combines two filters by feeding the output(s) of595 the one on the left into the input of the one on the right. It's596 similar to the Unix shell's pipe, if you're used to that.597598 If the one on the left produces multiple results, the one on599 the right will be run for each of those results. So, the600 expression `.[] | .foo` retrieves the "foo" field of each601 element of the input array. This is a cartesian product,602 which can be surprising.603604 Note that `.a.b.c` is the same as `.a | .b | .c`.605606 Note too that `.` is the input value at the particular stage607 in a "pipeline", specifically: where the `.` expression appears.608 Thus `.a | . | .b` is the same as `.a.b`, as the `.` in the609 middle refers to whatever value `.a` produced.610611 examples:612 - program: '.[] | .name'613 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'614 output: ['"JSON"', '"XML"']615616 - title: "Parenthesis"617 body: |618619 Parenthesis work as a grouping operator just as in any typical620 programming language.621622 examples:623 - program: '(. + 2) * 5'624 input: '1'625 output: ['15']626627 - title: Types and Values628 body: |629630 jq supports the same set of datatypes as JSON - numbers,631 strings, booleans, arrays, objects (which in JSON-speak are632 hashes with only string keys), and "null".633634 Booleans, null, strings and numbers are written the same way as635 in JSON. Just like everything else in jq, these simple636 values take an input and produce an output - `42` is a valid jq637 expression that takes an input, ignores it, and returns 42638 instead.639640 Numbers in jq are internally represented by their IEEE754 double641 precision approximation. Any arithmetic operation with numbers,642 whether they are literals or results of previous filters, will643 produce a double precision floating point result.644645 However, when parsing a literal jq will store the original literal646 string. If no mutation is applied to this value then it will make647 to the output in its original form, even if conversion to double648 would result in a loss.649650 entries:651 - title: "Array construction: `[]`"652 body: |653654 As in JSON, `[]` is used to construct arrays, as in655 `[1,2,3]`. The elements of the arrays can be any jq656 expression, including a pipeline. All of the results produced657 by all of the expressions are collected into one big array.658 You can use it to construct an array out of a known quantity659 of values (as in `[.foo, .bar, .baz]`) or to "collect" all the660 results of a filter into an array (as in `[.items[].name]`)661662 Once you understand the "," operator, you can look at jq's array663 syntax in a different light: the expression `[1,2,3]` is not using a664 built-in syntax for comma-separated arrays, but is instead applying665 the `[]` operator (collect results) to the expression 1,2,3 (which666 produces three different results).667668 If you have a filter `X` that produces four results,669 then the expression `[X]` will produce a single result, an670 array of four elements.671672 examples:673 - program: "[.user, .projects[]]"674 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'675 output: ['["stedolan", "jq", "wikiflow"]']676 - program: "[ .[] | . * 2]"677 input: '[1, 2, 3]'678 output: ['[2, 4, 6]']679680 - title: "Object Construction: `{}`"681 body: |682683 Like JSON, `{}` is for constructing objects (aka684 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.685686 If the keys are "identifier-like", then the quotes can be left687 off, as in `{a:42, b:17}`. Variable references as key688 expressions use the value of the variable as the key. Key689 expressions other than constant literals, identifiers, or690 variable references, need to be parenthesized, e.g.,691 `{("a"+"b"):59}`.692693 The value can be any expression (although you may need to wrap694 it in parentheses if, for example, it contains colons), which695 gets applied to the {} expression's input (remember, all696 filters have an input and an output).697698 {foo: .bar}699700 will produce the JSON object `{"foo": 42}` if given the JSON701 object `{"bar":42, "baz":43}` as its input. You can use this702 to select particular fields of an object: if the input is an703 object with "user", "title", "id", and "content" fields and704 you just want "user" and "title", you can write705706 {user: .user, title: .title}707708 Because that is so common, there's a shortcut syntax for it:709 `{user, title}`.710711 If one of the expressions produces multiple results,712 multiple dictionaries will be produced. If the input's713714 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}715716 then the expression717718 {user, title: .titles[]}719720 will produce two outputs:721722 {"user":"stedolan", "title": "JQ Primer"}723 {"user":"stedolan", "title": "More JQ"}724725 Putting parentheses around the key means it will be evaluated as an726 expression. With the same input as above,727728 {(.user): .titles}729730 produces731732 {"stedolan": ["JQ Primer", "More JQ"]}733734 Variable references as keys use the value of the variable as735 the key. Without a value then the variable's name becomes the736 key and its value becomes the value,737738 "f o o" as $foo | "b a r" as $bar | {$foo, $bar:$foo}739740 produces741742 {"foo":"f o o","b a r":"f o o"}743744 examples:745 - program: '{user, title: .titles[]}'746 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'747 output:748 - '{"user":"stedolan", "title": "JQ Primer"}'749 - '{"user":"stedolan", "title": "More JQ"}'750 - program: '{(.user): .titles}'751 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'752 output: ['{"stedolan": ["JQ Primer", "More JQ"]}']753754 - title: "Recursive Descent: `..`"755 body: |756757 Recursively descends `.`, producing every value. This is the758 same as the zero-argument `recurse` builtin (see below). This759 is intended to resemble the XPath `//` operator. Note that760 `..a` does not work; use `.. | .a` instead. In the example761 below we use `.. | .a?` to find all the values of object keys762 "a" in any object found "below" `.`.763764 This is particularly useful in conjunction with `path(EXP)`765 (also see below) and the `?` operator.766767 examples:768 - program: '.. | .a?'769 input: '[[{"a":1}]]'770 output: ['1']771772 - title: Builtin operators and functions773 body: |774775 Some jq operators (for instance, `+`) do different things776 depending on the type of their arguments (arrays, numbers,777 etc.). However, jq never does implicit type conversions. If you778 try to add a string to an object you'll get an error message and779 no result.780781 Please note that all numbers are converted to IEEE754 double precision782 floating point representation. Arithmetic and logical operators are working783 with these converted doubles. Results of all such operations are also limited784 to the double precision.785786 The only exception to this behaviour of number is a snapshot of original number787 literal. When a number which originally was provided as a literal is never788 mutated until the end of the program then it is printed to the output in its789 original literal form. This also includes cases when the original literal790 would be truncated when converted to the IEEE754 double precision floating point791 number.792793 entries:794 - title: "Addition: `+`"795 body: |796797 The operator `+` takes two filters, applies them both798 to the same input, and adds the results together. What799 "adding" means depends on the types involved:800801 - **Numbers** are added by normal arithmetic.802803 - **Arrays** are added by being concatenated into a larger array.804805 - **Strings** are added by being joined into a larger string.806807 - **Objects** are added by merging, that is, inserting all808 the key-value pairs from both objects into a single809 combined object. If both objects contain a value for the810 same key, the object on the right of the `+` wins. (For811 recursive merge use the `*` operator.)812813 `null` can be added to any value, and returns the other814 value unchanged.815816 examples:817 - program: '.a + 1'818 input: '{"a": 7}'819 output: ['8']820 - program: '.a + .b'821 input: '{"a": [1,2], "b": [3,4]}'822 output: ['[1,2,3,4]']823 - program: '.a + null'824 input: '{"a": 1}'825 output: ['1']826 - program: '.a + 1'827 input: '{}'828 output: ['1']829 - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'830 input: 'null'831 output: ['{"a": 42, "b": 2, "c": 3}']832833 - title: "Subtraction: `-`"834 body: |835836 As well as normal arithmetic subtraction on numbers, the `-`837 operator can be used on arrays to remove all occurrences of838 the second array's elements from the first array.839840 examples:841 - program: '4 - .a'842 input: '{"a":3}'843 output: ['1']844 - program: . - ["xml", "yaml"]845 input: '["xml", "yaml", "json"]'846 output: ['["json"]']847848 - title: "Multiplication, division, modulo: `*`, `/`, `%`"849 body: |850851 These infix operators behave as expected when given two numbers.852 Division by zero raises an error. `x % y` computes x modulo y.853854 Multiplying a string by a number produces the concatenation of855 that string that many times. `"x" * 0` produces `""`.856857 Dividing a string by another splits the first using the second858 as separators.859860 Multiplying two objects will merge them recursively: this works861 like addition but if both objects contain a value for the862 same key, and the values are objects, the two are merged with863 the same strategy.864865 examples:866 - program: '10 / . * 3'867 input: '5'868 output: ['6']869 - program: '. / ", "'870 input: '"a, b,c,d, e"'871 output: ['["a","b,c,d","e"]']872 - program: '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'873 input: 'null'874 output: ['{"k": {"a": 0, "b": 2, "c": 3}}']875 - program: '.[] | (1 / .)?'876 input: '[1,0,-1]'877 output: ['1', '-1']878879 - title: "`abs`"880 body: |881882 The builtin function `abs` is defined naively as: `if . < 0 then - . else . end`.883884 For numeric input, this is the absolute value. See the885 section on the identity filter for the implications of this886 definition for numeric input.887888 To compute the absolute value of a number as a floating point number, you may wish use `fabs`.889890 examples:891 - program: 'map(abs)'892 input: '[-10, -1.1, -1e-1]'893 output: ['[10,1.1,1e-1]']894895 - title: "`length`"896 body: |897898 The builtin function `length` gets the length of various899 different types of value:900901 - The length of a **string** is the number of Unicode902 codepoints it contains (which will be the same as its903 JSON-encoded length in bytes if it's pure ASCII).904905 - The length of a **number** is its absolute value.906907 - The length of an **array** is the number of elements.908909 - The length of an **object** is the number of key-value pairs.910911 - The length of **null** is zero.912913 - It is an error to use `length` on a **boolean**.914915 examples:916 - program: '.[] | length'917 input: '[[1,2], "string", {"a":2}, null, -5]'918 output: ['2', '6', '1', '0', '5']919920921 - title: "`utf8bytelength`"922 body: |923924 The builtin function `utf8bytelength` outputs the number of925 bytes used to encode a string in UTF-8.926927 examples:928 - program: 'utf8bytelength'929 input: '"\u03bc"'930 output: ['2']931932 - title: "`keys`, `keys_unsorted`"933 body: |934935 The builtin function `keys`, when given an object, returns936 its keys in an array.937938 The keys are sorted "alphabetically", by unicode codepoint939 order. This is not an order that makes particular sense in940 any particular language, but you can count on it being the941 same for any two objects with the same set of keys,942 regardless of locale settings.943944 When `keys` is given an array, it returns the valid indices945 for that array: the integers from 0 to length-1.946947 The `keys_unsorted` function is just like `keys`, but if948 the input is an object then the keys will not be sorted,949 instead the keys will roughly be in insertion order.950951 examples:952 - program: 'keys'953 input: '{"abc": 1, "abcd": 2, "Foo": 3}'954 output: ['["Foo", "abc", "abcd"]']955 - program: 'keys'956 input: '[42,3,35]'957 output: ['[0,1,2]']958959 - title: "`has(key)`"960 body: |961962 The builtin function `has` returns whether the input object963 has the given key, or the input array has an element at the964 given index.965966 `has($key)` has the same effect as checking whether `$key`967 is a member of the array returned by `keys`, although `has`968 will be faster.969970 examples:971 - program: 'map(has("foo"))'972 input: '[{"foo": 42}, {}]'973 output: ['[true, false]']974 - program: 'map(has(2))'975 input: '[[0,1], ["a","b","c"]]'976 output: ['[false, true]']977978 - title: "`in`"979 body: |980981 The builtin function `in` returns whether or not the input key is in the982 given object, or the input index corresponds to an element983 in the given array. It is, essentially, an inversed version984 of `has`.985986 examples:987 - program: '.[] | in({"foo": 42})'988 input: '["foo", "bar"]'989 output: ['true', 'false']990 - program: 'map(in([0,1]))'991 input: '[2, 0]'992 output: ['[false, true]']993994 - title: "`map(f)`, `map_values(f)`"995 body: |996997 For any filter `f`, `map(f)` and `map_values(f)` apply `f`998 to each of the values in the input array or object, that is,999 to the values of `.[]`.10001001 In the absence of errors, `map(f)` always outputs an array1002 whereas `map_values(f)` outputs an array if given an array,1003 or an object if given an object.10041005 When the input to `map_values(f)` is an object, the output1006 object has the same keys as the input object except for1007 those keys whose values when piped to `f` produce no values1008 at all.10091010 The key difference between `map(f)` and `map_values(f)` is1011 that the former simply forms an array from all the values of1012 `($x|f)` for each value, $x, in the input array or object,1013 but `map_values(f)` only uses `first($x|f)`.10141015 Specifically, for object inputs, `map_values(f)` constructs1016 the output object by examining in turn the value of1017 `first(.[$k]|f)` for each key, $k, of the input. If this1018 expression produces no values, then the corresponding key1019 will be dropped; otherwise, the output object will have that1020 value at the key, $k.10211022 Here are some examples to clarify the behavior of `map` and1023 `map_values` when applied to arrays. These examples assume the1024 input is `[1]` in all cases:10251026 map(.+1) #=> [2]1027 map(., .) #=> [1,1]1028 map(empty) #=> []10291030 map_values(.+1) #=> [2]1031 map_values(., .) #=> [1]1032 map_values(empty) #=> []10331034 `map(f)` is equivalent to `[.[] | f]` and1035 `map_values(f)` is equivalent to `.[] |= f`.10361037 In fact, these are their implementations.103810391040 examples:1041 - program: 'map(.+1)'1042 input: '[1,2,3]'1043 output: ['[2,3,4]']10441045 - program: 'map_values(.+1)'1046 input: '{"a": 1, "b": 2, "c": 3}'1047 output: ['{"a": 2, "b": 3, "c": 4}']10481049 - program: 'map(., .)'1050 input: '[1,2]'1051 output: ['[1,1,2,2]']10521053 - program: 'map_values(. // empty)'1054 input: '{"a": null, "b": true, "c": false}'1055 output: ['{"b":true}']105610571058 - title: "`pick(pathexps)`"1059 body: |10601061 Emit the projection of the input object or array defined by the1062 specified sequence of path expressions, such that if `p` is any1063 one of these specifications, then `(. | p)` will evaluate to the1064 same value as `(. | pick(pathexps) | p)`. For arrays, negative1065 indices and `.[m:n]` specifications should not be used.10661067 examples:1068 - program: 'pick(.a, .b.c, .x)'1069 input: '{"a": 1, "b": {"c": 2, "d": 3}, "e": 4}'1070 output: ['{"a":1,"b":{"c":2},"x":null}']10711072 - program: 'pick(.[2], .[0], .[0])'1073 input: '[1,2,3,4]'1074 output: ['[1,null,3]']107510761077 - title: "`path(path_expression)`"1078 body: |10791080 Outputs array representations of the given path expression1081 in `.`. The outputs are arrays of strings (object keys)1082 and/or numbers (array indices).10831084 Path expressions are jq expressions like `.a`, but also `.[]`.1085 There are two types of path expressions: ones that can match1086 exactly, and ones that cannot. For example, `.a.b.c` is an1087 exact match path expression, while `.a[].b` is not.10881089 `path(exact_path_expression)` will produce the array1090 representation of the path expression even if it does not1091 exist in `.`, if `.` is `null` or an array or an object.10921093 `path(pattern)` will produce array representations of the1094 paths matching `pattern` if the paths exist in `.`.10951096 Note that the path expressions are not different from normal1097 expressions. The expression1098 `path(..|select(type=="boolean"))` outputs all the paths to1099 boolean values in `.`, and only those paths.11001101 examples:1102 - program: 'path(.a[0].b)'1103 input: 'null'1104 output: ['["a",0,"b"]']1105 - program: '[path(..)]'1106 input: '{"a":[{"b":1}]}'1107 output: ['[[],["a"],["a",0],["a",0,"b"]]']11081109 - title: "`del(path_expression)`"1110 body: |11111112 The builtin function `del` removes a key and its corresponding1113 value from an object.11141115 examples:1116 - program: 'del(.foo)'1117 input: '{"foo": 42, "bar": 9001, "baz": 42}'1118 output: ['{"bar": 9001, "baz": 42}']1119 - program: 'del(.[1, 2])'1120 input: '["foo", "bar", "baz"]'1121 output: ['["foo"]']11221123 - title: "`getpath(PATHS)`"1124 body: |11251126 The builtin function `getpath` outputs the values in `.` found1127 at each path in `PATHS`.11281129 examples:1130 - program: 'getpath(["a","b"])'1131 input: 'null'1132 output: ['null']1133 - program: '[getpath(["a","b"], ["a","c"])]'1134 input: '{"a":{"b":0, "c":1}}'1135 output: ['[0, 1]']11361137 - title: "`setpath(PATHS; VALUE)`"1138 body: |11391140 The builtin function `setpath` sets the `PATHS` in `.` to `VALUE`.11411142 examples:1143 - program: 'setpath(["a","b"]; 1)'1144 input: 'null'1145 output: ['{"a": {"b": 1}}']1146 - program: 'setpath(["a","b"]; 1)'1147 input: '{"a":{"b":0}}'1148 output: ['{"a": {"b": 1}}']1149 - program: 'setpath([0,"a"]; 1)'1150 input: 'null'1151 output: ['[{"a":1}]']11521153 - title: "`delpaths(PATHS)`"1154 body: |11551156 The builtin function `delpaths` deletes the `PATHS` in `.`.1157 `PATHS` must be an array of paths, where each path is an array1158 of strings and numbers.11591160 examples:1161 - program: 'delpaths([["a","b"]])'1162 input: '{"a":{"b":1},"x":{"y":2}}'1163 output: ['{"a":{},"x":{"y":2}}']11641165 - title: "`to_entries`, `from_entries`, `with_entries(f)`"1166 body: |11671168 These functions convert between an object and an array of1169 key-value pairs. If `to_entries` is passed an object, then1170 for each `k: v` entry in the input, the output array1171 includes `{"key": k, "value": v}`.11721173 `from_entries` does the opposite conversion, and `with_entries(f)`1174 is a shorthand for `to_entries | map(f) | from_entries`, useful for1175 doing some operation to all keys and values of an object.1176 `from_entries` accepts `"key"`, `"Key"`, `"name"`, `"Name"`,1177 `"value"`, and `"Value"` as keys.11781179 examples:1180 - program: 'to_entries'1181 input: '{"a": 1, "b": 2}'1182 output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']1183 - program: 'from_entries'1184 input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'1185 output: ['{"a": 1, "b": 2}']1186 - program: 'with_entries(.key |= "KEY_" + .)'1187 input: '{"a": 1, "b": 2}'1188 output: ['{"KEY_a": 1, "KEY_b": 2}']118911901191 - title: "`select(boolean_expression)`"1192 body: |11931194 The function `select(f)` produces its input unchanged if1195 `f` returns true for that input, and produces no output1196 otherwise.11971198 It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`1199 will give you `[2,3]`.12001201 examples:1202 - program: 'map(select(. >= 2))'1203 input: '[1,5,3,0,7]'1204 output: ['[5,3,7]']1205 - program: '.[] | select(.id == "second")'1206 input: '[{"id": "first", "val": 1}, {"id": "second", "val": 2}]'1207 output: ['{"id": "second", "val": 2}']120812091210 - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"1211 body: |12121213 These built-ins select only inputs that are arrays, objects,1214 iterables (arrays or objects), booleans, numbers, normal1215 numbers, finite numbers, strings, null, non-null values, and1216 non-iterables, respectively.12171218 examples:1219 - program: '.[]|numbers'1220 input: '[[],{},1,"foo",null,true,false]'1221 output: ['1']12221223 - title: "`empty`"1224 body: |12251226 `empty` returns no results. None at all. Not even `null`.12271228 It's useful on occasion. You'll know if you need it :)12291230 examples:1231 - program: '1, empty, 2'1232 input: 'null'1233 output: ['1', '2']1234 - program: '[1,2,empty,3]'1235 input: 'null'1236 output: ['[1,2,3]']12371238 - title: "`error`, `error(message)`"1239 body: |12401241 Produces an error with the input value, or with the message1242 given as the argument. Errors can be caught with try/catch;1243 see below.12441245 examples:1246 - program: 'try error catch .'1247 input: '"error message"'1248 output: ['"error message"']12491250 - program: 'try error("invalid value: \(.)") catch .'1251 input: '42'1252 output: ['"invalid value: 42"']12531254 - title: "`halt`"1255 body: |12561257 Stops the jq program with no further outputs. jq will exit1258 with exit status `0`.12591260 - title: "`halt_error`, `halt_error(exit_code)`"1261 body: |12621263 Stops the jq program with no further outputs. The input will1264 be printed on `stderr` as raw output (i.e., strings will not1265 have double quotes) with no decoration, not even a newline.12661267 The given `exit_code` (defaulting to `5`) will be jq's exit1268 status.12691270 For example, `"Error: something went wrong\n"|halt_error(1)`.12711272 - title: "`$__loc__`"1273 body: |12741275 Produces an object with a "file" key and a "line" key, with1276 the filename and line number where `$__loc__` occurs, as1277 values.12781279 examples:1280 - program: 'try error("\($__loc__)") catch .'1281 input: 'null'1282 output: ['"{\"file\":\"<top-level>\",\"line\":1}"']12831284 - title: "`paths`, `paths(node_filter)`"1285 body: |12861287 `paths` outputs the paths to all the elements in its input1288 (except it does not output the empty list, representing .1289 itself).12901291 `paths(f)` outputs the paths to any values for which `f` is `true`.1292 That is, `paths(type == "number")` outputs the paths to all numeric1293 values.12941295 examples:1296 - program: '[paths]'1297 input: '[1,[[],{"a":2}]]'1298 output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']1299 - program: '[paths(type == "number")]'1300 input: '[1,[[],{"a":2}]]'1301 output: ['[[0],[1,1,"a"]]']13021303 - title: "`add`"1304 body: |13051306 The filter `add` takes as input an array, and produces as1307 output the elements of the array added together. This might1308 mean summed, concatenated or merged depending on the types1309 of the elements of the input array - the rules are the same1310 as those for the `+` operator (described above).13111312 If the input is an empty array, `add` returns `null`.13131314 examples:1315 - program: add1316 input: '["a","b","c"]'1317 output: ['"abc"']1318 - program: add1319 input: '[1, 2, 3]'1320 output: ['6']1321 - program: add1322 input: '[]'1323 output: ["null"]13241325 - title: "`any`, `any(condition)`, `any(generator; condition)`"1326 body: |13271328 The filter `any` takes as input an array of boolean values,1329 and produces `true` as output if any of the elements of1330 the array are `true`.13311332 If the input is an empty array, `any` returns `false`.13331334 The `any(condition)` form applies the given condition to the1335 elements of the input array.13361337 The `any(generator; condition)` form applies the given1338 condition to all the outputs of the given generator.13391340 examples:1341 - program: any1342 input: '[true, false]'1343 output: ["true"]1344 - program: any1345 input: '[false, false]'1346 output: ["false"]1347 - program: any1348 input: '[]'1349 output: ["false"]13501351 - title: "`all`, `all(condition)`, `all(generator; condition)`"1352 body: |13531354 The filter `all` takes as input an array of boolean values,1355 and produces `true` as output if all of the elements of1356 the array are `true`.13571358 The `all(condition)` form applies the given condition to the1359 elements of the input array.13601361 The `all(generator; condition)` form applies the given1362 condition to all the outputs of the given generator.13631364 If the input is an empty array, `all` returns `true`.13651366 examples:1367 - program: all1368 input: '[true, false]'1369 output: ["false"]1370 - program: all1371 input: '[true, true]'1372 output: ["true"]1373 - program: all1374 input: '[]'1375 output: ["true"]13761377 - title: "`flatten`, `flatten(depth)`"1378 body: |13791380 The filter `flatten` takes as input an array of nested arrays,1381 and produces a flat array in which all arrays inside the original1382 array have been recursively replaced by their values. You can pass1383 an argument to it to specify how many levels of nesting to flatten.13841385 `flatten(2)` is like `flatten`, but going only up to two1386 levels deep.13871388 examples:1389 - program: flatten1390 input: '[1, [2], [[3]]]'1391 output: ["[1, 2, 3]"]1392 - program: flatten(1)1393 input: '[1, [2], [[3]]]'1394 output: ["[1, 2, [3]]"]1395 - program: flatten1396 input: '[[]]'1397 output: ["[]"]1398 - program: flatten1399 input: '[{"foo": "bar"}, [{"foo": "baz"}]]'1400 output: ['[{"foo": "bar"}, {"foo": "baz"}]']14011402 - title: "`range(upto)`, `range(from; upto)`, `range(from; upto; by)`"1403 body: |14041405 The `range` function produces a range of numbers. `range(4; 10)`1406 produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers1407 are produced as separate outputs. Use `[range(4; 10)]` to get a range as1408 an array.14091410 The one argument form generates numbers from 0 to the given1411 number, with an increment of 1.14121413 The two argument form generates numbers from `from` to `upto`1414 with an increment of 1.14151416 The three argument form generates numbers `from` to `upto`1417 with an increment of `by`.14181419 examples:1420 - program: 'range(2; 4)'1421 input: 'null'1422 output: ['2', '3']1423 - program: '[range(2; 4)]'1424 input: 'null'1425 output: ['[2,3]']1426 - program: '[range(4)]'1427 input: 'null'1428 output: ['[0,1,2,3]']1429 - program: '[range(0; 10; 3)]'1430 input: 'null'1431 output: ['[0,3,6,9]']1432 - program: '[range(0; 10; -1)]'1433 input: 'null'1434 output: ['[]']1435 - program: '[range(0; -5; -1)]'1436 input: 'null'1437 output: ['[0,-1,-2,-3,-4]']14381439 - title: "`floor`"1440 body: |14411442 The `floor` function returns the floor of its numeric input.14431444 examples:1445 - program: 'floor'1446 input: '3.14159'1447 output: ['3']14481449 - title: "`sqrt`"1450 body: |14511452 The `sqrt` function returns the square root of its numeric input.14531454 examples:1455 - program: 'sqrt'1456 input: '9'1457 output: ['3']14581459 - title: "`tonumber`"1460 body: |14611462 The `tonumber` function parses its input as a number. It1463 will convert correctly-formatted strings to their numeric1464 equivalent, leave numbers alone, and give an error on all other input.14651466 examples:1467 - program: '.[] | tonumber'1468 input: '[1, "1"]'1469 output: ['1', '1']14701471 - title: "`tostring`"1472 body: |14731474 The `tostring` function prints its input as a1475 string. Strings are left unchanged, and all other values are1476 JSON-encoded.14771478 examples:1479 - program: '.[] | tostring'1480 input: '[1, "1", [1]]'1481 output: ['"1"', '"1"', '"[1]"']14821483 - title: "`type`"1484 body: |14851486 The `type` function returns the type of its argument as a1487 string, which is one of null, boolean, number, string, array1488 or object.14891490 examples:1491 - program: 'map(type)'1492 input: '[0, false, [], {}, null, "hello"]'1493 output: ['["number", "boolean", "array", "object", "null", "string"]']14941495 - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1496 body: |14971498 Some arithmetic operations can yield infinities and "not a1499 number" (NaN) values. The `isinfinite` builtin returns `true`1500 if its input is infinite. The `isnan` builtin returns `true`1501 if its input is a NaN. The `infinite` builtin returns a1502 positive infinite value. The `nan` builtin returns a NaN.1503 The `isnormal` builtin returns true if its input is a normal1504 number.15051506 Note that division by zero raises an error.15071508 Currently most arithmetic operations operating on infinities,1509 NaNs, and sub-normals do not raise errors.15101511 examples:1512 - program: '.[] | (infinite * .) < 0'1513 input: '[-1, 1]'1514 output: ['true', 'false']1515 - program: 'infinite, nan | type'1516 input: 'null'1517 output: ['"number"', '"number"']15181519 - title: "`sort`, `sort_by(path_expression)`"1520 body: |15211522 The `sort` functions sorts its input, which must be an1523 array. Values are sorted in the following order:15241525 * `null`1526 * `false`1527 * `true`1528 * numbers1529 * strings, in alphabetical order (by unicode codepoint value)1530 * arrays, in lexical order1531 * objects15321533 The ordering for objects is a little complex: first they're1534 compared by comparing their sets of keys (as arrays in1535 sorted order), and if their keys are equal then the values1536 are compared key by key.15371538 `sort_by` may be used to sort by a particular field of an1539 object, or by applying any jq filter. `sort_by(f)` compares1540 two elements by comparing the result of `f` on each element.1541 When `f` produces multiple values, it firstly compares the1542 first values, and the second values if the first values are1543 equal, and so on.15441545 examples:1546 - program: 'sort'1547 input: '[8,3,null,6]'1548 output: ['[null,3,6,8]']15491550 - program: 'sort_by(.foo)'1551 input: '[{"foo":4, "bar":10}, {"foo":3, "bar":10}, {"foo":2, "bar":1}]'1552 output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":10}, {"foo":4, "bar":10}]']15531554 - program: 'sort_by(.foo, .bar)'1555 input: '[{"foo":4, "bar":10}, {"foo":3, "bar":20}, {"foo":2, "bar":1}, {"foo":3, "bar":10}]'1556 output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":10}, {"foo":3, "bar":20}, {"foo":4, "bar":10}]']15571558 - title: "`group_by(path_expression)`"1559 body: |15601561 `group_by(.foo)` takes as input an array, groups the1562 elements having the same `.foo` field into separate arrays,1563 and produces all of these arrays as elements of a larger1564 array, sorted by the value of the `.foo` field.15651566 Any jq expression, not just a field access, may be used in1567 place of `.foo`. The sorting order is the same as described1568 in the `sort` function above.15691570 examples:1571 - program: 'group_by(.foo)'1572 input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'1573 output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']15741575 - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1576 body: |15771578 Find the minimum or maximum element of the input array.15791580 The `min_by(path_exp)` and `max_by(path_exp)` functions allow1581 you to specify a particular field or property to examine, e.g.1582 `min_by(.foo)` finds the object with the smallest `foo` field.15831584 examples:1585 - program: 'min'1586 input: '[5,4,2,7]'1587 output: ['2']1588 - program: 'max_by(.foo)'1589 input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'1590 output: ['{"foo":2, "bar":3}']15911592 - title: "`unique`, `unique_by(path_exp)`"1593 body: |15941595 The `unique` function takes as input an array and produces1596 an array of the same elements, in sorted order, with1597 duplicates removed.15981599 The `unique_by(path_exp)` function will keep only one element1600 for each value obtained by applying the argument. Think of it1601 as making an array by taking one element out of every group1602 produced by `group`.16031604 examples:1605 - program: 'unique'1606 input: '[1,2,5,3,5,3,1,3]'1607 output: ['[1,2,3,5]']1608 - program: 'unique_by(.foo)'1609 input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'1610 output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']1611 - program: 'unique_by(length)'1612 input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'1613 output: ['["bacon", "chunky", "asparagus"]']16141615 - title: "`reverse`"1616 body: |16171618 This function reverses an array.16191620 examples:1621 - program: 'reverse'1622 input: '[1,2,3,4]'1623 output: ['[4,3,2,1]']16241625 - title: "`contains(element)`"1626 body: |16271628 The filter `contains(b)` will produce true if b is1629 completely contained within the input. A string B is1630 contained in a string A if B is a substring of A. An array B1631 is contained in an array A if all elements in B are1632 contained in any element in A. An object B is contained in1633 object A if all of the values in B are contained in the1634 value in A with the same key. All other types are assumed to1635 be contained in each other if they are equal.16361637 examples:1638 - program: 'contains("bar")'1639 input: '"foobar"'1640 output: ['true']1641 - program: 'contains(["baz", "bar"])'1642 input: '["foobar", "foobaz", "blarp"]'1643 output: ['true']1644 - program: 'contains(["bazzzzz", "bar"])'1645 input: '["foobar", "foobaz", "blarp"]'1646 output: ['false']1647 - program: 'contains({foo: 12, bar: [{barp: 12}]})'1648 input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1649 output: ['true']1650 - program: 'contains({foo: 12, bar: [{barp: 15}]})'1651 input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1652 output: ['false']16531654 - title: "`indices(s)`"1655 body: |16561657 Outputs an array containing the indices in `.` where `s`1658 occurs. The input may be an array, in which case if `s` is an1659 array then the indices output will be those where all elements1660 in `.` match those of `s`.16611662 examples:1663 - program: 'indices(", ")'1664 input: '"a,b, cd, efg, hijk"'1665 output: ['[3,7,12]']1666 - program: 'indices(1)'1667 input: '[0,1,2,1,3,1,4]'1668 output: ['[1,3,5]']1669 - program: 'indices([1,2])'1670 input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1671 output: ['[1,8]']16721673 - title: "`index(s)`, `rindex(s)`"1674 body: |16751676 Outputs the index of the first (`index`) or last (`rindex`)1677 occurrence of `s` in the input.16781679 examples:1680 - program: 'index(", ")'1681 input: '"a,b, cd, efg, hijk"'1682 output: ['3']1683 - program: 'index(1)'1684 input: '[0,1,2,1,3,1,4]'1685 output: ['1']1686 - program: 'index([1,2])'1687 input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1688 output: ['1']1689 - program: 'rindex(", ")'1690 input: '"a,b, cd, efg, hijk"'1691 output: ['12']1692 - program: 'rindex(1)'1693 input: '[0,1,2,1,3,1,4]'1694 output: ['5']1695 - program: 'rindex([1,2])'1696 input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1697 output: ['8']16981699 - title: "`inside`"1700 body: |17011702 The filter `inside(b)` will produce true if the input is1703 completely contained within b. It is, essentially, an1704 inversed version of `contains`.17051706 examples:1707 - program: 'inside("foobar")'1708 input: '"bar"'1709 output: ['true']1710 - program: 'inside(["foobar", "foobaz", "blarp"])'1711 input: '["baz", "bar"]'1712 output: ['true']1713 - program: 'inside(["foobar", "foobaz", "blarp"])'1714 input: '["bazzzzz", "bar"]'1715 output: ['false']1716 - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1717 input: '{"foo": 12, "bar": [{"barp": 12}]}'1718 output: ['true']1719 - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1720 input: '{"foo": 12, "bar": [{"barp": 15}]}'1721 output: ['false']17221723 - title: "`startswith(str)`"1724 body: |17251726 Outputs `true` if . starts with the given string argument.17271728 examples:1729 - program: '[.[]|startswith("foo")]'1730 input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1731 output: ['[false, true, false, true, false]']17321733 - title: "`endswith(str)`"1734 body: |17351736 Outputs `true` if . ends with the given string argument.17371738 examples:1739 - program: '[.[]|endswith("foo")]'1740 input: '["foobar", "barfoo"]'1741 output: ['[false, true]']17421743 - title: "`combinations`, `combinations(n)`"1744 body: |17451746 Outputs all combinations of the elements of the arrays in the1747 input array. If given an argument `n`, it outputs all combinations1748 of `n` repetitions of the input array.17491750 examples:1751 - program: 'combinations'1752 input: '[[1,2], [3, 4]]'1753 output: ['[1, 3]', '[1, 4]', '[2, 3]', '[2, 4]']1754 - program: 'combinations(2)'1755 input: '[0, 1]'1756 output: ['[0, 0]', '[0, 1]', '[1, 0]', '[1, 1]']17571758 - title: "`ltrimstr(str)`"1759 body: |17601761 Outputs its input with the given prefix string removed, if it1762 starts with it.17631764 examples:1765 - program: '[.[]|ltrimstr("foo")]'1766 input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1767 output: ['["fo","","barfoo","bar","afoo"]']17681769 - title: "`rtrimstr(str)`"1770 body: |17711772 Outputs its input with the given suffix string removed, if it1773 ends with it.17741775 examples:1776 - program: '[.[]|rtrimstr("foo")]'1777 input: '["fo", "foo", "barfoo", "foobar", "foob"]'1778 output: ['["fo","","bar","foobar","foob"]']17791780 - title: "`trim`, `ltrim`, `rtrim`"1781 body: |17821783 `trim` trims both leading and trailing whitespace.17841785 `ltrim` trims only leading (left side) whitespace.17861787 `rtrim` trims only trailing (right side) whitespace.17881789 Whitespace characters are the usual `" "`, `"\n"` `"\t"`, `"\r"`1790 and also all characters in the Unicode character database with the1791 whitespace property. Note that what considers whitespace might1792 change in the future.17931794 examples:1795 - program: 'trim, ltrim, rtrim'1796 input: '" abc "'1797 output: ['"abc"', '"abc "', '" abc"']17981799 - title: "`explode`"1800 body: |18011802 Converts an input string into an array of the string's1803 codepoint numbers.18041805 examples:1806 - program: 'explode'1807 input: '"foobar"'1808 output: ['[102,111,111,98,97,114]']18091810 - title: "`implode`"1811 body: |18121813 The inverse of explode.18141815 examples:1816 - program: 'implode'1817 input: '[65, 66, 67]'1818 output: ['"ABC"']18191820 - title: "`split(str)`"1821 body: |18221823 Splits an input string on the separator argument.18241825 `split` can also split on regex matches when called with1826 two arguments (see the regular expressions section below).18271828 examples:1829 - program: 'split(", ")'1830 input: '"a, b,c,d, e, "'1831 output: ['["a","b,c,d","e",""]']18321833 - title: "`join(str)`"1834 body: |18351836 Joins the array of elements given as input, using the1837 argument as separator. It is the inverse of `split`: that is,1838 running `split("foo") | join("foo")` over any input string1839 returns said input string.18401841 Numbers and booleans in the input are converted to strings.1842 Null values are treated as empty strings. Arrays and objects1843 in the input are not supported.18441845 examples:1846 - program: 'join(", ")'1847 input: '["a","b,c,d","e"]'1848 output: ['"a, b,c,d, e"']1849 - program: 'join(" ")'1850 input: '["a",1,2.3,true,null,false]'1851 output: ['"a 1 2.3 true false"']18521853 - title: "`ascii_downcase`, `ascii_upcase`"1854 body: |18551856 Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1857 converted to the specified case.18581859 examples:1860 - program: 'ascii_upcase'1861 input: '"useful but not for é"'1862 output: ['"USEFUL BUT NOT FOR é"']18631864 - title: "`while(cond; update)`"1865 body: |18661867 The `while(cond; update)` function allows you to repeatedly1868 apply an update to `.` until `cond` is false.18691870 Note that `while(cond; update)` is internally defined as a1871 recursive jq function. Recursive calls within `while` will1872 not consume additional memory if `update` produces at most one1873 output for each input. See advanced topics below.18741875 examples:1876 - program: '[while(.<100; .*2)]'1877 input: '1'1878 output: ['[1,2,4,8,16,32,64]']18791880 - title: "`repeat(exp)`"1881 body: |18821883 The `repeat(exp)` function allows you to repeatedly1884 apply expression `exp` to `.` until an error is raised.18851886 Note that `repeat(exp)` is internally defined as a1887 recursive jq function. Recursive calls within `repeat` will1888 not consume additional memory if `exp` produces at most one1889 output for each input. See advanced topics below.18901891 examples:1892 - program: '[repeat(.*2, error)?]'1893 input: '1'1894 output: ['[2]']18951896 - title: "`until(cond; next)`"1897 body: |18981899 The `until(cond; next)` function allows you to repeatedly1900 apply the expression `next`, initially to `.` then to its own1901 output, until `cond` is true. For example, this can be used1902 to implement a factorial function (see below).19031904 Note that `until(cond; next)` is internally defined as a1905 recursive jq function. Recursive calls within `until()` will1906 not consume additional memory if `next` produces at most one1907 output for each input. See advanced topics below.19081909 examples:1910 - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1911 input: '4'1912 output: ['24']191319141915 - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`"1916 body: |19171918 The `recurse(f)` function allows you to search through a1919 recursive structure, and extract interesting data from all1920 levels. Suppose your input represents a filesystem:19211922 {"name": "/", "children": [1923 {"name": "/bin", "children": [1924 {"name": "/bin/ls", "children": []},1925 {"name": "/bin/sh", "children": []}]},1926 {"name": "/home", "children": [1927 {"name": "/home/stephen", "children": [1928 {"name": "/home/stephen/jq", "children": []}]}]}]}19291930 Now suppose you want to extract all of the filenames1931 present. You need to retrieve `.name`, `.children[].name`,1932 `.children[].children[].name`, and so on. You can do this1933 with:19341935 recurse(.children[]) | .name19361937 When called without an argument, `recurse` is equivalent to1938 `recurse(.[]?)`.19391940 `recurse(f)` is identical to `recurse(f; true)` and can be1941 used without concerns about recursion depth.19421943 `recurse(f; condition)` is a generator which begins by1944 emitting . and then emits in turn .|f, .|f|f, .|f|f|f, ... so long1945 as the computed value satisfies the condition. For example,1946 to generate all the integers, at least in principle, one1947 could write `recurse(.+1; true)`.19481949 The recursive calls in `recurse` will not consume additional1950 memory whenever `f` produces at most a single output for each1951 input.19521953 examples:1954 - program: 'recurse(.foo[])'1955 input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'1956 output:1957 - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'1958 - '{"foo":[]}'1959 - '{"foo":[{"foo":[]}]}'1960 - '{"foo":[]}'19611962 - program: 'recurse'1963 input: '{"a":0,"b":[1]}'1964 output:1965 - '{"a":0,"b":[1]}'1966 - '0'1967 - '[1]'1968 - '1'19691970 - program: 'recurse(. * .; . < 20)'1971 input: '2'1972 output: ['2', '4', '16']19731974 - title: "`walk(f)`"1975 body: |19761977 The `walk(f)` function applies f recursively to every1978 component of the input entity. When an array is1979 encountered, f is first applied to its elements and then to1980 the array itself; when an object is encountered, f is first1981 applied to all the values and then to the object. In1982 practice, f will usually test the type of its input, as1983 illustrated in the following examples. The first example1984 highlights the usefulness of processing the elements of an1985 array of arrays before processing the array itself. The second1986 example shows how all the keys of all the objects within the1987 input can be considered for alteration.19881989 examples:1990 - program: 'walk(if type == "array" then sort else . end)'1991 input: '[[4, 1, 7], [8, 5, 2], [3, 6, 9]]'1992 output:1993 - '[[1,4,7],[2,5,8],[3,6,9]]'19941995 - program: 'walk( if type == "object" then with_entries( .key |= sub( "^_+"; "") ) else . end )'1996 input: '[ { "_a": { "__b": 2 } } ]'1997 output:1998 - '[{"a":{"b":2}}]'19992000 - title: "`have_literal_numbers`"2001 body: |20022003 This builtin returns true if jq's build configuration2004 includes support for preservation of input number literals.20052006 - title: "`have_decnum`"2007 body: |20082009 This builtin returns true if jq was built with "decnum",2010 which is the current literal number preserving numeric2011 backend implementation for jq.20122013 - title: "`$JQ_BUILD_CONFIGURATION`"2014 body: |20152016 This builtin binding shows the jq executable's build2017 configuration. Its value has no particular format, but2018 it can be expected to be at least the `./configure`2019 command-line arguments, and may be enriched in the2020 future to include the version strings for the build2021 tooling used.20222023 Note that this can be overriden in the command-line2024 with `--arg` and related options.20252026 - title: "`$ENV`, `env`"2027 body: |20282029 `$ENV` is an object representing the environment variables as2030 set when the jq program started.20312032 `env` outputs an object representing jq's current environment.20332034 At the moment there is no builtin for setting environment2035 variables.20362037 examples:2038 - program: '$ENV.PAGER'2039 input: 'null'2040 output: ['"less"']20412042 - program: 'env.PAGER'2043 input: 'null'2044 output: ['"less"']20452046 - title: "`transpose`"2047 body: |20482049 Transpose a possibly jagged matrix (an array of arrays).2050 Rows are padded with nulls so the result is always rectangular.20512052 examples:2053 - program: 'transpose'2054 input: '[[1], [2,3]]'2055 output: ['[[1,2],[null,3]]']20562057 - title: "`bsearch(x)`"2058 body: |20592060 `bsearch(x)` conducts a binary search for x in the input2061 array. If the input is sorted and contains x, then2062 `bsearch(x)` will return its index in the array; otherwise, if2063 the array is sorted, it will return (-1 - ix) where ix is an2064 insertion point such that the array would still be sorted2065 after the insertion of x at ix. If the array is not sorted,2066 `bsearch(x)` will return an integer that is probably of no2067 interest.20682069 examples:2070 - program: 'bsearch(0)'2071 input: '[0,1]'2072 output: ['0']2073 - program: 'bsearch(0)'2074 input: '[1,2,3]'2075 output: ['-1']2076 - program: 'bsearch(4) as $ix | if $ix < 0 then .[-(1+$ix)] = 4 else . end'2077 input: '[1,2,3]'2078 output: ['[1,2,3,4]']20792080 - title: "String interpolation: `\\(exp)`"2081 body: |20822083 Inside a string, you can put an expression inside parens2084 after a backslash. Whatever the expression returns will be2085 interpolated into the string.20862087 examples:2088 - program: '"The input was \(.), which is one less than \(.+1)"'2089 input: '42'2090 output: ['"The input was 42, which is one less than 43"']20912092 - title: "Convert to/from JSON"2093 body: |20942095 The `tojson` and `fromjson` builtins dump values as JSON texts2096 or parse JSON texts into values, respectively. The `tojson`2097 builtin differs from `tostring` in that `tostring` returns strings2098 unmodified, while `tojson` encodes strings as JSON strings.20992100 examples:2101 - program: '[.[]|tostring]'2102 input: '[1, "foo", ["foo"]]'2103 output: ['["1","foo","[\"foo\"]"]']2104 - program: '[.[]|tojson]'2105 input: '[1, "foo", ["foo"]]'2106 output: ['["1","\"foo\"","[\"foo\"]"]']2107 - program: '[.[]|tojson|fromjson]'2108 input: '[1, "foo", ["foo"]]'2109 output: ['[1,"foo",["foo"]]']21102111 - title: "Format strings and escaping"2112 body: |21132114 The `@foo` syntax is used to format and escape strings,2115 which is useful for building URLs, documents in a language2116 like HTML or XML, and so forth. `@foo` can be used as a2117 filter on its own, the possible escapings are:21182119 * `@text`:21202121 Calls `tostring`, see that function for details.21222123 * `@json`:21242125 Serializes the input as JSON.21262127 * `@html`:21282129 Applies HTML/XML escaping, by mapping the characters2130 `<>&'"` to their entity equivalents `&lt;`, `&gt;`,2131 `&amp;`, `&apos;`, `&quot;`.21322133 * `@uri`:21342135 Applies percent-encoding, by mapping all reserved URI2136 characters to a `%XX` sequence.21372138 * `@csv`:21392140 The input must be an array, and it is rendered as CSV2141 with double quotes for strings, and quotes escaped by2142 repetition.21432144 * `@tsv`:21452146 The input must be an array, and it is rendered as TSV2147 (tab-separated values). Each input array will be printed as2148 a single line. Fields are separated by a single2149 tab (ascii `0x09`). Input characters line-feed (ascii `0x0a`),2150 carriage-return (ascii `0x0d`), tab (ascii `0x09`) and2151 backslash (ascii `0x5c`) will be output as escape sequences2152 `\n`, `\r`, `\t`, `\\` respectively.21532154 * `@sh`:21552156 The input is escaped suitable for use in a command-line2157 for a POSIX shell. If the input is an array, the output2158 will be a series of space-separated strings.21592160 * `@base64`:21612162 The input is converted to base64 as specified by RFC 4648.21632164 * `@base64d`:21652166 The inverse of `@base64`, input is decoded as specified by RFC 4648.2167 Note\: If the decoded string is not UTF-8, the results are undefined.21682169 This syntax can be combined with string interpolation in a2170 useful way. You can follow a `@foo` token with a string2171 literal. The contents of the string literal will *not* be2172 escaped. However, all interpolations made inside that string2173 literal will be escaped. For instance,21742175 @uri "https://www.google.com/search?q=\(.search)"21762177 will produce the following output for the input2178 `{"search":"what is jq?"}`:21792180 "https://www.google.com/search?q=what%20is%20jq%3F"21812182 Note that the slashes, question mark, etc. in the URL are2183 not escaped, as they were part of the string literal.21842185 examples:2186 - program: '@html'2187 input: '"This works if x < y"'2188 output: ['"This works if x &lt; y"']21892190 - program: '@sh "echo \(.)"'2191 input: "\"O'Hara's Ale\""2192 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]21932194 - program: '@base64'2195 input: '"This is a message"'2196 output: ['"VGhpcyBpcyBhIG1lc3NhZ2U="']21972198 - program: '@base64d'2199 input: '"VGhpcyBpcyBhIG1lc3NhZ2U="'2200 output: ['"This is a message"']22012202 - title: "Dates"2203 body: |22042205 jq provides some basic date handling functionality, with some2206 high-level and low-level builtins. In all cases these2207 builtins deal exclusively with time in UTC.22082209 The `fromdateiso8601` builtin parses datetimes in the ISO 86012210 format to a number of seconds since the Unix epoch2211 (1970-01-01T00:00:00Z). The `todateiso8601` builtin does the2212 inverse.22132214 The `fromdate` builtin parses datetime strings. Currently2215 `fromdate` only supports ISO 8601 datetime strings, but in the2216 future it will attempt to parse datetime strings in more2217 formats.22182219 The `todate` builtin is an alias for `todateiso8601`.22202221 The `now` builtin outputs the current time, in seconds since2222 the Unix epoch.22232224 Low-level jq interfaces to the C-library time functions are2225 also provided: `strptime`, `strftime`, `strflocaltime`,2226 `mktime`, `gmtime`, and `localtime`. Refer to your host2227 operating system's documentation for the format strings used2228 by `strptime` and `strftime`. Note: these are not necessarily2229 stable interfaces in jq, particularly as to their localization2230 functionality.22312232 The `gmtime` builtin consumes a number of seconds since the2233 Unix epoch and outputs a "broken down time" representation of2234 Greenwich Mean Time as an array of numbers representing2235 (in this order): the year, the month (zero-based), the day of2236 the month (one-based), the hour of the day, the minute of the2237 hour, the second of the minute, the day of the week, and the2238 day of the year -- all one-based unless otherwise stated. The2239 day of the week number may be wrong on some systems for dates2240 before March 1st 1900, or after December 31 2099.22412242 The `localtime` builtin works like the `gmtime` builtin, but2243 using the local timezone setting.22442245 The `mktime` builtin consumes "broken down time"2246 representations of time output by `gmtime` and `strptime`.22472248 The `strptime(fmt)` builtin parses input strings matching the2249 `fmt` argument. The output is in the "broken down time"2250 representation consumed by `gmtime` and output by `mktime`.22512252 The `strftime(fmt)` builtin formats a time (GMT) with the2253 given format. The `strflocaltime` does the same, but using2254 the local timezone setting.22552256 The format strings for `strptime` and `strftime` are described2257 in typical C library documentation. The format string for ISO2258 8601 datetime is `"%Y-%m-%dT%H:%M:%SZ"`.22592260 jq may not support some or all of this date functionality on2261 some systems. In particular, the `%u` and `%j` specifiers for2262 `strptime(fmt)` are not supported on macOS.22632264 examples:2265 - program: 'fromdate'2266 input: '"2015-03-05T23:51:47Z"'2267 output: ['1425599507']22682269 - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")'2270 input: '"2015-03-05T23:51:47Z"'2271 output: ['[2015,2,5,23,51,47,4,63]']22722273 - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'2274 input: '"2015-03-05T23:51:47Z"'2275 output: ['1425599507']22762277 - title: "SQL-Style Operators"2278 body: |22792280 jq provides a few SQL-style operators.22812282 * INDEX(stream; index_expression):22832284 This builtin produces an object whose keys are computed by2285 the given index expression applied to each value from the2286 given stream.22872288 * JOIN($idx; stream; idx_expr; join_expr):22892290 This builtin joins the values from the given stream to the2291 given index. The index's keys are computed by applying the2292 given index expression to each value from the given stream.2293 An array of the value in the stream and the corresponding2294 value from the index is fed to the given join expression to2295 produce each result.22962297 * JOIN($idx; stream; idx_expr):22982299 Same as `JOIN($idx; stream; idx_expr; .)`.23002301 * JOIN($idx; idx_expr):23022303 This builtin joins the input `.` to the given index, applying2304 the given index expression to `.` to compute the index key.2305 The join operation is as described above.23062307 * IN(s):23082309 This builtin outputs `true` if `.` appears in the given2310 stream, otherwise it outputs `false`.23112312 * IN(source; s):23132314 This builtin outputs `true` if any value in the source stream2315 appears in the second stream, otherwise it outputs `false`.23162317 - title: "`builtins`"2318 body: |23192320 Returns a list of all builtin functions in the format `name/arity`.2321 Since functions with the same name but different arities are considered2322 separate functions, `all/0`, `all/1`, and `all/2` would all be present2323 in the list.23242325 - title: Conditionals and Comparisons2326 entries:2327 - title: "`==`, `!=`"2328 body: |23292330 The expression 'a == b' will produce 'true' if the results of evaluating2331 a and b are equal (that is, if they represent equivalent JSON values) and2332 'false' otherwise. In particular, strings are never considered equal2333 to numbers. In checking for the equality of JSON objects, the ordering of keys2334 is irrelevant. If you're coming from JavaScript, please note that jq's `==` is like2335 JavaScript's `===`, the "strict equality" operator.23362337 != is "not equal", and 'a != b' returns the opposite value of 'a == b'23382339 examples:2340 - program: '. == false'2341 input: 'null'2342 output: ['false']23432344 - program: '. == {"b": {"d": (4 + 1e-20), "c": 3}, "a":1}'2345 input: '{"a":1, "b": {"c": 3, "d": 4}}'2346 output: ['true']23472348 - program: '.[] == 1'2349 input: '[1, 1.0, "1", "banana"]'2350 output: ['true', 'true', 'false', 'false']23512352 - title: if-then-else-end2353 body: |23542355 `if A then B else C end` will act the same as `B` if `A`2356 produces a value other than false or null, but act the same2357 as `C` otherwise.23582359 `if A then B end` is the same as `if A then B else . end`.2360 That is, the `else` branch is optional, and if absent is the2361 same as `.`. This also applies to `elif` with absent ending `else` branch.23622363 Checking for false or null is a simpler notion of2364 "truthiness" than is found in JavaScript or Python, but it2365 means that you'll sometimes have to be more explicit about2366 the condition you want. You can't test whether, e.g. a2367 string is empty using `if .name then A else B end`; you'll2368 need something like `if .name == "" then A else B end` instead.23692370 If the condition `A` produces multiple results, then `B` is evaluated2371 once for each result that is not false or null, and `C` is evaluated2372 once for each false or null.23732374 More cases can be added to an if using `elif A then B` syntax.23752376 examples:2377 - program: |-2378 if . == 0 then2379 "zero"2380 elif . == 1 then2381 "one"2382 else2383 "many"2384 end2385 input: '2'2386 output: ['"many"']23872388 - title: "`>`, `>=`, `<=`, `<`"2389 body: |23902391 The comparison operators `>`, `>=`, `<=`, `<` return whether2392 their left argument is greater than, greater than or equal2393 to, less than or equal to or less than their right argument2394 (respectively).23952396 The ordering is the same as that described for `sort`, above.23972398 examples:2399 - program: '. < 5'2400 input: '2'2401 output: ['true']24022403 - title: "`and`, `or`, `not`"2404 body: |24052406 jq supports the normal Boolean operators `and`, `or`, `not`.2407 They have the same standard of truth as if expressions -2408 `false` and `null` are considered "false values", and2409 anything else is a "true value".24102411 If an operand of one of these operators produces multiple2412 results, the operator itself will produce a result for each input.24132414 `not` is in fact a builtin function rather than an operator,2415 so it is called as a filter to which things can be piped2416 rather than with special syntax, as in `.foo and .bar |2417 not`.24182419 These three only produce the values `true` and `false`, and2420 so are only useful for genuine Boolean operations, rather2421 than the common Perl/Python/Ruby idiom of2422 "value_that_may_be_null or default". If you want to use this2423 form of "or", picking between two values rather than2424 evaluating a condition, see the `//` operator below.24252426 examples:2427 - program: '42 and "a string"'2428 input: 'null'2429 output: ['true']2430 - program: '(true, false) or false'2431 input: 'null'2432 output: ['true', 'false']2433 - program: '(true, true) and (true, false)'2434 input: 'null'2435 output: ['true', 'false', 'true', 'false']2436 - program: '[true, false | not]'2437 input: 'null'2438 output: ['[false, true]']24392440 - title: "Alternative operator: `//`"2441 body: |24422443 The `//` operator produces all the values of its left-hand2444 side that are neither `false` nor `null`. If the2445 left-hand side produces no values other than `false` or2446 `null`, then `//` produces all the values of its right-hand2447 side.24482449 A filter of the form `a // b` produces all the results of2450 `a` that are not `false` or `null`. If `a` produces no2451 results, or no results other than `false` or `null`, then `a2452 // b` produces the results of `b`.24532454 This is useful for providing defaults: `.foo // 1` will2455 evaluate to `1` if there's no `.foo` element in the2456 input. It's similar to how `or` is sometimes used in Python2457 (jq's `or` operator is reserved for strictly Boolean2458 operations).24592460 Note: `some_generator // defaults_here` is not the same2461 as `some_generator | . // defaults_here`. The latter will2462 produce default values for all non-`false`, non-`null`2463 values of the left-hand side, while the former will not.2464 Precedence rules can make this confusing. For example, in2465 `false, 1 // 2` the left-hand side of `//` is `1`, not2466 `false, 1` -- `false, 1 // 2` parses the same way as `false,2467 (1 // 2)`. In `(false, null, 1) | . // 42` the left-hand2468 side of `//` is `.`, which always produces just one value,2469 while in `(false, null, 1) // 42` the left-hand side is a2470 generator of three values, and since it produces a2471 value other `false` and `null`, the default `42` is not2472 produced.24732474 examples:2475 - program: 'empty // 42'2476 input: 'null'2477 output: ['42']2478 - program: '.foo // 42'2479 input: '{"foo": 19}'2480 output: ['19']2481 - program: '.foo // 42'2482 input: '{}'2483 output: ['42']2484 - program: '(false, null, 1) // 42'2485 input: 'null'2486 output: ['1']2487 - program: '(false, null, 1) | . // 42'2488 input: 'null'2489 output: ['42', '42', '1']24902491 - title: try-catch2492 body: |24932494 Errors can be caught by using `try EXP catch EXP`. The first2495 expression is executed, and if it fails then the second is2496 executed with the error message. The output of the handler,2497 if any, is output as if it had been the output of the2498 expression to try.24992500 The `try EXP` form uses `empty` as the exception handler.25012502 examples:2503 - program: 'try .a catch ". is not an object"'2504 input: 'true'2505 output: ['". is not an object"']2506 - program: '[.[]|try .a]'2507 input: '[{}, true, {"a":1}]'2508 output: ['[null, 1]']2509 - program: 'try error("some exception") catch .'2510 input: 'true'2511 output: ['"some exception"']25122513 - title: Breaking out of control structures2514 body: |25152516 A convenient use of try/catch is to break out of control2517 structures like `reduce`, `foreach`, `while`, and so on.25182519 For example:25202521 # Repeat an expression until it raises "break" as an2522 # error, then stop repeating without re-raising the error.2523 # But if the error caught is not "break" then re-raise it.2524 try repeat(exp) catch if .=="break" then empty else error25252526 jq has a syntax for named lexical labels to "break" or "go (back) to":25272528 label $out | ... break $out ...25292530 The `break $label_name` expression will cause the program to2531 act as though the nearest (to the left) `label $label_name`2532 produced `empty`.25332534 The relationship between the `break` and corresponding `label`2535 is lexical: the label has to be "visible" from the break.25362537 To break out of a `reduce`, for example:25382539 label $out | reduce .[] as $item (null; if .==false then break $out else ... end)25402541 The following jq program produces a syntax error:25422543 break $out25442545 because no label `$out` is visible.25462547 - title: "Error Suppression / Optional Operator: `?`"2548 body: |25492550 The `?` operator, used as `EXP?`, is shorthand for `try EXP`.25512552 examples:2553 - program: '[.[] | .a?]'2554 input: '[{}, true, {"a":1}]'2555 output: ['[null, 1]']2556 - program: '[.[] | tonumber?]'2557 input: '["1", "invalid", "3", 4]'2558 output: ['[1, 3, 4]']25592560 - title: Regular expressions2561 body: |25622563 jq uses the2564 [Oniguruma regular expression library](https://github.com/kkos/oniguruma/blob/master/doc/RE),2565 as do PHP, TextMate, Sublime Text, etc, so the2566 description here will focus on jq specifics.25672568 Oniguruma supports several flavors of regular expression, so it is important to know2569 that jq uses the ["Perl NG" (Perl with named groups)](https://github.com/kkos/oniguruma/blob/master/doc/SYNTAX.md) flavor.25702571 The jq regex filters are defined so that they can be used using2572 one of these patterns:25732574 STRING | FILTER(REGEX)2575 STRING | FILTER(REGEX; FLAGS)2576 STRING | FILTER([REGEX])2577 STRING | FILTER([REGEX, FLAGS])25782579 where:25802581 * STRING, REGEX, and FLAGS are jq strings and subject to jq string interpolation;2582 * REGEX, after string interpolation, should be a valid regular expression;2583 * FILTER is one of `test`, `match`, or `capture`, as described below.25842585 Since REGEX must evaluate to a JSON string, some characters that are needed2586 to form a regular expression must be escaped. For example, the regular expression2587 `\s` signifying a whitespace character would be written as `"\\s"`.25882589 FLAGS is a string consisting of one of more of the supported flags:25902591 * `g` - Global search (find all matches, not just the first)2592 * `i` - Case insensitive search2593 * `m` - Multi line mode (`.` will match newlines)2594 * `n` - Ignore empty matches2595 * `p` - Both s and m modes are enabled2596 * `s` - Single line mode (`^` -> `\A`, `$` -> `\Z`)2597 * `l` - Find longest possible matches2598 * `x` - Extended regex format (ignore whitespace and comments)25992600 To match a whitespace with the `x` flag, use `\s`, e.g.26012602 jq -n '"a b" | test("a\\sb"; "x")'26032604 Note that certain flags may also be specified within REGEX, e.g.26052606 jq -n '("test", "TEst", "teST", "TEST") | test("(?i)te(?-i)st")'26072608 evaluates to: `true`, `true`, `false`, `false`.26092610 entries:2611 - title: "`test(val)`, `test(regex; flags)`"2612 body: |26132614 Like `match`, but does not return match objects, only `true` or `false`2615 for whether or not the regex matches the input.26162617 examples:2618 - program: 'test("foo")'2619 input: '"foo"'2620 output: ['true']2621 - program: '.[] | test("a b c # spaces are ignored"; "ix")'2622 input: '["xabcd", "ABC"]'2623 output: ['true', 'true']26242625 - title: "`match(val)`, `match(regex; flags)`"2626 body: |26272628 **match** outputs an object for each match it finds. Matches have2629 the following fields:26302631 * `offset` - offset in UTF-8 codepoints from the beginning of the input2632 * `length` - length in UTF-8 codepoints of the match2633 * `string` - the string that it matched2634 * `captures` - an array of objects representing capturing groups.26352636 Capturing group objects have the following fields:26372638 * `offset` - offset in UTF-8 codepoints from the beginning of the input2639 * `length` - length in UTF-8 codepoints of this capturing group2640 * `string` - the string that was captured2641 * `name` - the name of the capturing group (or `null` if it was unnamed)26422643 Capturing groups that did not match anything return an offset of -126442645 examples:2646 - program: 'match("(abc)+"; "g")'2647 input: '"abc abc"'2648 output:2649 - '{"offset": 0, "length": 3, "string": "abc", "captures": [{"offset": 0, "length": 3, "string": "abc", "name": null}]}'2650 - '{"offset": 4, "length": 3, "string": "abc", "captures": [{"offset": 4, "length": 3, "string": "abc", "name": null}]}'2651 - program: 'match("foo")'2652 input: '"foo bar foo"'2653 output: ['{"offset": 0, "length": 3, "string": "foo", "captures": []}']2654 - program: 'match(["foo", "ig"])'2655 input: '"foo bar FOO"'2656 output:2657 - '{"offset": 0, "length": 3, "string": "foo", "captures": []}'2658 - '{"offset": 8, "length": 3, "string": "FOO", "captures": []}'2659 - program: 'match("foo (?<bar123>bar)? foo"; "ig")'2660 input: '"foo bar foo foo foo"'2661 output:2662 - '{"offset": 0, "length": 11, "string": "foo bar foo", "captures": [{"offset": 4, "length": 3, "string": "bar", "name": "bar123"}]}'2663 - '{"offset": 12, "length": 8, "string": "foo foo", "captures": [{"offset": -1, "length": 0, "string": null, "name": "bar123"}]}'26642665 - program: '[ match("."; "g")] | length'2666 input: '"abc"'2667 output: ['3']266826692670 - title: "`capture(val)`, `capture(regex; flags)`"2671 body: |26722673 Collects the named captures in a JSON object, with the name2674 of each capture as the key, and the matched string as the2675 corresponding value.26762677 examples:2678 - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2679 input: '"xyzzy-14"'2680 output: ['{ "a": "xyzzy", "n": "14" }']26812682 - title: "`scan(regex)`, `scan(regex; flags)`"2683 body: |26842685 Emit a stream of the non-overlapping substrings of the input2686 that match the regex in accordance with the flags, if any2687 have been specified. If there is no match, the stream is empty.2688 To capture all the matches for each input string, use the idiom2689 `[ expr ]`, e.g. `[ scan(regex) ]`.26902691 examples:2692 - program: 'scan("c")'2693 input: '"abcdefabc"'2694 output: ['"c"', '"c"']26952696 - title: "`split(regex; flags)`"2697 body: |26982699 Splits an input string on each regex match.27002701 For backwards compatibility, when called with a single argument,2702 `split` splits on a string, not a regex.27032704 examples:2705 - program: 'split(", *"; null)'2706 input: '"ab,cd, ef"'2707 output: ['["ab","cd","ef"]']270827092710 - title: "`splits(regex)`, `splits(regex; flags)`"2711 body: |27122713 These provide the same results as their `split` counterparts,2714 but as a stream instead of an array.27152716 examples:2717 - program: 'splits(", *")'2718 input: '"ab,cd, ef, gh"'2719 output: ['"ab"','"cd"','"ef"','"gh"']27202721 - title: "`sub(regex; tostring)`, `sub(regex; tostring; flags)`"2722 body: |27232724 Emit the string obtained by replacing the first match of2725 regex in the input string with `tostring`, after2726 interpolation. `tostring` should be a jq string or a stream2727 of such strings, each of which may contain references to2728 named captures. The named captures are, in effect, presented2729 as a JSON object (as constructed by `capture`) to2730 `tostring`, so a reference to a captured variable named "x"2731 would take the form: `"\(.x)"`.27322733 examples:2734 - program: 'sub("[^a-z]*(?<x>[a-z]+)"; "Z\(.x)"; "g")'2735 input: '"123abc456def"'2736 output: ['"ZabcZdef"']27372738 - program: '[sub("(?<a>.)"; "\(.a|ascii_upcase)", "\(.a|ascii_downcase)")]'2739 input: '"aB"'2740 output: ['["AB","aB"]']27412742 - title: "`gsub(regex; tostring)`, `gsub(regex; tostring; flags)`"2743 body: |27442745 `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2746 replaced by `tostring`, after interpolation. If the second argument is a stream2747 of jq strings, then `gsub` will produce a corresponding stream of JSON strings.27482749 examples:2750 - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2751 input: '"Abcabc"'2752 output: ['"+A-+a-"']27532754 - program: '[gsub("p"; "a", "b")]'2755 input: '"p"'2756 output: ['["a","b"]']275727582759 - title: Advanced features2760 body: |2761 Variables are an absolute necessity in most programming languages, but2762 they're relegated to an "advanced feature" in jq.27632764 In most languages, variables are the only means of passing around2765 data. If you calculate a value, and you want to use it more than once,2766 you'll need to store it in a variable. To pass a value to another part2767 of the program, you'll need that part of the program to define a2768 variable (as a function parameter, object member, or whatever) in2769 which to place the data.27702771 It is also possible to define functions in jq, although this is2772 is a feature whose biggest use is defining jq's standard library2773 (many jq functions such as `map` and `select` are in fact written2774 in jq).27752776 jq has reduction operators, which are very powerful but a bit2777 tricky. Again, these are mostly used internally, to define some2778 useful bits of jq's standard library.27792780 It may not be obvious at first, but jq is all about generators2781 (yes, as often found in other languages). Some utilities are2782 provided to help deal with generators.27832784 Some minimal I/O support (besides reading JSON from standard2785 input, and writing JSON to standard output) is available.27862787 Finally, there is a module/library system.27882789 entries:2790 - title: "Variable / Symbolic Binding Operator: `... as $identifier | ...`"2791 body: |27922793 In jq, all filters have an input and an output, so manual2794 plumbing is not necessary to pass a value from one part of a program2795 to the next. Many expressions, for instance `a + b`, pass their input2796 to two distinct subexpressions (here `a` and `b` are both passed the2797 same input), so variables aren't usually necessary in order to use a2798 value twice.27992800 For instance, calculating the average value of an array of numbers2801 requires a few variables in most languages - at least one to hold the2802 array, perhaps one for each element or for a loop counter. In jq, it's2803 simply `add / length` - the `add` expression is given the array and2804 produces its sum, and the `length` expression is given the array and2805 produces its length.28062807 So, there's generally a cleaner way to solve most problems in jq than2808 defining variables. Still, sometimes they do make things easier, so jq2809 lets you define variables using `expression as $variable`. All2810 variable names start with `$`. Here's a slightly uglier version of the2811 array-averaging example:28122813 length as $array_length | add / $array_length28142815 We'll need a more complicated problem to find a situation where using2816 variables actually makes our lives easier.281728182819 Suppose we have an array of blog posts, with "author" and "title"2820 fields, and another object which is used to map author usernames to2821 real names. Our input looks like:28222823 {"posts": [{"title": "First post", "author": "anon"},2824 {"title": "A well-written article", "author": "person1"}],2825 "realnames": {"anon": "Anonymous Coward",2826 "person1": "Person McPherson"}}28272828 We want to produce the posts with the author field containing a real2829 name, as in:28302831 {"title": "First post", "author": "Anonymous Coward"}2832 {"title": "A well-written article", "author": "Person McPherson"}28332834 We use a variable, $names, to store the realnames object, so that we2835 can refer to it later when looking up author usernames:28362837 .realnames as $names | .posts[] | {title, author: $names[.author]}28382839 The expression `exp as $x | ...` means: for each value of expression2840 `exp`, run the rest of the pipeline with the entire original input, and2841 with `$x` set to that value. Thus `as` functions as something of a2842 foreach loop.28432844 Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2845 `{$foo}` is a handy way of writing `{foo: $foo}`.28462847 Multiple variables may be declared using a single `as` expression by2848 providing a pattern that matches the structure of the input2849 (this is known as "destructuring"):28502851 . as {realnames: $names, posts: [$first, $second]} | ...28522853 The variable declarations in array patterns (e.g., `. as2854 [$first, $second]`) bind to the elements of the array in from2855 the element at index zero on up, in order. When there is no2856 value at the index for an array pattern element, `null` is2857 bound to that variable.28582859 Variables are scoped over the rest of the expression that defines2860 them, so28612862 .realnames as $names | (.posts[] | {title, author: $names[.author]})28632864 will work, but28652866 (.realnames as $names | .posts[]) | {title, author: $names[.author]}28672868 won't.28692870 For programming language theorists, it's more accurate to2871 say that jq variables are lexically-scoped bindings. In2872 particular there's no way to change the value of a binding;2873 one can only setup a new binding with the same name, but which2874 will not be visible where the old one was.28752876 examples:2877 - program: '.bar as $x | .foo | . + $x'2878 input: '{"foo":10, "bar":200}'2879 output: ['210']2880 - program: '. as $i|[(.*2|. as $i| $i), $i]'2881 input: '5'2882 output: ['[10,5]']2883 - program: '. as [$a, $b, {c: $c}] | $a + $b + $c'2884 input: '[2, 3, {"c": 4, "d": 5}]'2885 output: ['9']2886 - program: '.[] as [$a, $b] | {a: $a, b: $b}'2887 input: '[[0], [0, 1], [2, 1, 0]]'2888 output: ['{"a":0,"b":null}', '{"a":0,"b":1}', '{"a":2,"b":1}']28892890 - title: 'Destructuring Alternative Operator: `?//`'2891 body: |28922893 The destructuring alternative operator provides a concise mechanism2894 for destructuring an input that can take one of several forms.28952896 Suppose we have an API that returns a list of resources and events2897 associated with them, and we want to get the user_id and timestamp of2898 the first event for each resource. The API (having been clumsily2899 converted from XML) will only wrap the events in an array if the resource2900 has multiple events:29012902 {"resources": [{"id": 1, "kind": "widget", "events": {"action": "create", "user_id": 1, "ts": 13}},2903 {"id": 2, "kind": "widget", "events": [{"action": "create", "user_id": 1, "ts": 14}, {"action": "destroy", "user_id": 1, "ts": 15}]}]}29042905 We can use the destructuring alternative operator to handle this structural change simply:29062907 .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$user_id, $ts}]} | {$user_id, $kind, $id, $ts}29082909 Or, if we aren't sure if the input is an array of values or an object:29102911 .[] as [$id, $kind, $user_id, $ts] ?// {$id, $kind, $user_id, $ts} | ...29122913 Each alternative need not define all of the same variables, but all named2914 variables will be available to the subsequent expression. Variables not2915 matched in the alternative that succeeded will be `null`:29162917 .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$first_user_id, $first_ts}]} | {$user_id, $first_user_id, $kind, $id, $ts, $first_ts}29182919 Additionally, if the subsequent expression returns an error, the2920 alternative operator will attempt to try the next binding. Errors2921 that occur during the final alternative are passed through.29222923 [[3]] | .[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end29242925 examples:2926 - program: '.[] as {$a, $b, c: {$d, $e}} ?// {$a, $b, c: [{$d, $e}]} | {$a, $b, $d, $e}'2927 input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2928 output: ['{"a":1,"b":2,"d":3,"e":4}', '{"a":1,"b":2,"d":3,"e":4}']2929 - program: '.[] as {$a, $b, c: {$d}} ?// {$a, $b, c: [{$e}]} | {$a, $b, $d, $e}'2930 input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2931 output: ['{"a":1,"b":2,"d":3,"e":null}', '{"a":1,"b":2,"d":null,"e":4}']2932 - program: '.[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end'2933 input: '[[3]]'2934 output: ['{"a":null,"b":3}']29352936 - title: 'Defining Functions'2937 body: |29382939 You can give a filter a name using "def" syntax:29402941 def increment: . + 1;29422943 From then on, `increment` is usable as a filter just like a2944 builtin function (in fact, this is how many of the builtins2945 are defined). A function may take arguments:29462947 def map(f): [.[] | f];29482949 Arguments are passed as _filters_ (functions with no2950 arguments), _not_ as values. The same argument may be2951 referenced multiple times with different inputs (here `f` is2952 run for each element of the input array). Arguments to a2953 function work more like callbacks than like value arguments.2954 This is important to understand. Consider:29552956 def foo(f): f|f;2957 5|foo(.*2)29582959 The result will be 20 because `f` is `.*2`, and during the2960 first invocation of `f` `.` will be 5, and the second time it2961 will be 10 (5 * 2), so the result will be 20. Function2962 arguments are filters, and filters expect an input when2963 invoked.29642965 If you want the value-argument behaviour for defining simple2966 functions, you can just use a variable:29672968 def addvalue(f): f as $f | map(. + $f);29692970 Or use the short-hand:29712972 def addvalue($f): ...;29732974 With either definition, `addvalue(.foo)` will add the current2975 input's `.foo` field to each element of the array. Do note2976 that calling `addvalue(.[])` will cause the `map(. + $f)` part2977 to be evaluated once per value in the value of `.` at the call2978 site.29792980 Multiple definitions using the same function name are allowed.2981 Each re-definition replaces the previous one for the same2982 number of function arguments, but only for references from2983 functions (or main program) subsequent to the re-definition.2984 See also the section below on scoping.29852986 examples:2987 - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'2988 input: '[[1,2],[10,20]]'2989 output: ['[[1,2,1], [10,20,10]]']2990 - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'2991 input: '[[1,2],[10,20]]'2992 output: ['[[1,2,1,2], [10,20,1,2]]']29932994 - title: 'Scoping'2995 body: |29962997 There are two types of symbols in jq: value bindings (a.k.a.,2998 "variables"), and functions. Both are scoped lexically,2999 with expressions being able to refer only to symbols that3000 have been defined "to the left" of them. The only exception3001 to this rule is that functions can refer to themselves so as3002 to be able to create recursive functions.30033004 For example, in the following expression there is a binding3005 which is visible "to the right" of it, `... | .*3 as3006 $times_three | [. + $times_three] | ...`, but not "to the3007 left". Consider this expression now, `... | (.*3 as3008 $times_three | [. + $times_three]) | ...`: here the binding3009 `$times_three` is _not_ visible past the closing parenthesis.30103011 - title: "`isempty(exp)`"3012 body: |30133014 Returns true if `exp` produces no outputs, false otherwise.30153016 examples:3017 - program: 'isempty(empty)'3018 input: 'null'3019 output: ['true']30203021 - program: 'isempty(.[])'3022 input: '[]'3023 output: ['true']30243025 - program: 'isempty(.[])'3026 input: '[1,2,3]'3027 output: ['false']30283029 - title: "`limit(n; exp)`"3030 body: |30313032 The `limit` function extracts up to `n` outputs from `exp`.30333034 examples:3035 - program: '[limit(3;.[])]'3036 input: '[0,1,2,3,4,5,6,7,8,9]'3037 output: ['[0,1,2]']30383039 - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"3040 body: |30413042 The `first(expr)` and `last(expr)` functions extract the first3043 and last values from `expr`, respectively.30443045 The `nth(n; expr)` function extracts the nth value output by `expr`.3046 Note that `nth(n; expr)` doesn't support negative values of `n`.30473048 examples:3049 - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'3050 input: '10'3051 output: ['[0,9,5]']30523053 - title: "`first`, `last`, `nth(n)`"3054 body: |30553056 The `first` and `last` functions extract the first3057 and last values from any array at `.`.30583059 The `nth(n)` function extracts the nth value of any array at `.`.30603061 examples:3062 - program: '[range(.)]|[first, last, nth(5)]'3063 input: '10'3064 output: ['[0,9,5]']30653066 - title: "`reduce`"3067 body: |30683069 The `reduce` syntax allows you to combine all of the results of3070 an expression by accumulating them into a single answer.3071 The form is `reduce EXP as $var (INIT; UPDATE)`.3072 As an example, we'll pass `[1,2,3]` to this expression:30733074 reduce .[] as $item (0; . + $item)30753076 For each result that `.[]` produces, `. + $item` is run to3077 accumulate a running total, starting from 0 as the input value.3078 In this example, `.[]` produces the results `1`, `2`, and `3`,3079 so the effect is similar to running something like this:30803081 0 | 1 as $item | . + $item |3082 2 as $item | . + $item |3083 3 as $item | . + $item30843085 examples:3086 - program: 'reduce .[] as $item (0; . + $item)'3087 input: '[1,2,3,4,5]'3088 output: ['15']30893090 - program: 'reduce .[] as [$i,$j] (0; . + $i * $j)'3091 input: '[[1,2],[3,4],[5,6]]'3092 output: ['44']30933094 - program: 'reduce .[] as {$x,$y} (null; .x += $x | .y += [$y])'3095 input: '[{"x":"a","y":1},{"x":"b","y":2},{"x":"c","y":3}]'3096 output: ['{"x":"abc","y":[1,2,3]}']30973098 - title: "`foreach`"3099 body: |31003101 The `foreach` syntax is similar to `reduce`, but intended to3102 allow the construction of `limit` and reducers that produce3103 intermediate results.31043105 The form is `foreach EXP as $var (INIT; UPDATE; EXTRACT)`.3106 As an example, we'll pass `[1,2,3]` to this expression:31073108 foreach .[] as $item (0; . + $item; [$item, . * 2])31093110 Like the `reduce` syntax, `. + $item` is run for each result3111 that `.[]` produces, but `[$item, . * 2]` is run for each3112 intermediate values. In this example, since the intermediate3113 values are `1`, `3`, and `6`, the `foreach` expression produces3114 `[1,2]`, `[2,6]`, and `[3,12]`. So the effect is similar3115 to running something like this:31163117 0 | 1 as $item | . + $item | [$item, . * 2],3118 2 as $item | . + $item | [$item, . * 2],3119 3 as $item | . + $item | [$item, . * 2]31203121 When `EXTRACT` is omitted, the identity filter is used.3122 That is, it outputs the intermediate values as they are.31233124 examples:3125 - program: 'foreach .[] as $item (0; . + $item)'3126 input: '[1,2,3,4,5]'3127 output: ['1','3','6','10','15']31283129 - program: 'foreach .[] as $item (0; . + $item; [$item, . * 2])'3130 input: '[1,2,3,4,5]'3131 output: ['[1,2]','[2,6]','[3,12]','[4,20]','[5,30]']31323133 - program: 'foreach .[] as $item (0; . + 1; {index: ., $item})'3134 input: '["foo", "bar", "baz"]'3135 output:3136 - '{"index":1,"item":"foo"}'3137 - '{"index":2,"item":"bar"}'3138 - '{"index":3,"item":"baz"}'31393140 - title: Recursion3141 body: |31423143 As described above, `recurse` uses recursion, and any jq3144 function can be recursive. The `while` builtin is also3145 implemented in terms of recursion.31463147 Tail calls are optimized whenever the expression to the left of3148 the recursive call outputs its last value. In practice this3149 means that the expression to the left of the recursive call3150 should not produce more than one output for each input.31513152 For example:31533154 def recurse(f): def r: ., (f | select(. != null) | r); r;31553156 def while(cond; update):3157 def _while:3158 if cond then ., (update | _while) else empty end;3159 _while;31603161 def repeat(exp):3162 def _repeat:3163 exp, _repeat;3164 _repeat;31653166 - title: Generators and iterators3167 body: |31683169 Some jq operators and functions are actually generators in3170 that they can produce zero, one, or more values for each3171 input, just as one might expect in other programming3172 languages that have generators. For example, `.[]`3173 generates all the values in its input (which must be an3174 array or an object), `range(0; 10)` generates the integers3175 between 0 and 10, and so on.31763177 Even the comma operator is a generator, generating first3178 the values generated by the expression to the left of the3179 comma, then the values generated by the expression on the3180 right of the comma.31813182 The `empty` builtin is the generator that produces zero3183 outputs. The `empty` builtin backtracks to the preceding3184 generator expression.31853186 All jq functions can be generators just by using builtin3187 generators. It is also possible to construct new generators3188 using only recursion and the comma operator. If3189 recursive calls are "in tail position" then the3190 generator will be efficient. In the example below the3191 recursive call by `_range` to itself is in tail position.3192 The example shows off three advanced topics: tail recursion,3193 generator construction, and sub-functions.31943195 examples:3196 - program: 'def range(init; upto; by):3197 def _range:3198 if (by > 0 and . < upto) or (by < 0 and . > upto)3199 then ., ((.+by)|_range)3200 else . end;3201 if by == 0 then init else init|_range end |3202 select((by > 0 and . < upto) or (by < 0 and . > upto));3203 range(0; 10; 3)'3204 input: 'null'3205 output: ['0', '3', '6', '9']3206 - program: 'def while(cond; update):3207 def _while:3208 if cond then ., (update | _while) else empty end;3209 _while;3210 [while(.<100; .*2)]'3211 input: '1'3212 output: ['[1,2,4,8,16,32,64]']32133214 - title: 'Math'3215 body: |32163217 jq currently only has IEEE754 double-precision (64-bit) floating3218 point number support.32193220 Besides simple arithmetic operators such as `+`, jq also has most3221 standard math functions from the C math library. C math functions3222 that take a single input argument (e.g., `sin()`) are available as3223 zero-argument jq functions. C math functions that take two input3224 arguments (e.g., `pow()`) are available as two-argument jq3225 functions that ignore `.`. C math functions that take three input3226 arguments are available as three-argument jq functions that ignore3227 `.`.32283229 Availability of standard math functions depends on the3230 availability of the corresponding math functions in your operating3231 system and C math library. Unavailable math functions will be3232 defined but will raise an error.32333234 One-input C math functions: `acos` `acosh` `asin` `asinh` `atan`3235 `atanh` `cbrt` `ceil` `cos` `cosh` `erf` `erfc` `exp` `exp10`3236 `exp2` `expm1` `fabs` `floor` `gamma` `j0` `j1` `lgamma` `log`3237 `log10` `log1p` `log2` `logb` `nearbyint` `rint` `round`3238 `significand` `sin` `sinh` `sqrt` `tan` `tanh` `tgamma` `trunc`3239 `y0` `y1`.32403241 Two-input C math functions: `atan2` `copysign` `drem` `fdim`3242 `fmax` `fmin` `fmod` `frexp` `hypot` `jn` `ldexp` `modf`3243 `nextafter` `nexttoward` `pow` `remainder` `scalb` `scalbln` `yn`.32443245 Three-input C math functions: `fma`.32463247 See your system's manual for more information on each of these.32483249 - title: 'I/O'3250 body: |32513252 At this time jq has minimal support for I/O, mostly in the3253 form of control over when inputs are read. Two builtins functions3254 are provided for this, `input` and `inputs`, that read from the3255 same sources (e.g., `stdin`, files named on the command-line) as3256 jq itself. These two builtins, and jq's own reading actions, can3257 be interleaved with each other. They are commonly used in combination3258 with the null input option `-n` to prevent one input from being read3259 implicitly.32603261 Two builtins provide minimal output capabilities, `debug`, and3262 `stderr`. (Recall that a jq program's output values are always3263 output as JSON texts on `stdout`.) The `debug` builtin can have3264 application-specific behavior, such as for executables that use3265 the libjq C API but aren't the jq executable itself. The `stderr`3266 builtin outputs its input in raw mode to stder with no additional3267 decoration, not even a newline.32683269 Most jq builtins are referentially transparent, and yield constant3270 and repeatable value streams when applied to constant inputs.3271 This is not true of I/O builtins.32723273 entries:3274 - title: "`input`"3275 body: |32763277 Outputs one new input.32783279 Note that when using `input` it is generally be necessary to3280 invoke jq with the `-n` command-line option, otherwise3281 the first entity will be lost.32823283 echo 1 2 3 4 | jq '[., input]' # [1,2] [3,4]32843285 - title: "`inputs`"3286 body: |32873288 Outputs all remaining inputs, one by one.32893290 This is primarily useful for reductions over a program's3291 inputs. Note that when using `inputs` it is generally necessary3292 to invoke jq with the `-n` command-line option, otherwise3293 the first entity will be lost.32943295 echo 1 2 3 | jq -n 'reduce inputs as $i (0; . + $i)' # 632963297 - title: "`debug`, `debug(msgs)`"3298 body: |32993300 These two filters are like `.` but have as a side-effect the3301 production of one or more messages on stderr.33023303 The message produced by the `debug` filter has the form33043305 ["DEBUG:",<input-value>]33063307 where `<input-value>` is a compact rendition of the input3308 value. This format may change in the future.33093310 The `debug(msgs)` filter is defined as `(msgs | debug | empty), .`3311 thus allowing great flexibility in the content of the message,3312 while also allowing multi-line debugging statements to be created.33133314 For example, the expression:33153316 1 as $x | 2 | debug("Entering function foo with $x == \($x)", .) | (.+1)33173318 would produce the value 3 but with the following two lines3319 being written to stderr:33203321 ["DEBUG:","Entering function foo with $x == 1"]3322 ["DEBUG:",2]33233324 - title: "`stderr`"3325 body: |33263327 Prints its input in raw and compact mode to stderr with no3328 additional decoration, not even a newline.33293330 - title: "`input_filename`"3331 body: |33323333 Returns the name of the file whose input is currently being3334 filtered. Note that this will not work well unless jq is3335 running in a UTF-8 locale.33363337 - title: "`input_line_number`"3338 body: |33393340 Returns the line number of the input currently being filtered.33413342 - title: 'Streaming'3343 body: |33443345 With the `--stream` option jq can parse input texts in a streaming3346 fashion, allowing jq programs to start processing large JSON texts3347 immediately rather than after the parse completes. If you have a3348 single JSON text that is 1GB in size, streaming it will allow you3349 to process it much more quickly.33503351 However, streaming isn't easy to deal with as the jq program will3352 have `[<path>, <leaf-value>]` (and a few other forms) as inputs.33533354 Several builtins are provided to make handling streams easier.33553356 The examples below use the streamed form of `[0,[1]]`, which is3357 `[[0],0],[[1,0],1],[[1,0]],[[1]]`.33583359 Streaming forms include `[<path>, <leaf-value>]` (to indicate any3360 scalar value, empty array, or empty object), and `[<path>]` (to3361 indicate the end of an array or object). Future versions of jq3362 run with `--stream` and `--seq` may output additional forms such3363 as `["error message"]` when an input text fails to parse.33643365 entries:3366 - title: "`truncate_stream(stream_expression)`"3367 body: |33683369 Consumes a number as input and truncates the corresponding3370 number of path elements from the left of the outputs of the3371 given streaming expression.33723373 examples:3374 - program: 'truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])'3375 input: '1'3376 output: ['[[0],2]', '[[0]]']33773378 - title: "`fromstream(stream_expression)`"3379 body: |33803381 Outputs values corresponding to the stream expression's3382 outputs.33833384 examples:3385 - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'3386 input: 'null'3387 output: ['[2]']33883389 - title: "`tostream`"3390 body: |33913392 The `tostream` builtin outputs the streamed form of its input.33933394 examples:3395 - program: '. as $dot|fromstream($dot|tostream)|.==$dot'3396 input: '[0,[1,{"a":1},{"b":2}]]'3397 output: ['true']33983399 - title: Assignment3400 body: |3401 Assignment works a little differently in jq than in most3402 programming languages. jq doesn't distinguish between references3403 to and copies of something - two objects or arrays are either3404 equal or not equal, without any further notion of being "the3405 same object" or "not the same object".34063407 If an object has two fields which are arrays, `.foo` and `.bar`,3408 and you append something to `.foo`, then `.bar` will not get3409 bigger, even if you've previously set `.bar = .foo`. If you're3410 used to programming in languages like Python, Java, Ruby,3411 JavaScript, etc. then you can think of it as though jq does a full3412 deep copy of every object before it does the assignment (for3413 performance it doesn't actually do that, but that's the general3414 idea).34153416 This means that it's impossible to build circular values in jq3417 (such as an array whose first element is itself). This is quite3418 intentional, and ensures that anything a jq program can produce3419 can be represented in JSON.34203421 All the assignment operators in jq have path expressions on the3422 left-hand side (LHS). The right-hand side (RHS) provides values3423 to set to the paths named by the LHS path expressions.34243425 Values in jq are always immutable. Internally, assignment works3426 by using a reduction to compute new, replacement values for `.` that3427 have had all the desired assignments applied to `.`, then3428 outputting the modified value. This might be made clear by this3429 example: `{a:{b:{c:1}}} | (.a.b|=3), .`. This will output3430 `{"a":{"b":3}}` and `{"a":{"b":{"c":1}}}` because the last3431 sub-expression, `.`, sees the original value, not the modified3432 value.34333434 Most users will want to use modification assignment operators,3435 such as `|=` or `+=`, rather than `=`.34363437 Note that the LHS of assignment operators refers to a value in3438 `.`. Thus `$var.foo = 1` won't work as expected (`$var.foo` is3439 not a valid or useful path expression in `.`); use `$var | .foo =3440 1` instead.34413442 Note too that `.a,.b=0` does not set `.a` and `.b`, but3443 `(.a,.b)=0` sets both.34443445 entries:3446 - title: "Update-assignment: `|=`"3447 body: |3448 This is the "update" operator `|=`. It takes a filter on the3449 right-hand side and works out the new value for the property3450 of `.` being assigned to by running the old value through this3451 expression. For instance, `(.foo, .bar) |= .+1` will build an3452 object with the `foo` field set to the input's `foo` plus 1,3453 and the `bar` field set to the input's `bar` plus 1.34543455 The left-hand side can be any general path expression; see `path()`.34563457 Note that the left-hand side of `|=` refers to a value in `.`.3458 Thus `$var.foo |= . + 1` won't work as expected (`$var.foo` is3459 not a valid or useful path expression in `.`); use `$var |3460 .foo |= . + 1` instead.34613462 If the right-hand side outputs no values (i.e., `empty`), then3463 the left-hand side path will be deleted, as with `del(path)`.34643465 If the right-hand side outputs multiple values, only the first3466 one will be used (COMPATIBILITY NOTE: in jq 1.5 and earlier3467 releases, it used to be that only the last one was used).34683469 examples:3470 - program: '(..|select(type=="boolean")) |= if . then 1 else 0 end'3471 input: '[true,false,[5,true,[true,[false]],false]]'3472 output: ['[1,0,[5,1,[1,[0]],0]]']34733474 - title: "Arithmetic update-assignment: `+=`, `-=`, `*=`, `/=`, `%=`, `//=`"3475 body: |34763477 jq has a few operators of the form `a op= b`, which are all3478 equivalent to `a |= . op b`. So, `+= 1` can be used to3479 increment values, being the same as `|= . + 1`.34803481 examples:3482 - program: .foo += 13483 input: '{"foo": 42}'3484 output: ['{"foo": 43}']34853486 - title: "Plain assignment: `=`"3487 body: |34883489 This is the plain assignment operator. Unlike the others, the3490 input to the right-hand side (RHS) is the same as the input to3491 the left-hand side (LHS) rather than the value at the LHS3492 path, and all values output by the RHS will be used (as shown3493 below).34943495 If the RHS of `=` produces multiple values, then for each such3496 value jq will set the paths on the left-hand side to the value3497 and then it will output the modified `.`. For example,3498 `(.a,.b) = range(2)` outputs `{"a":0,"b":0}`, then3499 `{"a":1,"b":1}`. The "update" assignment forms (see above) do3500 not do this.35013502 This example should show the difference between `=` and `|=`:35033504 Provide input `{"a": {"b": 10}, "b": 20}` to the programs35053506 .a = .b35073508 and35093510 .a |= .b35113512 The former will set the `a` field of the input to the `b`3513 field of the input, and produce the output `{"a": 20, "b": 20}`.3514 The latter will set the `a` field of the input to the `a`3515 field's `b` field, producing `{"a": 10, "b": 20}`.35163517 examples:3518 - program: .a = .b3519 input: '{"a": {"b": 10}, "b": 20}'3520 output: ['{"a":20,"b":20}']35213522 - program: .a |= .b3523 input: '{"a": {"b": 10}, "b": 20}'3524 output: ['{"a":10,"b":20}']35253526 - program: (.a, .b) = range(3)3527 input: 'null'3528 output:3529 - '{"a":0,"b":0}'3530 - '{"a":1,"b":1}'3531 - '{"a":2,"b":2}'35323533 - program: (.a, .b) |= range(3)3534 input: 'null'3535 output: ['{"a":0,"b":0}']35363537 - title: Complex assignments3538 body: |3539 Lots more things are allowed on the left-hand side of a jq assignment3540 than in most languages. We've already seen simple field accesses on3541 the left hand side, and it's no surprise that array accesses work just3542 as well:35433544 .posts[0].title = "JQ Manual"35453546 What may come as a surprise is that the expression on the left may3547 produce multiple results, referring to different points in the input3548 document:35493550 .posts[].comments |= . + ["this is great"]35513552 That example appends the string "this is great" to the "comments"3553 array of each post in the input (where the input is an object with a3554 field "posts" which is an array of posts).35553556 When jq encounters an assignment like 'a = b', it records the "path"3557 taken to select a part of the input document while executing a. This3558 path is then used to find which part of the input to change while3559 executing the assignment. Any filter may be used on the3560 left-hand side of an equals - whichever paths it selects from the3561 input will be where the assignment is performed.35623563 This is a very powerful operation. Suppose we wanted to add a comment3564 to blog posts, using the same "blog" input above. This time, we only3565 want to comment on the posts written by "stedolan". We can find those3566 posts using the "select" function described earlier:35673568 .posts[] | select(.author == "stedolan")35693570 The paths provided by this operation point to each of the posts that3571 "stedolan" wrote, and we can comment on each of them in the same way3572 that we did before:35733574 (.posts[] | select(.author == "stedolan") | .comments) |=3575 . + ["terrible."]35763577 - title: Comments35783579 body: |35803581 You can write comments in your jq filters using `#`.35823583 A `#` character (not part of a string) starts a comment.3584 All characters from `#` to the end of the line are ignored.35853586 If the end of the line is preceded by an odd number of backslash3587 characters, the following line is also considered part of the3588 comment and is ignored.35893590 For example, the following code outputs `[1,3,4,7]`35913592 [3593 1,3594 # foo \3595 2,3596 # bar \\3597 3,3598 4, # baz \\\3599 5, \3600 6,3601 73602 # comment \3603 comment \3604 comment3605 ]36063607 Backslash continuing the comment on the next line can be useful3608 when writing the "shebang" for a jq script:36093610 #!/bin/sh --3611 # total - Output the sum of the given arguments (or stdin)3612 # usage: total [numbers...]3613 # \3614 exec jq --args -MRnf "$0" -- "$@"36153616 $ARGS.positional |3617 reduce (3618 if . == []3619 then inputs3620 else .[]3621 end |3622 . as $dot |3623 try tonumber catch false |3624 if not or isnan then3625 @json "total: Invalid number \($dot).\n" | halt_error(1)3626 end3627 ) as $n (0; . + $n)36283629 The `exec` line is considered a comment by jq, so it is ignored.3630 But it is not ignored by `sh`, since in `sh` a backslash at the3631 end of the line does not continue the comment.3632 With this trick, when the script is invoked as `total 1 2`,3633 `/bin/sh -- /path/to/total 1 2` will be run, and `sh` will then3634 run `exec jq --args -MRnf /path/to/total -- 1 2` replacing itself3635 with a `jq` interpreter invoked with the specified options (`-M`,3636 `-R`, `-n`, `--args`), that evaluates the current file (`$0`),3637 with the arguments (`$@`) that were passed to `sh`.36383639 - title: Modules3640 body: |36413642 jq has a library/module system. Modules are files whose names end3643 in `.jq`.36443645 Modules imported by a program are searched for in a default search3646 path (see below). The `import` and `include` directives allow the3647 importer to alter this path.36483649 Paths in the search path are subject to various substitutions.36503651 For paths starting with `~/`, the user's home directory is3652 substituted for `~`.36533654 For paths starting with `$ORIGIN/`, the directory where the jq3655 executable is located is substituted for `$ORIGIN`.36563657 For paths starting with `./` or paths that are `.`, the path of3658 the including file is substituted for `.`. For top-level programs3659 given on the command-line, the current directory is used.36603661 Import directives can optionally specify a search path to which3662 the default is appended.36633664 The default search path is the search path given to the `-L`3665 command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",3666 "$ORIGIN/../lib"]`.36673668 Null and empty string path elements terminate search path3669 processing.36703671 A dependency with relative path `foo/bar` would be searched for in3672 `foo/bar.jq` and `foo/bar/bar.jq` in the given search path. This3673 is intended to allow modules to be placed in a directory along3674 with, for example, version control files, README files, and so on,3675 but also to allow for single-file modules.36763677 Consecutive components with the same name are not allowed to avoid3678 ambiguities (e.g., `foo/foo`).36793680 For example, with `-L$HOME/.jq` a module `foo` can be found in3681 `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.36823683 If `$HOME/.jq` is a file, it is sourced into the main program.36843685 entries:3686 - title: "`import RelativePathString as NAME [<metadata>];`"3687 body: |36883689 Imports a module found at the given path relative to a3690 directory in a search path. A `.jq` suffix will be added to3691 the relative path string. The module's symbols are prefixed3692 with `NAME::`.36933694 The optional metadata must be a constant jq expression. It3695 should be an object with keys like `homepage` and so on. At3696 this time jq only uses the `search` key/value of the metadata.3697 The metadata is also made available to users via the3698 `modulemeta` builtin.36993700 The `search` key in the metadata, if present, should have a3701 string or array value (array of strings); this is the search3702 path to be prefixed to the top-level search path.37033704 - title: "`include RelativePathString [<metadata>];`"3705 body: |37063707 Imports a module found at the given path relative to a3708 directory in a search path as if it were included in place. A3709 `.jq` suffix will be added to the relative path string. The3710 module's symbols are imported into the caller's namespace as3711 if the module's content had been included directly.37123713 The optional metadata must be a constant jq expression. It3714 should be an object with keys like `homepage` and so on. At3715 this time jq only uses the `search` key/value of the metadata.3716 The metadata is also made available to users via the3717 `modulemeta` builtin.37183719 - title: "`import RelativePathString as $NAME [<metadata>];`"3720 body: |37213722 Imports a JSON file found at the given path relative to a3723 directory in a search path. A `.json` suffix will be added to3724 the relative path string. The file's data will be available3725 as `$NAME::NAME`.37263727 The optional metadata must be a constant jq expression. It3728 should be an object with keys like `homepage` and so on. At3729 this time jq only uses the `search` key/value of the metadata.3730 The metadata is also made available to users via the3731 `modulemeta` builtin.37323733 The `search` key in the metadata, if present, should have a3734 string or array value (array of strings); this is the search3735 path to be prefixed to the top-level search path.37363737 - title: "`module <metadata>;`"3738 body: |37393740 This directive is entirely optional. It's not required for3741 proper operation. It serves only the purpose of providing3742 metadata that can be read with the `modulemeta` builtin.37433744 The metadata must be a constant jq expression. It should be3745 an object with keys like `homepage`. At this time jq doesn't3746 use this metadata, but it is made available to users via the3747 `modulemeta` builtin.37483749 - title: "`modulemeta`"3750 body: |37513752 Takes a module name as input and outputs the module's metadata3753 as an object, with the module's imports (including metadata)3754 as an array value for the `deps` key and the module's defined3755 functions as an array value for the `defs` key.37563757 Programs can use this to query a module's metadata, which they3758 could then use to, for example, search for, download, and3759 install missing dependencies.37603761 - title: Colors3762 body: |37633764 To configure alternative colors just set the `JQ_COLORS`3765 environment variable to colon-delimited list of partial terminal3766 escape sequences like `"1;31"`, in this order:37673768 - color for `null`3769 - color for `false`3770 - color for `true`3771 - color for numbers3772 - color for strings3773 - color for arrays3774 - color for objects3775 - color for object keys37763777 The default color scheme is the same as setting3778 `JQ_COLORS="0;90:0;39:0;39:0;39:0;32:1;39:1;39:1;34"`.37793780 This is not a manual for VT100/ANSI escapes. However, each of3781 these color specifications should consist of two numbers separated3782 by a semi-colon, where the first number is one of these:37833784 - 1 (bright)3785 - 2 (dim)3786 - 4 (underscore)3787 - 5 (blink)3788 - 7 (reverse)3789 - 8 (hidden)37903791 and the second is one of these:37923793 - 30 (black)3794 - 31 (red)3795 - 32 (green)3796 - 33 (yellow)3797 - 34 (blue)3798 - 35 (magenta)3799 - 36 (cyan)3800 - 37 (white)
modified:docs/content/manual/v1.3/manual.yml-5 removed
1---2headline: jq 1.3 Manual34history: |56 *The manual for the development version of jq can be found7 [here](../).*84body: |56 A jq program is a "filter": it takes an input, and produces an7 output. There are a lot of builtin filters for extracting a
1252 unmodified lines
modified:docs/content/manual/v1.4/manual.yml-5 removed
1---2headline: jq 1.4 Manual34history: |56 *The manual for the development version of jq can be found7 [here](../).*84body: |56 A jq program is a "filter": it takes an input, and produces an7 output. There are a lot of builtin filters for extracting a
1658 unmodified lines
modified:docs/content/manual/v1.5/manual.yml-5 removed
1---2headline: jq 1.5 Manual34history: |56 *The manual for the development version of jq can be found7 [here](../).*84body: |56 A jq program is a "filter": it takes an input, and produces an7 output. There are a lot of builtin filters for extracting a
2922 unmodified lines
modified:docs/content/manual/v1.6/manual.yml-5 removed
1---2headline: jq 1.6 Manual34history: |56 *The manual for the development version of jq can be found7 [here](../).*84body: |56 A jq program is a "filter": it takes an input, and produces an7 output. There are a lot of builtin filters for extracting a
3356 unmodified lines
modified:docs/content/manual/v1.7/manual.yml-5 removed
1---2headline: jq 1.7 Manual34history: |56 *The manual for the development version of jq can be found7 [here](../).*84body: |56 A jq program is a "filter": it takes an input, and produces an7 output. There are a lot of builtin filters for extracting a
3690 unmodified lines
modified:docs/content/manual/manual.yml+1 added-3805 removed
1---2headline: jq Manual (development version)34history: |56 *For released versions, see [jq 1.7](./v1.7/), [jq 1.6](./v1.6/), [jq 1.5](./v1.5/),7 [jq 1.4](./v1.4/) or [jq 1.3](./v1.3/).*89body: |1011 A jq program is a "filter": it takes an input, and produces an12 output. There are a lot of builtin filters for extracting a13 particular field of an object, or converting a number to a string,14 or various other standard tasks.1516 Filters can be combined in various ways - you can pipe the output of17 one filter into another filter, or collect the output of a filter18 into an array.1920 Some filters produce multiple results, for instance there's one that21 produces all the elements of its input array. Piping that filter22 into a second runs the second filter for each element of the23 array. Generally, things that would be done with loops and iteration24 in other languages are just done by gluing filters together in jq.2526 It's important to remember that every filter has an input and an27 output. Even literals like "hello" or 42 are filters - they take an28 input but always produce the same literal as output. Operations that29 combine two filters, like addition, generally feed the same input to30 both and combine the results. So, you can implement an averaging31 filter as `add / length` - feeding the input array both to the `add`32 filter and the `length` filter and then performing the division.3334 But that's getting ahead of ourselves. :) Let's start with something35 simpler:3637manpage_intro: |38 jq(1) -- Command-line JSON processor39 ====================================4041 ## SYNOPSIS4243 `jq` [<options>...] <filter> [<files>...]4445 `jq` can transform JSON in various ways, by selecting, iterating,46 reducing and otherwise mangling JSON documents. For instance,47 running the command `jq 'map(.price) | add'` will take an array of48 JSON objects as input and return the sum of their "price" fields.4950 `jq` can accept text input as well, but by default, `jq` reads a51 stream of JSON entities (including numbers and other literals) from52 `stdin`. Whitespace is only needed to separate entities such as 153 and 2, and true and false. One or more <files> may be specified, in54 which case `jq` will read input from those instead.5556 The <options> are described in the [INVOKING JQ] section; they57 mostly concern input and output formatting. The <filter> is written58 in the jq language and specifies how to transform the input59 file or document.6061 ## FILTERS6263manpage_epilogue: |64 ## BUGS6566 Presumably. Report them or discuss them at:6768 https://github.com/jqlang/jq/issues6970 ## AUTHOR7172 Stephen Dolan `<mu@netsoc.tcd.ie>`7374sections:75 - title: Invoking jq76 body: |7778 jq filters run on a stream of JSON data. The input to jq is79 parsed as a sequence of whitespace-separated JSON values which80 are passed through the provided filter one at a time. The81 output(s) of the filter are written to standard output, as a82 sequence of newline-separated JSON data.8384 The simplest and most common filter (or jq program) is `.`,85 which is the identity operator, copying the inputs of the jq86 processor to the output stream. Because the default behavior of87 the jq processor is to read JSON texts from the input stream,88 and to pretty-print outputs, the `.` program's main use is to89 validate and pretty-print the inputs. The jq programming90 language is quite rich and allows for much more than just91 validation and pretty-printing.9293 Note: it is important to mind the shell's quoting rules. As a94 general rule it's best to always quote (with single-quote95 characters on Unix shells) the jq program, as too many characters with special96 meaning to jq are also shell meta-characters. For example, `jq97 "foo"` will fail on most Unix shells because that will be the same98 as `jq foo`, which will generally fail because `foo is not99 defined`. When using the Windows command shell (cmd.exe) it's100 best to use double quotes around your jq program when given on the101 command-line (instead of the `-f program-file` option), but then102 double-quotes in the jq program need backslash escaping. When using103 the Powershell (`powershell.exe`) or the Powershell Core104 (`pwsh`/`pwsh.exe`), use single-quote characters around the jq105 program and backslash-escaped double-quotes (`\"`) inside the jq106 program.107108 * Unix shells: `jq '.["foo"]'`109 * Powershell: `jq '.[\"foo\"]'`110 * Windows command shell: `jq ".[\"foo\"]"`111112 Note: jq allows user-defined functions, but every jq program113 must have a top-level expression.114115 You can affect how jq reads and writes its input and output116 using some command-line options:117118 * `--null-input` / `-n`:119120 Don't read any input at all. Instead, the filter is run once121 using `null` as the input. This is useful when using jq as a122 simple calculator or to construct JSON data from scratch.123124 * `--raw-input` / `-R`:125126 Don't parse the input as JSON. Instead, each line of text is127 passed to the filter as a string. If combined with `--slurp`,128 then the entire input is passed to the filter as a single long129 string.130131 * `--slurp` / `-s`:132133 Instead of running the filter for each JSON object in the134 input, read the entire input stream into a large array and run135 the filter just once.136137 * `--compact-output` / `-c`:138139 By default, jq pretty-prints JSON output. Using this option140 will result in more compact output by instead putting each141 JSON object on a single line.142143 * `--raw-output` / `-r`:144145 With this option, if the filter's result is a string then it146 will be written directly to standard output rather than being147 formatted as a JSON string with quotes. This can be useful for148 making jq filters talk to non-JSON-based systems.149150 * `--raw-output0`:151152 Like `-r` but jq will print NUL instead of newline after each output.153 This can be useful when the values being output can contain newlines.154 When the output value contains NUL, jq exits with non-zero code.155156 * `--join-output` / `-j`:157158 Like `-r` but jq won't print a newline after each output.159160 * `--ascii-output` / `-a`:161162 jq usually outputs non-ASCII Unicode codepoints as UTF-8, even163 if the input specified them as escape sequences (like164 "\u03bc"). Using this option, you can force jq to produce pure165 ASCII output with every non-ASCII character replaced with the166 equivalent escape sequence.167168 * `--sort-keys` / `-S`:169170 Output the fields of each object with the keys in sorted order.171172 * `--color-output` / `-C` and `--monochrome-output` / `-M`:173174 By default, jq outputs colored JSON if writing to a175 terminal. You can force it to produce color even if writing to176 a pipe or a file using `-C`, and disable color with `-M`.177 When the `NO_COLOR` environment variable is not empty, jq disables178 colored output by default, but you can enable it by `-C`.179180 Colors can be configured with the `JQ_COLORS` environment181 variable (see below).182183 * `--tab`:184185 Use a tab for each indentation level instead of two spaces.186187 * `--indent n`:188189 Use the given number of spaces (no more than 7) for indentation.190191 * `--unbuffered`:192193 Flush the output after each JSON object is printed (useful if194 you're piping a slow data source into jq and piping jq's195 output elsewhere).196197 * `--stream`:198199 Parse the input in streaming fashion, outputting arrays of path200 and leaf values (scalars and empty arrays or empty objects).201 For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]`202 becomes `[[0],[]]`, `[[1],"a"]`, and `[[2,0],"b"]`.203204 This is useful for processing very large inputs. Use this in205 conjunction with filtering and the `reduce` and `foreach` syntax206 to reduce large inputs incrementally.207208 * `--stream-errors`:209210 Like `--stream`, but invalid JSON inputs yield array values211 where the first element is the error and the second is a path.212 For example, `["a",n]` produces `["Invalid literal at line 1,213 column 7",[1]]`.214215 Implies `--stream`. Invalid JSON inputs produce no error values216 when `--stream` without `--stream-errors`.217218 * `--seq`:219220 Use the `application/json-seq` MIME type scheme for separating221 JSON texts in jq's input and output. This means that an ASCII222 RS (record separator) character is printed before each value on223 output and an ASCII LF (line feed) is printed after every224 output. Input JSON texts that fail to parse are ignored (but225 warned about), discarding all subsequent input until the next226 RS. This mode also parses the output of jq without the `--seq`227 option.228229 * `-f filename` / `--from-file filename`:230231 Read filter from the file rather than from a command line, like232 awk's -f option.233234 * `-L directory`:235236 Prepend `directory` to the search list for modules. If this237 option is used then no builtin search list is used. See the238 section on modules below.239240 * `--arg name value`:241242 This option passes a value to the jq program as a predefined243 variable. If you run jq with `--arg foo bar`, then `$foo` is244 available in the program and has the value `"bar"`. Note that245 `value` will be treated as a string, so `--arg foo 123` will246 bind `$foo` to `"123"`.247248 Named arguments are also available to the jq program as249 `$ARGS.named`.250251 * `--argjson name JSON-text`:252253 This option passes a JSON-encoded value to the jq program as a254 predefined variable. If you run jq with `--argjson foo 123`, then255 `$foo` is available in the program and has the value `123`.256257 * `--slurpfile variable-name filename`:258259 This option reads all the JSON texts in the named file and binds260 an array of the parsed JSON values to the given global variable.261 If you run jq with `--slurpfile foo bar`, then `$foo` is available262 in the program and has an array whose elements correspond to the263 texts in the file named `bar`.264265 * `--rawfile variable-name filename`:266267 This option reads in the named file and binds its contents to the given268 global variable. If you run jq with `--rawfile foo bar`, then `$foo` is269 available in the program and has a string whose contents are to the texts270 in the file named `bar`.271272 * `--args`:273274 Remaining arguments are positional string arguments. These are275 available to the jq program as `$ARGS.positional[]`.276277 * `--jsonargs`:278279 Remaining arguments are positional JSON text arguments. These280 are available to the jq program as `$ARGS.positional[]`.281282 * `--exit-status` / `-e`:283284 Sets the exit status of jq to 0 if the last output value was285 neither `false` nor `null`, 1 if the last output value was286 either `false` or `null`, or 4 if no valid result was ever287 produced. Normally jq exits with 2 if there was any usage288 problem or system error, 3 if there was a jq program compile289 error, or 0 if the jq program ran.290291 Another way to set the exit status is with the `halt_error`292 builtin function.293294 * `--binary` / `-b`:295296 Windows users using WSL, MSYS2, or Cygwin, should use this option297 when using a native jq.exe, otherwise jq will turn newlines (LFs)298 into carriage-return-then-newline (CRLF).299300 * `--version` / `-V`:301302 Output the jq version and exit with zero.303304 * `--build-configuration`:305306 Output the build configuration of jq and exit with zero.307 This output has no supported format or structure and may change308 without notice in future releases.309310 * `--help` / `-h`:311312 Output the jq help and exit with zero.313314 * `--`:315316 Terminates argument processing. Remaining arguments are not317 interpreted as options.318319 * `--run-tests [filename]`:320321 Runs the tests in the given file or standard input. This must322 be the last option given and does not honor all preceding323 options. The input consists of comment lines, empty lines, and324 program lines followed by one input line, as many lines of325 output as are expected (one per output), and a terminating empty326 line. Compilation failure tests start with a line containing327 only `%%FAIL`, then a line containing the program to compile,328 then a line containing an error message to compare to the329 actual.330331 Be warned that this option can change backwards-incompatibly.332333 - title: Basic filters334 entries:335 - title: "Identity: `.`"336 body: |337338 The absolute simplest filter is `.` . This filter takes its339 input and produces the same value as output. That is, this340 is the identity operator.341342 Since jq by default pretty-prints all output, a trivial343 program consisting of nothing but `.` can be used to format344 JSON output from, say, `curl`.345346 Although the identity filter never modifies the value of its347 input, jq processing can sometimes make it appear as though348 it does. For example, using the current implementation of349 jq, we would see that the expression:350351 1E1234567890 | .352353 produces `1.7976931348623157e+308` on at least one platform.354 This is because, in the process of parsing the number, this355 particular version of jq has converted it to an IEEE754356 double-precision representation, losing precision.357358 The way in which jq handles numbers has changed over time359 and further changes are likely within the parameters set by360 the relevant JSON standards. Moreover, build configuration361 options can alter how jq processes numbers.362363 The following remarks are therefore offered with the364 understanding that they are intended to be descriptive of the365 current version of jq and should not be interpreted as being366 prescriptive:367368 (1) Any arithmetic operation on a number that has not369 already been converted to an IEEE754 double precision370 representation will trigger a conversion to the IEEE754371 representation.372373 (2) jq will attempt to maintain the original decimal374 precision of number literals (if the `--disable-decnum`375 build configuration option was not used), but in expressions376 such `1E1234567890`, precision will be lost if the exponent377 is too large.378379 (3) In jq programs, a leading minus sign will trigger the380 conversion of the number to an IEEE754 representation.381382 (4) Comparisons are carried out using the untruncated383 big decimal representation of numbers if available, as384 illustrated in one of the following examples.385386 The examples below use the builtin function `have_decnum` in387 order to demonstrate the expected effects of using / not388 using the `--disable-decnum` build configuration option, and389 also to allow automated tests derived from these examples to390 pass regardless of whether that option is used.391392 examples:393 - program: '.'394 input: '"Hello, world!"'395 output: ['"Hello, world!"']396397 - program: '.'398 input: '0.12345678901234567890123456789'399 output: ['0.12345678901234567890123456789']400401 - program: '[., tojson] | . == if have_decnum then [12345678909876543212345,"12345678909876543212345"] else [12345678909876543000000,"12345678909876543000000"] end'402 input: '12345678909876543212345'403 output: ['true']404405 - program: '. < 0.12345678901234567890123456788'406 input: '0.12345678901234567890123456789'407 output: ['false']408409 - program: 'map([., . == 1]) | tojson | . == if have_decnum then "[[1,true],[1.000,true],[1.0,true],[1.00,true]]" else "[[1,true],[1,true],[1,true],[1,true]]" end'410 input: '[1, 1.000, 1.0, 100e-2]'411 output: ['true']412413 - program: '. as $big | [$big, $big + 1] | map(. > 10000000000000000000000000000000) | . == if have_decnum then [true, false] else [false, false] end'414 input: '10000000000000000000000000000001'415 output: ['true']416417 - title: "Object Identifier-Index: `.foo`, `.foo.bar`"418 body: |419420 The simplest *useful* filter has the form `.foo`. When given a421 JSON object (aka dictionary or hash) as input, `.foo` produces422 the value at the key "foo" if the key is present, or null otherwise.423424 A filter of the form `.foo.bar` is equivalent to `.foo | .bar`.425426 The `.foo` syntax only works for simple, identifier-like keys, that427 is, keys that are all made of alphanumeric characters and428 underscore, and which do not start with a digit.429430 If the key contains special characters or starts with a digit,431 you need to surround it with double quotes like this:432 `."foo$"`, or else `.["foo$"]`.433434 For example `.["foo::bar"]` and `.["foo.bar"]` work while435 `.foo::bar` does not.436437 examples:438 - program: '.foo'439 input: '{"foo": 42, "bar": "less interesting data"}'440 output: ['42']441442 - program: '.foo'443 input: '{"notfoo": true, "alsonotfoo": false}'444 output: ['null']445446 - program: '.["foo"]'447 input: '{"foo": 42}'448 output: ['42']449450 - title: "Optional Object Identifier-Index: `.foo?`"451 body: |452453 Just like `.foo`, but does not output an error when `.` is not an454 object.455456 examples:457 - program: '.foo?'458 input: '{"foo": 42, "bar": "less interesting data"}'459 output: ['42']460 - program: '.foo?'461 input: '{"notfoo": true, "alsonotfoo": false}'462 output: ['null']463 - program: '.["foo"]?'464 input: '{"foo": 42}'465 output: ['42']466 - program: '[.foo?]'467 input: '[1,2]'468 output: ['[]']469470 - title: "Object Index: `.[<string>]`"471 body: |472473 You can also look up fields of an object using syntax like474 `.["foo"]` (`.foo` above is a shorthand version of this, but475 only for identifier-like strings).476477 - title: "Array Index: `.[<number>]`"478 body: |479480 When the index value is an integer, `.[<number>]` can index481 arrays. Arrays are zero-based, so `.[2]` returns the third482 element.483484 Negative indices are allowed, with -1 referring to the last485 element, -2 referring to the next to last element, and so on.486487 examples:488 - program: '.[0]'489 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'490 output: ['{"name":"JSON", "good":true}']491492 - program: '.[2]'493 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'494 output: ['null']495496 - program: '.[-2]'497 input: '[1,2,3]'498 output: ['2']499500 - title: "Array/String Slice: `.[<number>:<number>]`"501 body: |502503 The `.[<number>:<number>]` syntax can be used to return a504 subarray of an array or substring of a string. The array505 returned by `.[10:15]` will be of length 5, containing the506 elements from index 10 (inclusive) to index 15 (exclusive).507 Either index may be negative (in which case it counts508 backwards from the end of the array), or omitted (in which509 case it refers to the start or end of the array).510 Indices are zero-based.511512 examples:513 - program: '.[2:4]'514 input: '["a","b","c","d","e"]'515 output: ['["c", "d"]']516517 - program: '.[2:4]'518 input: '"abcdefghi"'519 output: ['"cd"']520521 - program: '.[:3]'522 input: '["a","b","c","d","e"]'523 output: ['["a", "b", "c"]']524525 - program: '.[-2:]'526 input: '["a","b","c","d","e"]'527 output: ['["d", "e"]']528529 - title: "Array/Object Value Iterator: `.[]`"530 body: |531532 If you use the `.[index]` syntax, but omit the index533 entirely, it will return *all* of the elements of an534 array. Running `.[]` with the input `[1,2,3]` will produce the535 numbers as three separate results, rather than as a single536 array. A filter of the form `.foo[]` is equivalent to537 `.foo | .[]`.538539 You can also use this on an object, and it will return all540 the values of the object.541542 Note that the iterator operator is a generator of values.543544 examples:545 - program: '.[]'546 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'547 output:548 - '{"name":"JSON", "good":true}'549 - '{"name":"XML", "good":false}'550551 - program: '.[]'552 input: '[]'553 output: []554555 - program: '.foo[]'556 input: '{"foo":[1,2,3]}'557 output: ['1','2','3']558559 - program: '.[]'560 input: '{"a": 1, "b": 1}'561 output: ['1', '1']562563 - title: "`.[]?`"564 body: |565566 Like `.[]`, but no errors will be output if . is not an array567 or object. A filter of the form `.foo[]?` is equivalent to568 `.foo | .[]?`.569570 - title: "Comma: `,`"571 body: |572573 If two filters are separated by a comma, then the574 same input will be fed into both and the two filters' output575 value streams will be concatenated in order: first, all of the576 outputs produced by the left expression, and then all of the577 outputs produced by the right. For instance, filter `.foo,578 .bar`, produces both the "foo" fields and "bar" fields as579 separate outputs.580581 The `,` operator is one way to construct generators.582583 examples:584 - program: '.foo, .bar'585 input: '{"foo": 42, "bar": "something else", "baz": true}'586 output: ['42', '"something else"']587588 - program: ".user, .projects[]"589 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'590 output: ['"stedolan"', '"jq"', '"wikiflow"']591592 - program: '.[4,2]'593 input: '["a","b","c","d","e"]'594 output: ['"e"', '"c"']595596 - title: "Pipe: `|`"597 body: |598599 The | operator combines two filters by feeding the output(s) of600 the one on the left into the input of the one on the right. It's601 similar to the Unix shell's pipe, if you're used to that.602603 If the one on the left produces multiple results, the one on604 the right will be run for each of those results. So, the605 expression `.[] | .foo` retrieves the "foo" field of each606 element of the input array. This is a cartesian product,607 which can be surprising.608609 Note that `.a.b.c` is the same as `.a | .b | .c`.610611 Note too that `.` is the input value at the particular stage612 in a "pipeline", specifically: where the `.` expression appears.613 Thus `.a | . | .b` is the same as `.a.b`, as the `.` in the614 middle refers to whatever value `.a` produced.615616 examples:617 - program: '.[] | .name'618 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'619 output: ['"JSON"', '"XML"']620621 - title: "Parenthesis"622 body: |623624 Parenthesis work as a grouping operator just as in any typical625 programming language.626627 examples:628 - program: '(. + 2) * 5'629 input: '1'630 output: ['15']631632 - title: Types and Values633 body: |634635 jq supports the same set of datatypes as JSON - numbers,636 strings, booleans, arrays, objects (which in JSON-speak are637 hashes with only string keys), and "null".638639 Booleans, null, strings and numbers are written the same way as640 in JSON. Just like everything else in jq, these simple641 values take an input and produce an output - `42` is a valid jq642 expression that takes an input, ignores it, and returns 42643 instead.644645 Numbers in jq are internally represented by their IEEE754 double646 precision approximation. Any arithmetic operation with numbers,647 whether they are literals or results of previous filters, will648 produce a double precision floating point result.649650 However, when parsing a literal jq will store the original literal651 string. If no mutation is applied to this value then it will make652 to the output in its original form, even if conversion to double653 would result in a loss.654655 entries:656 - title: "Array construction: `[]`"657 body: |658659 As in JSON, `[]` is used to construct arrays, as in660 `[1,2,3]`. The elements of the arrays can be any jq661 expression, including a pipeline. All of the results produced662 by all of the expressions are collected into one big array.663 You can use it to construct an array out of a known quantity664 of values (as in `[.foo, .bar, .baz]`) or to "collect" all the665 results of a filter into an array (as in `[.items[].name]`)666667 Once you understand the "," operator, you can look at jq's array668 syntax in a different light: the expression `[1,2,3]` is not using a669 built-in syntax for comma-separated arrays, but is instead applying670 the `[]` operator (collect results) to the expression 1,2,3 (which671 produces three different results).672673 If you have a filter `X` that produces four results,674 then the expression `[X]` will produce a single result, an675 array of four elements.676677 examples:678 - program: "[.user, .projects[]]"679 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'680 output: ['["stedolan", "jq", "wikiflow"]']681 - program: "[ .[] | . * 2]"682 input: '[1, 2, 3]'683 output: ['[2, 4, 6]']684685 - title: "Object Construction: `{}`"686 body: |687688 Like JSON, `{}` is for constructing objects (aka689 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.690691 If the keys are "identifier-like", then the quotes can be left692 off, as in `{a:42, b:17}`. Variable references as key693 expressions use the value of the variable as the key. Key694 expressions other than constant literals, identifiers, or695 variable references, need to be parenthesized, e.g.,696 `{("a"+"b"):59}`.697698 The value can be any expression (although you may need to wrap699 it in parentheses if, for example, it contains colons), which700 gets applied to the {} expression's input (remember, all701 filters have an input and an output).702703 {foo: .bar}704705 will produce the JSON object `{"foo": 42}` if given the JSON706 object `{"bar":42, "baz":43}` as its input. You can use this707 to select particular fields of an object: if the input is an708 object with "user", "title", "id", and "content" fields and709 you just want "user" and "title", you can write710711 {user: .user, title: .title}712713 Because that is so common, there's a shortcut syntax for it:714 `{user, title}`.715716 If one of the expressions produces multiple results,717 multiple dictionaries will be produced. If the input's718719 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}720721 then the expression722723 {user, title: .titles[]}724725 will produce two outputs:726727 {"user":"stedolan", "title": "JQ Primer"}728 {"user":"stedolan", "title": "More JQ"}729730 Putting parentheses around the key means it will be evaluated as an731 expression. With the same input as above,732733 {(.user): .titles}734735 produces736737 {"stedolan": ["JQ Primer", "More JQ"]}738739 Variable references as keys use the value of the variable as740 the key. Without a value then the variable's name becomes the741 key and its value becomes the value,742743 "f o o" as $foo | "b a r" as $bar | {$foo, $bar:$foo}744745 produces746747 {"foo":"f o o","b a r":"f o o"}748749 examples:750 - program: '{user, title: .titles[]}'751 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'752 output:753 - '{"user":"stedolan", "title": "JQ Primer"}'754 - '{"user":"stedolan", "title": "More JQ"}'755 - program: '{(.user): .titles}'756 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'757 output: ['{"stedolan": ["JQ Primer", "More JQ"]}']758759 - title: "Recursive Descent: `..`"760 body: |761762 Recursively descends `.`, producing every value. This is the763 same as the zero-argument `recurse` builtin (see below). This764 is intended to resemble the XPath `//` operator. Note that765 `..a` does not work; use `.. | .a` instead. In the example766 below we use `.. | .a?` to find all the values of object keys767 "a" in any object found "below" `.`.768769 This is particularly useful in conjunction with `path(EXP)`770 (also see below) and the `?` operator.771772 examples:773 - program: '.. | .a?'774 input: '[[{"a":1}]]'775 output: ['1']776777 - title: Builtin operators and functions778 body: |779780 Some jq operators (for instance, `+`) do different things781 depending on the type of their arguments (arrays, numbers,782 etc.). However, jq never does implicit type conversions. If you783 try to add a string to an object you'll get an error message and784 no result.785786 Please note that all numbers are converted to IEEE754 double precision787 floating point representation. Arithmetic and logical operators are working788 with these converted doubles. Results of all such operations are also limited789 to the double precision.790791 The only exception to this behaviour of number is a snapshot of original number792 literal. When a number which originally was provided as a literal is never793 mutated until the end of the program then it is printed to the output in its794 original literal form. This also includes cases when the original literal795 would be truncated when converted to the IEEE754 double precision floating point796 number.797798 entries:799 - title: "Addition: `+`"800 body: |801802 The operator `+` takes two filters, applies them both803 to the same input, and adds the results together. What804 "adding" means depends on the types involved:805806 - **Numbers** are added by normal arithmetic.807808 - **Arrays** are added by being concatenated into a larger array.809810 - **Strings** are added by being joined into a larger string.811812 - **Objects** are added by merging, that is, inserting all813 the key-value pairs from both objects into a single814 combined object. If both objects contain a value for the815 same key, the object on the right of the `+` wins. (For816 recursive merge use the `*` operator.)817818 `null` can be added to any value, and returns the other819 value unchanged.820821 examples:822 - program: '.a + 1'823 input: '{"a": 7}'824 output: ['8']825 - program: '.a + .b'826 input: '{"a": [1,2], "b": [3,4]}'827 output: ['[1,2,3,4]']828 - program: '.a + null'829 input: '{"a": 1}'830 output: ['1']831 - program: '.a + 1'832 input: '{}'833 output: ['1']834 - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'835 input: 'null'836 output: ['{"a": 42, "b": 2, "c": 3}']837838 - title: "Subtraction: `-`"839 body: |840841 As well as normal arithmetic subtraction on numbers, the `-`842 operator can be used on arrays to remove all occurrences of843 the second array's elements from the first array.844845 examples:846 - program: '4 - .a'847 input: '{"a":3}'848 output: ['1']849 - program: . - ["xml", "yaml"]850 input: '["xml", "yaml", "json"]'851 output: ['["json"]']852853 - title: "Multiplication, division, modulo: `*`, `/`, `%`"854 body: |855856 These infix operators behave as expected when given two numbers.857 Division by zero raises an error. `x % y` computes x modulo y.858859 Multiplying a string by a number produces the concatenation of860 that string that many times. `"x" * 0` produces `""`.861862 Dividing a string by another splits the first using the second863 as separators.864865 Multiplying two objects will merge them recursively: this works866 like addition but if both objects contain a value for the867 same key, and the values are objects, the two are merged with868 the same strategy.869870 examples:871 - program: '10 / . * 3'872 input: '5'873 output: ['6']874 - program: '. / ", "'875 input: '"a, b,c,d, e"'876 output: ['["a","b,c,d","e"]']877 - program: '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'878 input: 'null'879 output: ['{"k": {"a": 0, "b": 2, "c": 3}}']880 - program: '.[] | (1 / .)?'881 input: '[1,0,-1]'882 output: ['1', '-1']883884 - title: "`abs`"885 body: |886887 The builtin function `abs` is defined naively as: `if . < 0 then - . else . end`.888889 For numeric input, this is the absolute value. See the890 section on the identity filter for the implications of this891 definition for numeric input.892893 To compute the absolute value of a number as a floating point number, you may wish use `fabs`.894895 examples:896 - program: 'map(abs)'897 input: '[-10, -1.1, -1e-1]'898 output: ['[10,1.1,1e-1]']899900 - title: "`length`"901 body: |902903 The builtin function `length` gets the length of various904 different types of value:905906 - The length of a **string** is the number of Unicode907 codepoints it contains (which will be the same as its908 JSON-encoded length in bytes if it's pure ASCII).909910 - The length of a **number** is its absolute value.911912 - The length of an **array** is the number of elements.913914 - The length of an **object** is the number of key-value pairs.915916 - The length of **null** is zero.917918 - It is an error to use `length` on a **boolean**.919920 examples:921 - program: '.[] | length'922 input: '[[1,2], "string", {"a":2}, null, -5]'923 output: ['2', '6', '1', '0', '5']924925926 - title: "`utf8bytelength`"927 body: |928929 The builtin function `utf8bytelength` outputs the number of930 bytes used to encode a string in UTF-8.931932 examples:933 - program: 'utf8bytelength'934 input: '"\u03bc"'935 output: ['2']936937 - title: "`keys`, `keys_unsorted`"938 body: |939940 The builtin function `keys`, when given an object, returns941 its keys in an array.942943 The keys are sorted "alphabetically", by unicode codepoint944 order. This is not an order that makes particular sense in945 any particular language, but you can count on it being the946 same for any two objects with the same set of keys,947 regardless of locale settings.948949 When `keys` is given an array, it returns the valid indices950 for that array: the integers from 0 to length-1.951952 The `keys_unsorted` function is just like `keys`, but if953 the input is an object then the keys will not be sorted,954 instead the keys will roughly be in insertion order.955956 examples:957 - program: 'keys'958 input: '{"abc": 1, "abcd": 2, "Foo": 3}'959 output: ['["Foo", "abc", "abcd"]']960 - program: 'keys'961 input: '[42,3,35]'962 output: ['[0,1,2]']963964 - title: "`has(key)`"965 body: |966967 The builtin function `has` returns whether the input object968 has the given key, or the input array has an element at the969 given index.970971 `has($key)` has the same effect as checking whether `$key`972 is a member of the array returned by `keys`, although `has`973 will be faster.974975 examples:976 - program: 'map(has("foo"))'977 input: '[{"foo": 42}, {}]'978 output: ['[true, false]']979 - program: 'map(has(2))'980 input: '[[0,1], ["a","b","c"]]'981 output: ['[false, true]']982983 - title: "`in`"984 body: |985986 The builtin function `in` returns whether or not the input key is in the987 given object, or the input index corresponds to an element988 in the given array. It is, essentially, an inversed version989 of `has`.990991 examples:992 - program: '.[] | in({"foo": 42})'993 input: '["foo", "bar"]'994 output: ['true', 'false']995 - program: 'map(in([0,1]))'996 input: '[2, 0]'997 output: ['[false, true]']998999 - title: "`map(f)`, `map_values(f)`"1000 body: |10011002 For any filter `f`, `map(f)` and `map_values(f)` apply `f`1003 to each of the values in the input array or object, that is,1004 to the values of `.[]`.10051006 In the absence of errors, `map(f)` always outputs an array1007 whereas `map_values(f)` outputs an array if given an array,1008 or an object if given an object.10091010 When the input to `map_values(f)` is an object, the output1011 object has the same keys as the input object except for1012 those keys whose values when piped to `f` produce no values1013 at all.10141015 The key difference between `map(f)` and `map_values(f)` is1016 that the former simply forms an array from all the values of1017 `($x|f)` for each value, $x, in the input array or object,1018 but `map_values(f)` only uses `first($x|f)`.10191020 Specifically, for object inputs, `map_values(f)` constructs1021 the output object by examining in turn the value of1022 `first(.[$k]|f)` for each key, $k, of the input. If this1023 expression produces no values, then the corresponding key1024 will be dropped; otherwise, the output object will have that1025 value at the key, $k.10261027 Here are some examples to clarify the behavior of `map` and1028 `map_values` when applied to arrays. These examples assume the1029 input is `[1]` in all cases:10301031 map(.+1) #=> [2]1032 map(., .) #=> [1,1]1033 map(empty) #=> []10341035 map_values(.+1) #=> [2]1036 map_values(., .) #=> [1]1037 map_values(empty) #=> []10381039 `map(f)` is equivalent to `[.[] | f]` and1040 `map_values(f)` is equivalent to `.[] |= f`.10411042 In fact, these are their implementations.104310441045 examples:1046 - program: 'map(.+1)'1047 input: '[1,2,3]'1048 output: ['[2,3,4]']10491050 - program: 'map_values(.+1)'1051 input: '{"a": 1, "b": 2, "c": 3}'1052 output: ['{"a": 2, "b": 3, "c": 4}']10531054 - program: 'map(., .)'1055 input: '[1,2]'1056 output: ['[1,1,2,2]']10571058 - program: 'map_values(. // empty)'1059 input: '{"a": null, "b": true, "c": false}'1060 output: ['{"b":true}']106110621063 - title: "`pick(pathexps)`"1064 body: |10651066 Emit the projection of the input object or array defined by the1067 specified sequence of path expressions, such that if `p` is any1068 one of these specifications, then `(. | p)` will evaluate to the1069 same value as `(. | pick(pathexps) | p)`. For arrays, negative1070 indices and `.[m:n]` specifications should not be used.10711072 examples:1073 - program: 'pick(.a, .b.c, .x)'1074 input: '{"a": 1, "b": {"c": 2, "d": 3}, "e": 4}'1075 output: ['{"a":1,"b":{"c":2},"x":null}']10761077 - program: 'pick(.[2], .[0], .[0])'1078 input: '[1,2,3,4]'1079 output: ['[1,null,3]']108010811082 - title: "`path(path_expression)`"1083 body: |10841085 Outputs array representations of the given path expression1086 in `.`. The outputs are arrays of strings (object keys)1087 and/or numbers (array indices).10881089 Path expressions are jq expressions like `.a`, but also `.[]`.1090 There are two types of path expressions: ones that can match1091 exactly, and ones that cannot. For example, `.a.b.c` is an1092 exact match path expression, while `.a[].b` is not.10931094 `path(exact_path_expression)` will produce the array1095 representation of the path expression even if it does not1096 exist in `.`, if `.` is `null` or an array or an object.10971098 `path(pattern)` will produce array representations of the1099 paths matching `pattern` if the paths exist in `.`.11001101 Note that the path expressions are not different from normal1102 expressions. The expression1103 `path(..|select(type=="boolean"))` outputs all the paths to1104 boolean values in `.`, and only those paths.11051106 examples:1107 - program: 'path(.a[0].b)'1108 input: 'null'1109 output: ['["a",0,"b"]']1110 - program: '[path(..)]'1111 input: '{"a":[{"b":1}]}'1112 output: ['[[],["a"],["a",0],["a",0,"b"]]']11131114 - title: "`del(path_expression)`"1115 body: |11161117 The builtin function `del` removes a key and its corresponding1118 value from an object.11191120 examples:1121 - program: 'del(.foo)'1122 input: '{"foo": 42, "bar": 9001, "baz": 42}'1123 output: ['{"bar": 9001, "baz": 42}']1124 - program: 'del(.[1, 2])'1125 input: '["foo", "bar", "baz"]'1126 output: ['["foo"]']11271128 - title: "`getpath(PATHS)`"1129 body: |11301131 The builtin function `getpath` outputs the values in `.` found1132 at each path in `PATHS`.11331134 examples:1135 - program: 'getpath(["a","b"])'1136 input: 'null'1137 output: ['null']1138 - program: '[getpath(["a","b"], ["a","c"])]'1139 input: '{"a":{"b":0, "c":1}}'1140 output: ['[0, 1]']11411142 - title: "`setpath(PATHS; VALUE)`"1143 body: |11441145 The builtin function `setpath` sets the `PATHS` in `.` to `VALUE`.11461147 examples:1148 - program: 'setpath(["a","b"]; 1)'1149 input: 'null'1150 output: ['{"a": {"b": 1}}']1151 - program: 'setpath(["a","b"]; 1)'1152 input: '{"a":{"b":0}}'1153 output: ['{"a": {"b": 1}}']1154 - program: 'setpath([0,"a"]; 1)'1155 input: 'null'1156 output: ['[{"a":1}]']11571158 - title: "`delpaths(PATHS)`"1159 body: |11601161 The builtin function `delpaths` deletes the `PATHS` in `.`.1162 `PATHS` must be an array of paths, where each path is an array1163 of strings and numbers.11641165 examples:1166 - program: 'delpaths([["a","b"]])'1167 input: '{"a":{"b":1},"x":{"y":2}}'1168 output: ['{"a":{},"x":{"y":2}}']11691170 - title: "`to_entries`, `from_entries`, `with_entries(f)`"1171 body: |11721173 These functions convert between an object and an array of1174 key-value pairs. If `to_entries` is passed an object, then1175 for each `k: v` entry in the input, the output array1176 includes `{"key": k, "value": v}`.11771178 `from_entries` does the opposite conversion, and `with_entries(f)`1179 is a shorthand for `to_entries | map(f) | from_entries`, useful for1180 doing some operation to all keys and values of an object.1181 `from_entries` accepts `"key"`, `"Key"`, `"name"`, `"Name"`,1182 `"value"`, and `"Value"` as keys.11831184 examples:1185 - program: 'to_entries'1186 input: '{"a": 1, "b": 2}'1187 output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']1188 - program: 'from_entries'1189 input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'1190 output: ['{"a": 1, "b": 2}']1191 - program: 'with_entries(.key |= "KEY_" + .)'1192 input: '{"a": 1, "b": 2}'1193 output: ['{"KEY_a": 1, "KEY_b": 2}']119411951196 - title: "`select(boolean_expression)`"1197 body: |11981199 The function `select(f)` produces its input unchanged if1200 `f` returns true for that input, and produces no output1201 otherwise.12021203 It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`1204 will give you `[2,3]`.12051206 examples:1207 - program: 'map(select(. >= 2))'1208 input: '[1,5,3,0,7]'1209 output: ['[5,3,7]']1210 - program: '.[] | select(.id == "second")'1211 input: '[{"id": "first", "val": 1}, {"id": "second", "val": 2}]'1212 output: ['{"id": "second", "val": 2}']121312141215 - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"1216 body: |12171218 These built-ins select only inputs that are arrays, objects,1219 iterables (arrays or objects), booleans, numbers, normal1220 numbers, finite numbers, strings, null, non-null values, and1221 non-iterables, respectively.12221223 examples:1224 - program: '.[]|numbers'1225 input: '[[],{},1,"foo",null,true,false]'1226 output: ['1']12271228 - title: "`empty`"1229 body: |12301231 `empty` returns no results. None at all. Not even `null`.12321233 It's useful on occasion. You'll know if you need it :)12341235 examples:1236 - program: '1, empty, 2'1237 input: 'null'1238 output: ['1', '2']1239 - program: '[1,2,empty,3]'1240 input: 'null'1241 output: ['[1,2,3]']12421243 - title: "`error`, `error(message)`"1244 body: |12451246 Produces an error with the input value, or with the message1247 given as the argument. Errors can be caught with try/catch;1248 see below.12491250 examples:1251 - program: 'try error catch .'1252 input: '"error message"'1253 output: ['"error message"']12541255 - program: 'try error("invalid value: \(.)") catch .'1256 input: '42'1257 output: ['"invalid value: 42"']12581259 - title: "`halt`"1260 body: |12611262 Stops the jq program with no further outputs. jq will exit1263 with exit status `0`.12641265 - title: "`halt_error`, `halt_error(exit_code)`"1266 body: |12671268 Stops the jq program with no further outputs. The input will1269 be printed on `stderr` as raw output (i.e., strings will not1270 have double quotes) with no decoration, not even a newline.12711272 The given `exit_code` (defaulting to `5`) will be jq's exit1273 status.12741275 For example, `"Error: something went wrong\n"|halt_error(1)`.12761277 - title: "`$__loc__`"1278 body: |12791280 Produces an object with a "file" key and a "line" key, with1281 the filename and line number where `$__loc__` occurs, as1282 values.12831284 examples:1285 - program: 'try error("\($__loc__)") catch .'1286 input: 'null'1287 output: ['"{\"file\":\"<top-level>\",\"line\":1}"']12881289 - title: "`paths`, `paths(node_filter)`"1290 body: |12911292 `paths` outputs the paths to all the elements in its input1293 (except it does not output the empty list, representing .1294 itself).12951296 `paths(f)` outputs the paths to any values for which `f` is `true`.1297 That is, `paths(type == "number")` outputs the paths to all numeric1298 values.12991300 examples:1301 - program: '[paths]'1302 input: '[1,[[],{"a":2}]]'1303 output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']1304 - program: '[paths(type == "number")]'1305 input: '[1,[[],{"a":2}]]'1306 output: ['[[0],[1,1,"a"]]']13071308 - title: "`add`"1309 body: |13101311 The filter `add` takes as input an array, and produces as1312 output the elements of the array added together. This might1313 mean summed, concatenated or merged depending on the types1314 of the elements of the input array - the rules are the same1315 as those for the `+` operator (described above).13161317 If the input is an empty array, `add` returns `null`.13181319 examples:1320 - program: add1321 input: '["a","b","c"]'1322 output: ['"abc"']1323 - program: add1324 input: '[1, 2, 3]'1325 output: ['6']1326 - program: add1327 input: '[]'1328 output: ["null"]13291330 - title: "`any`, `any(condition)`, `any(generator; condition)`"1331 body: |13321333 The filter `any` takes as input an array of boolean values,1334 and produces `true` as output if any of the elements of1335 the array are `true`.13361337 If the input is an empty array, `any` returns `false`.13381339 The `any(condition)` form applies the given condition to the1340 elements of the input array.13411342 The `any(generator; condition)` form applies the given1343 condition to all the outputs of the given generator.13441345 examples:1346 - program: any1347 input: '[true, false]'1348 output: ["true"]1349 - program: any1350 input: '[false, false]'1351 output: ["false"]1352 - program: any1353 input: '[]'1354 output: ["false"]13551356 - title: "`all`, `all(condition)`, `all(generator; condition)`"1357 body: |13581359 The filter `all` takes as input an array of boolean values,1360 and produces `true` as output if all of the elements of1361 the array are `true`.13621363 The `all(condition)` form applies the given condition to the1364 elements of the input array.13651366 The `all(generator; condition)` form applies the given1367 condition to all the outputs of the given generator.13681369 If the input is an empty array, `all` returns `true`.13701371 examples:1372 - program: all1373 input: '[true, false]'1374 output: ["false"]1375 - program: all1376 input: '[true, true]'1377 output: ["true"]1378 - program: all1379 input: '[]'1380 output: ["true"]13811382 - title: "`flatten`, `flatten(depth)`"1383 body: |13841385 The filter `flatten` takes as input an array of nested arrays,1386 and produces a flat array in which all arrays inside the original1387 array have been recursively replaced by their values. You can pass1388 an argument to it to specify how many levels of nesting to flatten.13891390 `flatten(2)` is like `flatten`, but going only up to two1391 levels deep.13921393 examples:1394 - program: flatten1395 input: '[1, [2], [[3]]]'1396 output: ["[1, 2, 3]"]1397 - program: flatten(1)1398 input: '[1, [2], [[3]]]'1399 output: ["[1, 2, [3]]"]1400 - program: flatten1401 input: '[[]]'1402 output: ["[]"]1403 - program: flatten1404 input: '[{"foo": "bar"}, [{"foo": "baz"}]]'1405 output: ['[{"foo": "bar"}, {"foo": "baz"}]']14061407 - title: "`range(upto)`, `range(from; upto)`, `range(from; upto; by)`"1408 body: |14091410 The `range` function produces a range of numbers. `range(4; 10)`1411 produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers1412 are produced as separate outputs. Use `[range(4; 10)]` to get a range as1413 an array.14141415 The one argument form generates numbers from 0 to the given1416 number, with an increment of 1.14171418 The two argument form generates numbers from `from` to `upto`1419 with an increment of 1.14201421 The three argument form generates numbers `from` to `upto`1422 with an increment of `by`.14231424 examples:1425 - program: 'range(2; 4)'1426 input: 'null'1427 output: ['2', '3']1428 - program: '[range(2; 4)]'1429 input: 'null'1430 output: ['[2,3]']1431 - program: '[range(4)]'1432 input: 'null'1433 output: ['[0,1,2,3]']1434 - program: '[range(0; 10; 3)]'1435 input: 'null'1436 output: ['[0,3,6,9]']1437 - program: '[range(0; 10; -1)]'1438 input: 'null'1439 output: ['[]']1440 - program: '[range(0; -5; -1)]'1441 input: 'null'1442 output: ['[0,-1,-2,-3,-4]']14431444 - title: "`floor`"1445 body: |14461447 The `floor` function returns the floor of its numeric input.14481449 examples:1450 - program: 'floor'1451 input: '3.14159'1452 output: ['3']14531454 - title: "`sqrt`"1455 body: |14561457 The `sqrt` function returns the square root of its numeric input.14581459 examples:1460 - program: 'sqrt'1461 input: '9'1462 output: ['3']14631464 - title: "`tonumber`"1465 body: |14661467 The `tonumber` function parses its input as a number. It1468 will convert correctly-formatted strings to their numeric1469 equivalent, leave numbers alone, and give an error on all other input.14701471 examples:1472 - program: '.[] | tonumber'1473 input: '[1, "1"]'1474 output: ['1', '1']14751476 - title: "`tostring`"1477 body: |14781479 The `tostring` function prints its input as a1480 string. Strings are left unchanged, and all other values are1481 JSON-encoded.14821483 examples:1484 - program: '.[] | tostring'1485 input: '[1, "1", [1]]'1486 output: ['"1"', '"1"', '"[1]"']14871488 - title: "`type`"1489 body: |14901491 The `type` function returns the type of its argument as a1492 string, which is one of null, boolean, number, string, array1493 or object.14941495 examples:1496 - program: 'map(type)'1497 input: '[0, false, [], {}, null, "hello"]'1498 output: ['["number", "boolean", "array", "object", "null", "string"]']14991500 - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1501 body: |15021503 Some arithmetic operations can yield infinities and "not a1504 number" (NaN) values. The `isinfinite` builtin returns `true`1505 if its input is infinite. The `isnan` builtin returns `true`1506 if its input is a NaN. The `infinite` builtin returns a1507 positive infinite value. The `nan` builtin returns a NaN.1508 The `isnormal` builtin returns true if its input is a normal1509 number.15101511 Note that division by zero raises an error.15121513 Currently most arithmetic operations operating on infinities,1514 NaNs, and sub-normals do not raise errors.15151516 examples:1517 - program: '.[] | (infinite * .) < 0'1518 input: '[-1, 1]'1519 output: ['true', 'false']1520 - program: 'infinite, nan | type'1521 input: 'null'1522 output: ['"number"', '"number"']15231524 - title: "`sort`, `sort_by(path_expression)`"1525 body: |15261527 The `sort` functions sorts its input, which must be an1528 array. Values are sorted in the following order:15291530 * `null`1531 * `false`1532 * `true`1533 * numbers1534 * strings, in alphabetical order (by unicode codepoint value)1535 * arrays, in lexical order1536 * objects15371538 The ordering for objects is a little complex: first they're1539 compared by comparing their sets of keys (as arrays in1540 sorted order), and if their keys are equal then the values1541 are compared key by key.15421543 `sort_by` may be used to sort by a particular field of an1544 object, or by applying any jq filter. `sort_by(f)` compares1545 two elements by comparing the result of `f` on each element.1546 When `f` produces multiple values, it firstly compares the1547 first values, and the second values if the first values are1548 equal, and so on.15491550 examples:1551 - program: 'sort'1552 input: '[8,3,null,6]'1553 output: ['[null,3,6,8]']15541555 - program: 'sort_by(.foo)'1556 input: '[{"foo":4, "bar":10}, {"foo":3, "bar":10}, {"foo":2, "bar":1}]'1557 output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":10}, {"foo":4, "bar":10}]']15581559 - program: 'sort_by(.foo, .bar)'1560 input: '[{"foo":4, "bar":10}, {"foo":3, "bar":20}, {"foo":2, "bar":1}, {"foo":3, "bar":10}]'1561 output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":10}, {"foo":3, "bar":20}, {"foo":4, "bar":10}]']15621563 - title: "`group_by(path_expression)`"1564 body: |15651566 `group_by(.foo)` takes as input an array, groups the1567 elements having the same `.foo` field into separate arrays,1568 and produces all of these arrays as elements of a larger1569 array, sorted by the value of the `.foo` field.15701571 Any jq expression, not just a field access, may be used in1572 place of `.foo`. The sorting order is the same as described1573 in the `sort` function above.15741575 examples:1576 - program: 'group_by(.foo)'1577 input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'1578 output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']15791580 - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1581 body: |15821583 Find the minimum or maximum element of the input array.15841585 The `min_by(path_exp)` and `max_by(path_exp)` functions allow1586 you to specify a particular field or property to examine, e.g.1587 `min_by(.foo)` finds the object with the smallest `foo` field.15881589 examples:1590 - program: 'min'1591 input: '[5,4,2,7]'1592 output: ['2']1593 - program: 'max_by(.foo)'1594 input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'1595 output: ['{"foo":2, "bar":3}']15961597 - title: "`unique`, `unique_by(path_exp)`"1598 body: |15991600 The `unique` function takes as input an array and produces1601 an array of the same elements, in sorted order, with1602 duplicates removed.16031604 The `unique_by(path_exp)` function will keep only one element1605 for each value obtained by applying the argument. Think of it1606 as making an array by taking one element out of every group1607 produced by `group`.16081609 examples:1610 - program: 'unique'1611 input: '[1,2,5,3,5,3,1,3]'1612 output: ['[1,2,3,5]']1613 - program: 'unique_by(.foo)'1614 input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'1615 output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']1616 - program: 'unique_by(length)'1617 input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'1618 output: ['["bacon", "chunky", "asparagus"]']16191620 - title: "`reverse`"1621 body: |16221623 This function reverses an array.16241625 examples:1626 - program: 'reverse'1627 input: '[1,2,3,4]'1628 output: ['[4,3,2,1]']16291630 - title: "`contains(element)`"1631 body: |16321633 The filter `contains(b)` will produce true if b is1634 completely contained within the input. A string B is1635 contained in a string A if B is a substring of A. An array B1636 is contained in an array A if all elements in B are1637 contained in any element in A. An object B is contained in1638 object A if all of the values in B are contained in the1639 value in A with the same key. All other types are assumed to1640 be contained in each other if they are equal.16411642 examples:1643 - program: 'contains("bar")'1644 input: '"foobar"'1645 output: ['true']1646 - program: 'contains(["baz", "bar"])'1647 input: '["foobar", "foobaz", "blarp"]'1648 output: ['true']1649 - program: 'contains(["bazzzzz", "bar"])'1650 input: '["foobar", "foobaz", "blarp"]'1651 output: ['false']1652 - program: 'contains({foo: 12, bar: [{barp: 12}]})'1653 input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1654 output: ['true']1655 - program: 'contains({foo: 12, bar: [{barp: 15}]})'1656 input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1657 output: ['false']16581659 - title: "`indices(s)`"1660 body: |16611662 Outputs an array containing the indices in `.` where `s`1663 occurs. The input may be an array, in which case if `s` is an1664 array then the indices output will be those where all elements1665 in `.` match those of `s`.16661667 examples:1668 - program: 'indices(", ")'1669 input: '"a,b, cd, efg, hijk"'1670 output: ['[3,7,12]']1671 - program: 'indices(1)'1672 input: '[0,1,2,1,3,1,4]'1673 output: ['[1,3,5]']1674 - program: 'indices([1,2])'1675 input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1676 output: ['[1,8]']16771678 - title: "`index(s)`, `rindex(s)`"1679 body: |16801681 Outputs the index of the first (`index`) or last (`rindex`)1682 occurrence of `s` in the input.16831684 examples:1685 - program: 'index(", ")'1686 input: '"a,b, cd, efg, hijk"'1687 output: ['3']1688 - program: 'index(1)'1689 input: '[0,1,2,1,3,1,4]'1690 output: ['1']1691 - program: 'index([1,2])'1692 input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1693 output: ['1']1694 - program: 'rindex(", ")'1695 input: '"a,b, cd, efg, hijk"'1696 output: ['12']1697 - program: 'rindex(1)'1698 input: '[0,1,2,1,3,1,4]'1699 output: ['5']1700 - program: 'rindex([1,2])'1701 input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1702 output: ['8']17031704 - title: "`inside`"1705 body: |17061707 The filter `inside(b)` will produce true if the input is1708 completely contained within b. It is, essentially, an1709 inversed version of `contains`.17101711 examples:1712 - program: 'inside("foobar")'1713 input: '"bar"'1714 output: ['true']1715 - program: 'inside(["foobar", "foobaz", "blarp"])'1716 input: '["baz", "bar"]'1717 output: ['true']1718 - program: 'inside(["foobar", "foobaz", "blarp"])'1719 input: '["bazzzzz", "bar"]'1720 output: ['false']1721 - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1722 input: '{"foo": 12, "bar": [{"barp": 12}]}'1723 output: ['true']1724 - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1725 input: '{"foo": 12, "bar": [{"barp": 15}]}'1726 output: ['false']17271728 - title: "`startswith(str)`"1729 body: |17301731 Outputs `true` if . starts with the given string argument.17321733 examples:1734 - program: '[.[]|startswith("foo")]'1735 input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1736 output: ['[false, true, false, true, false]']17371738 - title: "`endswith(str)`"1739 body: |17401741 Outputs `true` if . ends with the given string argument.17421743 examples:1744 - program: '[.[]|endswith("foo")]'1745 input: '["foobar", "barfoo"]'1746 output: ['[false, true]']17471748 - title: "`combinations`, `combinations(n)`"1749 body: |17501751 Outputs all combinations of the elements of the arrays in the1752 input array. If given an argument `n`, it outputs all combinations1753 of `n` repetitions of the input array.17541755 examples:1756 - program: 'combinations'1757 input: '[[1,2], [3, 4]]'1758 output: ['[1, 3]', '[1, 4]', '[2, 3]', '[2, 4]']1759 - program: 'combinations(2)'1760 input: '[0, 1]'1761 output: ['[0, 0]', '[0, 1]', '[1, 0]', '[1, 1]']17621763 - title: "`ltrimstr(str)`"1764 body: |17651766 Outputs its input with the given prefix string removed, if it1767 starts with it.17681769 examples:1770 - program: '[.[]|ltrimstr("foo")]'1771 input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1772 output: ['["fo","","barfoo","bar","afoo"]']17731774 - title: "`rtrimstr(str)`"1775 body: |17761777 Outputs its input with the given suffix string removed, if it1778 ends with it.17791780 examples:1781 - program: '[.[]|rtrimstr("foo")]'1782 input: '["fo", "foo", "barfoo", "foobar", "foob"]'1783 output: ['["fo","","bar","foobar","foob"]']17841785 - title: "`trim`, `ltrim`, `rtrim`"1786 body: |17871788 `trim` trims both leading and trailing whitespace.17891790 `ltrim` trims only leading (left side) whitespace.17911792 `rtrim` trims only trailing (right side) whitespace.17931794 Whitespace characters are the usual `" "`, `"\n"` `"\t"`, `"\r"`1795 and also all characters in the Unicode character database with the1796 whitespace property. Note that what considers whitespace might1797 change in the future.17981799 examples:1800 - program: 'trim, ltrim, rtrim'1801 input: '" abc "'1802 output: ['"abc"', '"abc "', '" abc"']18031804 - title: "`explode`"1805 body: |18061807 Converts an input string into an array of the string's1808 codepoint numbers.18091810 examples:1811 - program: 'explode'1812 input: '"foobar"'1813 output: ['[102,111,111,98,97,114]']18141815 - title: "`implode`"1816 body: |18171818 The inverse of explode.18191820 examples:1821 - program: 'implode'1822 input: '[65, 66, 67]'1823 output: ['"ABC"']18241825 - title: "`split(str)`"1826 body: |18271828 Splits an input string on the separator argument.18291830 `split` can also split on regex matches when called with1831 two arguments (see the regular expressions section below).18321833 examples:1834 - program: 'split(", ")'1835 input: '"a, b,c,d, e, "'1836 output: ['["a","b,c,d","e",""]']18371838 - title: "`join(str)`"1839 body: |18401841 Joins the array of elements given as input, using the1842 argument as separator. It is the inverse of `split`: that is,1843 running `split("foo") | join("foo")` over any input string1844 returns said input string.18451846 Numbers and booleans in the input are converted to strings.1847 Null values are treated as empty strings. Arrays and objects1848 in the input are not supported.18491850 examples:1851 - program: 'join(", ")'1852 input: '["a","b,c,d","e"]'1853 output: ['"a, b,c,d, e"']1854 - program: 'join(" ")'1855 input: '["a",1,2.3,true,null,false]'1856 output: ['"a 1 2.3 true false"']18571858 - title: "`ascii_downcase`, `ascii_upcase`"1859 body: |18601861 Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1862 converted to the specified case.18631864 examples:1865 - program: 'ascii_upcase'1866 input: '"useful but not for é"'1867 output: ['"USEFUL BUT NOT FOR é"']18681869 - title: "`while(cond; update)`"1870 body: |18711872 The `while(cond; update)` function allows you to repeatedly1873 apply an update to `.` until `cond` is false.18741875 Note that `while(cond; update)` is internally defined as a1876 recursive jq function. Recursive calls within `while` will1877 not consume additional memory if `update` produces at most one1878 output for each input. See advanced topics below.18791880 examples:1881 - program: '[while(.<100; .*2)]'1882 input: '1'1883 output: ['[1,2,4,8,16,32,64]']18841885 - title: "`repeat(exp)`"1886 body: |18871888 The `repeat(exp)` function allows you to repeatedly1889 apply expression `exp` to `.` until an error is raised.18901891 Note that `repeat(exp)` is internally defined as a1892 recursive jq function. Recursive calls within `repeat` will1893 not consume additional memory if `exp` produces at most one1894 output for each input. See advanced topics below.18951896 examples:1897 - program: '[repeat(.*2, error)?]'1898 input: '1'1899 output: ['[2]']19001901 - title: "`until(cond; next)`"1902 body: |19031904 The `until(cond; next)` function allows you to repeatedly1905 apply the expression `next`, initially to `.` then to its own1906 output, until `cond` is true. For example, this can be used1907 to implement a factorial function (see below).19081909 Note that `until(cond; next)` is internally defined as a1910 recursive jq function. Recursive calls within `until()` will1911 not consume additional memory if `next` produces at most one1912 output for each input. See advanced topics below.19131914 examples:1915 - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1916 input: '4'1917 output: ['24']191819191920 - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`"1921 body: |19221923 The `recurse(f)` function allows you to search through a1924 recursive structure, and extract interesting data from all1925 levels. Suppose your input represents a filesystem:19261927 {"name": "/", "children": [1928 {"name": "/bin", "children": [1929 {"name": "/bin/ls", "children": []},1930 {"name": "/bin/sh", "children": []}]},1931 {"name": "/home", "children": [1932 {"name": "/home/stephen", "children": [1933 {"name": "/home/stephen/jq", "children": []}]}]}]}19341935 Now suppose you want to extract all of the filenames1936 present. You need to retrieve `.name`, `.children[].name`,1937 `.children[].children[].name`, and so on. You can do this1938 with:19391940 recurse(.children[]) | .name19411942 When called without an argument, `recurse` is equivalent to1943 `recurse(.[]?)`.19441945 `recurse(f)` is identical to `recurse(f; true)` and can be1946 used without concerns about recursion depth.19471948 `recurse(f; condition)` is a generator which begins by1949 emitting . and then emits in turn .|f, .|f|f, .|f|f|f, ... so long1950 as the computed value satisfies the condition. For example,1951 to generate all the integers, at least in principle, one1952 could write `recurse(.+1; true)`.19531954 The recursive calls in `recurse` will not consume additional1955 memory whenever `f` produces at most a single output for each1956 input.19571958 examples:1959 - program: 'recurse(.foo[])'1960 input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'1961 output:1962 - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'1963 - '{"foo":[]}'1964 - '{"foo":[{"foo":[]}]}'1965 - '{"foo":[]}'19661967 - program: 'recurse'1968 input: '{"a":0,"b":[1]}'1969 output:1970 - '{"a":0,"b":[1]}'1971 - '0'1972 - '[1]'1973 - '1'19741975 - program: 'recurse(. * .; . < 20)'1976 input: '2'1977 output: ['2', '4', '16']19781979 - title: "`walk(f)`"1980 body: |19811982 The `walk(f)` function applies f recursively to every1983 component of the input entity. When an array is1984 encountered, f is first applied to its elements and then to1985 the array itself; when an object is encountered, f is first1986 applied to all the values and then to the object. In1987 practice, f will usually test the type of its input, as1988 illustrated in the following examples. The first example1989 highlights the usefulness of processing the elements of an1990 array of arrays before processing the array itself. The second1991 example shows how all the keys of all the objects within the1992 input can be considered for alteration.19931994 examples:1995 - program: 'walk(if type == "array" then sort else . end)'1996 input: '[[4, 1, 7], [8, 5, 2], [3, 6, 9]]'1997 output:1998 - '[[1,4,7],[2,5,8],[3,6,9]]'19992000 - program: 'walk( if type == "object" then with_entries( .key |= sub( "^_+"; "") ) else . end )'2001 input: '[ { "_a": { "__b": 2 } } ]'2002 output:2003 - '[{"a":{"b":2}}]'20042005 - title: "`have_literal_numbers`"2006 body: |20072008 This builtin returns true if jq's build configuration2009 includes support for preservation of input number literals.20102011 - title: "`have_decnum`"2012 body: |20132014 This builtin returns true if jq was built with "decnum",2015 which is the current literal number preserving numeric2016 backend implementation for jq.20172018 - title: "`$JQ_BUILD_CONFIGURATION`"2019 body: |20202021 This builtin binding shows the jq executable's build2022 configuration. Its value has no particular format, but2023 it can be expected to be at least the `./configure`2024 command-line arguments, and may be enriched in the2025 future to include the version strings for the build2026 tooling used.20272028 Note that this can be overriden in the command-line2029 with `--arg` and related options.20302031 - title: "`$ENV`, `env`"2032 body: |20332034 `$ENV` is an object representing the environment variables as2035 set when the jq program started.20362037 `env` outputs an object representing jq's current environment.20382039 At the moment there is no builtin for setting environment2040 variables.20412042 examples:2043 - program: '$ENV.PAGER'2044 input: 'null'2045 output: ['"less"']20462047 - program: 'env.PAGER'2048 input: 'null'2049 output: ['"less"']20502051 - title: "`transpose`"2052 body: |20532054 Transpose a possibly jagged matrix (an array of arrays).2055 Rows are padded with nulls so the result is always rectangular.20562057 examples:2058 - program: 'transpose'2059 input: '[[1], [2,3]]'2060 output: ['[[1,2],[null,3]]']20612062 - title: "`bsearch(x)`"2063 body: |20642065 `bsearch(x)` conducts a binary search for x in the input2066 array. If the input is sorted and contains x, then2067 `bsearch(x)` will return its index in the array; otherwise, if2068 the array is sorted, it will return (-1 - ix) where ix is an2069 insertion point such that the array would still be sorted2070 after the insertion of x at ix. If the array is not sorted,2071 `bsearch(x)` will return an integer that is probably of no2072 interest.20732074 examples:2075 - program: 'bsearch(0)'2076 input: '[0,1]'2077 output: ['0']2078 - program: 'bsearch(0)'2079 input: '[1,2,3]'2080 output: ['-1']2081 - program: 'bsearch(4) as $ix | if $ix < 0 then .[-(1+$ix)] = 4 else . end'2082 input: '[1,2,3]'2083 output: ['[1,2,3,4]']20842085 - title: "String interpolation: `\\(exp)`"2086 body: |20872088 Inside a string, you can put an expression inside parens2089 after a backslash. Whatever the expression returns will be2090 interpolated into the string.20912092 examples:2093 - program: '"The input was \(.), which is one less than \(.+1)"'2094 input: '42'2095 output: ['"The input was 42, which is one less than 43"']20962097 - title: "Convert to/from JSON"2098 body: |20992100 The `tojson` and `fromjson` builtins dump values as JSON texts2101 or parse JSON texts into values, respectively. The `tojson`2102 builtin differs from `tostring` in that `tostring` returns strings2103 unmodified, while `tojson` encodes strings as JSON strings.21042105 examples:2106 - program: '[.[]|tostring]'2107 input: '[1, "foo", ["foo"]]'2108 output: ['["1","foo","[\"foo\"]"]']2109 - program: '[.[]|tojson]'2110 input: '[1, "foo", ["foo"]]'2111 output: ['["1","\"foo\"","[\"foo\"]"]']2112 - program: '[.[]|tojson|fromjson]'2113 input: '[1, "foo", ["foo"]]'2114 output: ['[1,"foo",["foo"]]']21152116 - title: "Format strings and escaping"2117 body: |21182119 The `@foo` syntax is used to format and escape strings,2120 which is useful for building URLs, documents in a language2121 like HTML or XML, and so forth. `@foo` can be used as a2122 filter on its own, the possible escapings are:21232124 * `@text`:21252126 Calls `tostring`, see that function for details.21272128 * `@json`:21292130 Serializes the input as JSON.21312132 * `@html`:21332134 Applies HTML/XML escaping, by mapping the characters2135 `<>&'"` to their entity equivalents `&lt;`, `&gt;`,2136 `&amp;`, `&apos;`, `&quot;`.21372138 * `@uri`:21392140 Applies percent-encoding, by mapping all reserved URI2141 characters to a `%XX` sequence.21422143 * `@csv`:21442145 The input must be an array, and it is rendered as CSV2146 with double quotes for strings, and quotes escaped by2147 repetition.21482149 * `@tsv`:21502151 The input must be an array, and it is rendered as TSV2152 (tab-separated values). Each input array will be printed as2153 a single line. Fields are separated by a single2154 tab (ascii `0x09`). Input characters line-feed (ascii `0x0a`),2155 carriage-return (ascii `0x0d`), tab (ascii `0x09`) and2156 backslash (ascii `0x5c`) will be output as escape sequences2157 `\n`, `\r`, `\t`, `\\` respectively.21582159 * `@sh`:21602161 The input is escaped suitable for use in a command-line2162 for a POSIX shell. If the input is an array, the output2163 will be a series of space-separated strings.21642165 * `@base64`:21662167 The input is converted to base64 as specified by RFC 4648.21682169 * `@base64d`:21702171 The inverse of `@base64`, input is decoded as specified by RFC 4648.2172 Note\: If the decoded string is not UTF-8, the results are undefined.21732174 This syntax can be combined with string interpolation in a2175 useful way. You can follow a `@foo` token with a string2176 literal. The contents of the string literal will *not* be2177 escaped. However, all interpolations made inside that string2178 literal will be escaped. For instance,21792180 @uri "https://www.google.com/search?q=\(.search)"21812182 will produce the following output for the input2183 `{"search":"what is jq?"}`:21842185 "https://www.google.com/search?q=what%20is%20jq%3F"21862187 Note that the slashes, question mark, etc. in the URL are2188 not escaped, as they were part of the string literal.21892190 examples:2191 - program: '@html'2192 input: '"This works if x < y"'2193 output: ['"This works if x &lt; y"']21942195 - program: '@sh "echo \(.)"'2196 input: "\"O'Hara's Ale\""2197 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]21982199 - program: '@base64'2200 input: '"This is a message"'2201 output: ['"VGhpcyBpcyBhIG1lc3NhZ2U="']22022203 - program: '@base64d'2204 input: '"VGhpcyBpcyBhIG1lc3NhZ2U="'2205 output: ['"This is a message"']22062207 - title: "Dates"2208 body: |22092210 jq provides some basic date handling functionality, with some2211 high-level and low-level builtins. In all cases these2212 builtins deal exclusively with time in UTC.22132214 The `fromdateiso8601` builtin parses datetimes in the ISO 86012215 format to a number of seconds since the Unix epoch2216 (1970-01-01T00:00:00Z). The `todateiso8601` builtin does the2217 inverse.22182219 The `fromdate` builtin parses datetime strings. Currently2220 `fromdate` only supports ISO 8601 datetime strings, but in the2221 future it will attempt to parse datetime strings in more2222 formats.22232224 The `todate` builtin is an alias for `todateiso8601`.22252226 The `now` builtin outputs the current time, in seconds since2227 the Unix epoch.22282229 Low-level jq interfaces to the C-library time functions are2230 also provided: `strptime`, `strftime`, `strflocaltime`,2231 `mktime`, `gmtime`, and `localtime`. Refer to your host2232 operating system's documentation for the format strings used2233 by `strptime` and `strftime`. Note: these are not necessarily2234 stable interfaces in jq, particularly as to their localization2235 functionality.22362237 The `gmtime` builtin consumes a number of seconds since the2238 Unix epoch and outputs a "broken down time" representation of2239 Greenwich Mean Time as an array of numbers representing2240 (in this order): the year, the month (zero-based), the day of2241 the month (one-based), the hour of the day, the minute of the2242 hour, the second of the minute, the day of the week, and the2243 day of the year -- all one-based unless otherwise stated. The2244 day of the week number may be wrong on some systems for dates2245 before March 1st 1900, or after December 31 2099.22462247 The `localtime` builtin works like the `gmtime` builtin, but2248 using the local timezone setting.22492250 The `mktime` builtin consumes "broken down time"2251 representations of time output by `gmtime` and `strptime`.22522253 The `strptime(fmt)` builtin parses input strings matching the2254 `fmt` argument. The output is in the "broken down time"2255 representation consumed by `gmtime` and output by `mktime`.22562257 The `strftime(fmt)` builtin formats a time (GMT) with the2258 given format. The `strflocaltime` does the same, but using2259 the local timezone setting.22602261 The format strings for `strptime` and `strftime` are described2262 in typical C library documentation. The format string for ISO2263 8601 datetime is `"%Y-%m-%dT%H:%M:%SZ"`.22642265 jq may not support some or all of this date functionality on2266 some systems. In particular, the `%u` and `%j` specifiers for2267 `strptime(fmt)` are not supported on macOS.22682269 examples:2270 - program: 'fromdate'2271 input: '"2015-03-05T23:51:47Z"'2272 output: ['1425599507']22732274 - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")'2275 input: '"2015-03-05T23:51:47Z"'2276 output: ['[2015,2,5,23,51,47,4,63]']22772278 - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'2279 input: '"2015-03-05T23:51:47Z"'2280 output: ['1425599507']22812282 - title: "SQL-Style Operators"2283 body: |22842285 jq provides a few SQL-style operators.22862287 * INDEX(stream; index_expression):22882289 This builtin produces an object whose keys are computed by2290 the given index expression applied to each value from the2291 given stream.22922293 * JOIN($idx; stream; idx_expr; join_expr):22942295 This builtin joins the values from the given stream to the2296 given index. The index's keys are computed by applying the2297 given index expression to each value from the given stream.2298 An array of the value in the stream and the corresponding2299 value from the index is fed to the given join expression to2300 produce each result.23012302 * JOIN($idx; stream; idx_expr):23032304 Same as `JOIN($idx; stream; idx_expr; .)`.23052306 * JOIN($idx; idx_expr):23072308 This builtin joins the input `.` to the given index, applying2309 the given index expression to `.` to compute the index key.2310 The join operation is as described above.23112312 * IN(s):23132314 This builtin outputs `true` if `.` appears in the given2315 stream, otherwise it outputs `false`.23162317 * IN(source; s):23182319 This builtin outputs `true` if any value in the source stream2320 appears in the second stream, otherwise it outputs `false`.23212322 - title: "`builtins`"2323 body: |23242325 Returns a list of all builtin functions in the format `name/arity`.2326 Since functions with the same name but different arities are considered2327 separate functions, `all/0`, `all/1`, and `all/2` would all be present2328 in the list.23292330 - title: Conditionals and Comparisons2331 entries:2332 - title: "`==`, `!=`"2333 body: |23342335 The expression 'a == b' will produce 'true' if the results of evaluating2336 a and b are equal (that is, if they represent equivalent JSON values) and2337 'false' otherwise. In particular, strings are never considered equal2338 to numbers. In checking for the equality of JSON objects, the ordering of keys2339 is irrelevant. If you're coming from JavaScript, please note that jq's `==` is like2340 JavaScript's `===`, the "strict equality" operator.23412342 != is "not equal", and 'a != b' returns the opposite value of 'a == b'23432344 examples:2345 - program: '. == false'2346 input: 'null'2347 output: ['false']23482349 - program: '. == {"b": {"d": (4 + 1e-20), "c": 3}, "a":1}'2350 input: '{"a":1, "b": {"c": 3, "d": 4}}'2351 output: ['true']23522353 - program: '.[] == 1'2354 input: '[1, 1.0, "1", "banana"]'2355 output: ['true', 'true', 'false', 'false']23562357 - title: if-then-else-end2358 body: |23592360 `if A then B else C end` will act the same as `B` if `A`2361 produces a value other than false or null, but act the same2362 as `C` otherwise.23632364 `if A then B end` is the same as `if A then B else . end`.2365 That is, the `else` branch is optional, and if absent is the2366 same as `.`. This also applies to `elif` with absent ending `else` branch.23672368 Checking for false or null is a simpler notion of2369 "truthiness" than is found in JavaScript or Python, but it2370 means that you'll sometimes have to be more explicit about2371 the condition you want. You can't test whether, e.g. a2372 string is empty using `if .name then A else B end`; you'll2373 need something like `if .name == "" then A else B end` instead.23742375 If the condition `A` produces multiple results, then `B` is evaluated2376 once for each result that is not false or null, and `C` is evaluated2377 once for each false or null.23782379 More cases can be added to an if using `elif A then B` syntax.23802381 examples:2382 - program: |-2383 if . == 0 then2384 "zero"2385 elif . == 1 then2386 "one"2387 else2388 "many"2389 end2390 input: '2'2391 output: ['"many"']23922393 - title: "`>`, `>=`, `<=`, `<`"2394 body: |23952396 The comparison operators `>`, `>=`, `<=`, `<` return whether2397 their left argument is greater than, greater than or equal2398 to, less than or equal to or less than their right argument2399 (respectively).24002401 The ordering is the same as that described for `sort`, above.24022403 examples:2404 - program: '. < 5'2405 input: '2'2406 output: ['true']24072408 - title: "`and`, `or`, `not`"2409 body: |24102411 jq supports the normal Boolean operators `and`, `or`, `not`.2412 They have the same standard of truth as if expressions -2413 `false` and `null` are considered "false values", and2414 anything else is a "true value".24152416 If an operand of one of these operators produces multiple2417 results, the operator itself will produce a result for each input.24182419 `not` is in fact a builtin function rather than an operator,2420 so it is called as a filter to which things can be piped2421 rather than with special syntax, as in `.foo and .bar |2422 not`.24232424 These three only produce the values `true` and `false`, and2425 so are only useful for genuine Boolean operations, rather2426 than the common Perl/Python/Ruby idiom of2427 "value_that_may_be_null or default". If you want to use this2428 form of "or", picking between two values rather than2429 evaluating a condition, see the `//` operator below.24302431 examples:2432 - program: '42 and "a string"'2433 input: 'null'2434 output: ['true']2435 - program: '(true, false) or false'2436 input: 'null'2437 output: ['true', 'false']2438 - program: '(true, true) and (true, false)'2439 input: 'null'2440 output: ['true', 'false', 'true', 'false']2441 - program: '[true, false | not]'2442 input: 'null'2443 output: ['[false, true]']24442445 - title: "Alternative operator: `//`"2446 body: |24472448 The `//` operator produces all the values of its left-hand2449 side that are neither `false` nor `null`. If the2450 left-hand side produces no values other than `false` or2451 `null`, then `//` produces all the values of its right-hand2452 side.24532454 A filter of the form `a // b` produces all the results of2455 `a` that are not `false` or `null`. If `a` produces no2456 results, or no results other than `false` or `null`, then `a2457 // b` produces the results of `b`.24582459 This is useful for providing defaults: `.foo // 1` will2460 evaluate to `1` if there's no `.foo` element in the2461 input. It's similar to how `or` is sometimes used in Python2462 (jq's `or` operator is reserved for strictly Boolean2463 operations).24642465 Note: `some_generator // defaults_here` is not the same2466 as `some_generator | . // defaults_here`. The latter will2467 produce default values for all non-`false`, non-`null`2468 values of the left-hand side, while the former will not.2469 Precedence rules can make this confusing. For example, in2470 `false, 1 // 2` the left-hand side of `//` is `1`, not2471 `false, 1` -- `false, 1 // 2` parses the same way as `false,2472 (1 // 2)`. In `(false, null, 1) | . // 42` the left-hand2473 side of `//` is `.`, which always produces just one value,2474 while in `(false, null, 1) // 42` the left-hand side is a2475 generator of three values, and since it produces a2476 value other `false` and `null`, the default `42` is not2477 produced.24782479 examples:2480 - program: 'empty // 42'2481 input: 'null'2482 output: ['42']2483 - program: '.foo // 42'2484 input: '{"foo": 19}'2485 output: ['19']2486 - program: '.foo // 42'2487 input: '{}'2488 output: ['42']2489 - program: '(false, null, 1) // 42'2490 input: 'null'2491 output: ['1']2492 - program: '(false, null, 1) | . // 42'2493 input: 'null'2494 output: ['42', '42', '1']24952496 - title: try-catch2497 body: |24982499 Errors can be caught by using `try EXP catch EXP`. The first2500 expression is executed, and if it fails then the second is2501 executed with the error message. The output of the handler,2502 if any, is output as if it had been the output of the2503 expression to try.25042505 The `try EXP` form uses `empty` as the exception handler.25062507 examples:2508 - program: 'try .a catch ". is not an object"'2509 input: 'true'2510 output: ['". is not an object"']2511 - program: '[.[]|try .a]'2512 input: '[{}, true, {"a":1}]'2513 output: ['[null, 1]']2514 - program: 'try error("some exception") catch .'2515 input: 'true'2516 output: ['"some exception"']25172518 - title: Breaking out of control structures2519 body: |25202521 A convenient use of try/catch is to break out of control2522 structures like `reduce`, `foreach`, `while`, and so on.25232524 For example:25252526 # Repeat an expression until it raises "break" as an2527 # error, then stop repeating without re-raising the error.2528 # But if the error caught is not "break" then re-raise it.2529 try repeat(exp) catch if .=="break" then empty else error25302531 jq has a syntax for named lexical labels to "break" or "go (back) to":25322533 label $out | ... break $out ...25342535 The `break $label_name` expression will cause the program to2536 act as though the nearest (to the left) `label $label_name`2537 produced `empty`.25382539 The relationship between the `break` and corresponding `label`2540 is lexical: the label has to be "visible" from the break.25412542 To break out of a `reduce`, for example:25432544 label $out | reduce .[] as $item (null; if .==false then break $out else ... end)25452546 The following jq program produces a syntax error:25472548 break $out25492550 because no label `$out` is visible.25512552 - title: "Error Suppression / Optional Operator: `?`"2553 body: |25542555 The `?` operator, used as `EXP?`, is shorthand for `try EXP`.25562557 examples:2558 - program: '[.[] | .a?]'2559 input: '[{}, true, {"a":1}]'2560 output: ['[null, 1]']2561 - program: '[.[] | tonumber?]'2562 input: '["1", "invalid", "3", 4]'2563 output: ['[1, 3, 4]']25642565 - title: Regular expressions2566 body: |25672568 jq uses the2569 [Oniguruma regular expression library](https://github.com/kkos/oniguruma/blob/master/doc/RE),2570 as do PHP, TextMate, Sublime Text, etc, so the2571 description here will focus on jq specifics.25722573 Oniguruma supports several flavors of regular expression, so it is important to know2574 that jq uses the ["Perl NG" (Perl with named groups)](https://github.com/kkos/oniguruma/blob/master/doc/SYNTAX.md) flavor.25752576 The jq regex filters are defined so that they can be used using2577 one of these patterns:25782579 STRING | FILTER(REGEX)2580 STRING | FILTER(REGEX; FLAGS)2581 STRING | FILTER([REGEX])2582 STRING | FILTER([REGEX, FLAGS])25832584 where:25852586 * STRING, REGEX, and FLAGS are jq strings and subject to jq string interpolation;2587 * REGEX, after string interpolation, should be a valid regular expression;2588 * FILTER is one of `test`, `match`, or `capture`, as described below.25892590 Since REGEX must evaluate to a JSON string, some characters that are needed2591 to form a regular expression must be escaped. For example, the regular expression2592 `\s` signifying a whitespace character would be written as `"\\s"`.25932594 FLAGS is a string consisting of one of more of the supported flags:25952596 * `g` - Global search (find all matches, not just the first)2597 * `i` - Case insensitive search2598 * `m` - Multi line mode (`.` will match newlines)2599 * `n` - Ignore empty matches2600 * `p` - Both s and m modes are enabled2601 * `s` - Single line mode (`^` -> `\A`, `$` -> `\Z`)2602 * `l` - Find longest possible matches2603 * `x` - Extended regex format (ignore whitespace and comments)26042605 To match a whitespace with the `x` flag, use `\s`, e.g.26062607 jq -n '"a b" | test("a\\sb"; "x")'26082609 Note that certain flags may also be specified within REGEX, e.g.26102611 jq -n '("test", "TEst", "teST", "TEST") | test("(?i)te(?-i)st")'26122613 evaluates to: `true`, `true`, `false`, `false`.26142615 entries:2616 - title: "`test(val)`, `test(regex; flags)`"2617 body: |26182619 Like `match`, but does not return match objects, only `true` or `false`2620 for whether or not the regex matches the input.26212622 examples:2623 - program: 'test("foo")'2624 input: '"foo"'2625 output: ['true']2626 - program: '.[] | test("a b c # spaces are ignored"; "ix")'2627 input: '["xabcd", "ABC"]'2628 output: ['true', 'true']26292630 - title: "`match(val)`, `match(regex; flags)`"2631 body: |26322633 **match** outputs an object for each match it finds. Matches have2634 the following fields:26352636 * `offset` - offset in UTF-8 codepoints from the beginning of the input2637 * `length` - length in UTF-8 codepoints of the match2638 * `string` - the string that it matched2639 * `captures` - an array of objects representing capturing groups.26402641 Capturing group objects have the following fields:26422643 * `offset` - offset in UTF-8 codepoints from the beginning of the input2644 * `length` - length in UTF-8 codepoints of this capturing group2645 * `string` - the string that was captured2646 * `name` - the name of the capturing group (or `null` if it was unnamed)26472648 Capturing groups that did not match anything return an offset of -126492650 examples:2651 - program: 'match("(abc)+"; "g")'2652 input: '"abc abc"'2653 output:2654 - '{"offset": 0, "length": 3, "string": "abc", "captures": [{"offset": 0, "length": 3, "string": "abc", "name": null}]}'2655 - '{"offset": 4, "length": 3, "string": "abc", "captures": [{"offset": 4, "length": 3, "string": "abc", "name": null}]}'2656 - program: 'match("foo")'2657 input: '"foo bar foo"'2658 output: ['{"offset": 0, "length": 3, "string": "foo", "captures": []}']2659 - program: 'match(["foo", "ig"])'2660 input: '"foo bar FOO"'2661 output:2662 - '{"offset": 0, "length": 3, "string": "foo", "captures": []}'2663 - '{"offset": 8, "length": 3, "string": "FOO", "captures": []}'2664 - program: 'match("foo (?<bar123>bar)? foo"; "ig")'2665 input: '"foo bar foo foo foo"'2666 output:2667 - '{"offset": 0, "length": 11, "string": "foo bar foo", "captures": [{"offset": 4, "length": 3, "string": "bar", "name": "bar123"}]}'2668 - '{"offset": 12, "length": 8, "string": "foo foo", "captures": [{"offset": -1, "length": 0, "string": null, "name": "bar123"}]}'26692670 - program: '[ match("."; "g")] | length'2671 input: '"abc"'2672 output: ['3']267326742675 - title: "`capture(val)`, `capture(regex; flags)`"2676 body: |26772678 Collects the named captures in a JSON object, with the name2679 of each capture as the key, and the matched string as the2680 corresponding value.26812682 examples:2683 - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2684 input: '"xyzzy-14"'2685 output: ['{ "a": "xyzzy", "n": "14" }']26862687 - title: "`scan(regex)`, `scan(regex; flags)`"2688 body: |26892690 Emit a stream of the non-overlapping substrings of the input2691 that match the regex in accordance with the flags, if any2692 have been specified. If there is no match, the stream is empty.2693 To capture all the matches for each input string, use the idiom2694 `[ expr ]`, e.g. `[ scan(regex) ]`.26952696 examples:2697 - program: 'scan("c")'2698 input: '"abcdefabc"'2699 output: ['"c"', '"c"']27002701 - title: "`split(regex; flags)`"2702 body: |27032704 Splits an input string on each regex match.27052706 For backwards compatibility, when called with a single argument,2707 `split` splits on a string, not a regex.27082709 examples:2710 - program: 'split(", *"; null)'2711 input: '"ab,cd, ef"'2712 output: ['["ab","cd","ef"]']271327142715 - title: "`splits(regex)`, `splits(regex; flags)`"2716 body: |27172718 These provide the same results as their `split` counterparts,2719 but as a stream instead of an array.27202721 examples:2722 - program: 'splits(", *")'2723 input: '"ab,cd, ef, gh"'2724 output: ['"ab"','"cd"','"ef"','"gh"']27252726 - title: "`sub(regex; tostring)`, `sub(regex; tostring; flags)`"2727 body: |27282729 Emit the string obtained by replacing the first match of2730 regex in the input string with `tostring`, after2731 interpolation. `tostring` should be a jq string or a stream2732 of such strings, each of which may contain references to2733 named captures. The named captures are, in effect, presented2734 as a JSON object (as constructed by `capture`) to2735 `tostring`, so a reference to a captured variable named "x"2736 would take the form: `"\(.x)"`.27372738 examples:2739 - program: 'sub("[^a-z]*(?<x>[a-z]+)"; "Z\(.x)"; "g")'2740 input: '"123abc456def"'2741 output: ['"ZabcZdef"']27422743 - program: '[sub("(?<a>.)"; "\(.a|ascii_upcase)", "\(.a|ascii_downcase)")]'2744 input: '"aB"'2745 output: ['["AB","aB"]']27462747 - title: "`gsub(regex; tostring)`, `gsub(regex; tostring; flags)`"2748 body: |27492750 `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2751 replaced by `tostring`, after interpolation. If the second argument is a stream2752 of jq strings, then `gsub` will produce a corresponding stream of JSON strings.27532754 examples:2755 - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2756 input: '"Abcabc"'2757 output: ['"+A-+a-"']27582759 - program: '[gsub("p"; "a", "b")]'2760 input: '"p"'2761 output: ['["a","b"]']276227632764 - title: Advanced features2765 body: |2766 Variables are an absolute necessity in most programming languages, but2767 they're relegated to an "advanced feature" in jq.27682769 In most languages, variables are the only means of passing around2770 data. If you calculate a value, and you want to use it more than once,2771 you'll need to store it in a variable. To pass a value to another part2772 of the program, you'll need that part of the program to define a2773 variable (as a function parameter, object member, or whatever) in2774 which to place the data.27752776 It is also possible to define functions in jq, although this is2777 is a feature whose biggest use is defining jq's standard library2778 (many jq functions such as `map` and `select` are in fact written2779 in jq).27802781 jq has reduction operators, which are very powerful but a bit2782 tricky. Again, these are mostly used internally, to define some2783 useful bits of jq's standard library.27842785 It may not be obvious at first, but jq is all about generators2786 (yes, as often found in other languages). Some utilities are2787 provided to help deal with generators.27882789 Some minimal I/O support (besides reading JSON from standard2790 input, and writing JSON to standard output) is available.27912792 Finally, there is a module/library system.27932794 entries:2795 - title: "Variable / Symbolic Binding Operator: `... as $identifier | ...`"2796 body: |27972798 In jq, all filters have an input and an output, so manual2799 plumbing is not necessary to pass a value from one part of a program2800 to the next. Many expressions, for instance `a + b`, pass their input2801 to two distinct subexpressions (here `a` and `b` are both passed the2802 same input), so variables aren't usually necessary in order to use a2803 value twice.28042805 For instance, calculating the average value of an array of numbers2806 requires a few variables in most languages - at least one to hold the2807 array, perhaps one for each element or for a loop counter. In jq, it's2808 simply `add / length` - the `add` expression is given the array and2809 produces its sum, and the `length` expression is given the array and2810 produces its length.28112812 So, there's generally a cleaner way to solve most problems in jq than2813 defining variables. Still, sometimes they do make things easier, so jq2814 lets you define variables using `expression as $variable`. All2815 variable names start with `$`. Here's a slightly uglier version of the2816 array-averaging example:28172818 length as $array_length | add / $array_length28192820 We'll need a more complicated problem to find a situation where using2821 variables actually makes our lives easier.282228232824 Suppose we have an array of blog posts, with "author" and "title"2825 fields, and another object which is used to map author usernames to2826 real names. Our input looks like:28272828 {"posts": [{"title": "First post", "author": "anon"},2829 {"title": "A well-written article", "author": "person1"}],2830 "realnames": {"anon": "Anonymous Coward",2831 "person1": "Person McPherson"}}28322833 We want to produce the posts with the author field containing a real2834 name, as in:28352836 {"title": "First post", "author": "Anonymous Coward"}2837 {"title": "A well-written article", "author": "Person McPherson"}28382839 We use a variable, $names, to store the realnames object, so that we2840 can refer to it later when looking up author usernames:28412842 .realnames as $names | .posts[] | {title, author: $names[.author]}28432844 The expression `exp as $x | ...` means: for each value of expression2845 `exp`, run the rest of the pipeline with the entire original input, and2846 with `$x` set to that value. Thus `as` functions as something of a2847 foreach loop.28482849 Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2850 `{$foo}` is a handy way of writing `{foo: $foo}`.28512852 Multiple variables may be declared using a single `as` expression by2853 providing a pattern that matches the structure of the input2854 (this is known as "destructuring"):28552856 . as {realnames: $names, posts: [$first, $second]} | ...28572858 The variable declarations in array patterns (e.g., `. as2859 [$first, $second]`) bind to the elements of the array in from2860 the element at index zero on up, in order. When there is no2861 value at the index for an array pattern element, `null` is2862 bound to that variable.28632864 Variables are scoped over the rest of the expression that defines2865 them, so28662867 .realnames as $names | (.posts[] | {title, author: $names[.author]})28682869 will work, but28702871 (.realnames as $names | .posts[]) | {title, author: $names[.author]}28722873 won't.28742875 For programming language theorists, it's more accurate to2876 say that jq variables are lexically-scoped bindings. In2877 particular there's no way to change the value of a binding;2878 one can only setup a new binding with the same name, but which2879 will not be visible where the old one was.28802881 examples:2882 - program: '.bar as $x | .foo | . + $x'2883 input: '{"foo":10, "bar":200}'2884 output: ['210']2885 - program: '. as $i|[(.*2|. as $i| $i), $i]'2886 input: '5'2887 output: ['[10,5]']2888 - program: '. as [$a, $b, {c: $c}] | $a + $b + $c'2889 input: '[2, 3, {"c": 4, "d": 5}]'2890 output: ['9']2891 - program: '.[] as [$a, $b] | {a: $a, b: $b}'2892 input: '[[0], [0, 1], [2, 1, 0]]'2893 output: ['{"a":0,"b":null}', '{"a":0,"b":1}', '{"a":2,"b":1}']28942895 - title: 'Destructuring Alternative Operator: `?//`'2896 body: |28972898 The destructuring alternative operator provides a concise mechanism2899 for destructuring an input that can take one of several forms.29002901 Suppose we have an API that returns a list of resources and events2902 associated with them, and we want to get the user_id and timestamp of2903 the first event for each resource. The API (having been clumsily2904 converted from XML) will only wrap the events in an array if the resource2905 has multiple events:29062907 {"resources": [{"id": 1, "kind": "widget", "events": {"action": "create", "user_id": 1, "ts": 13}},2908 {"id": 2, "kind": "widget", "events": [{"action": "create", "user_id": 1, "ts": 14}, {"action": "destroy", "user_id": 1, "ts": 15}]}]}29092910 We can use the destructuring alternative operator to handle this structural change simply:29112912 .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$user_id, $ts}]} | {$user_id, $kind, $id, $ts}29132914 Or, if we aren't sure if the input is an array of values or an object:29152916 .[] as [$id, $kind, $user_id, $ts] ?// {$id, $kind, $user_id, $ts} | ...29172918 Each alternative need not define all of the same variables, but all named2919 variables will be available to the subsequent expression. Variables not2920 matched in the alternative that succeeded will be `null`:29212922 .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$first_user_id, $first_ts}]} | {$user_id, $first_user_id, $kind, $id, $ts, $first_ts}29232924 Additionally, if the subsequent expression returns an error, the2925 alternative operator will attempt to try the next binding. Errors2926 that occur during the final alternative are passed through.29272928 [[3]] | .[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end29292930 examples:2931 - program: '.[] as {$a, $b, c: {$d, $e}} ?// {$a, $b, c: [{$d, $e}]} | {$a, $b, $d, $e}'2932 input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2933 output: ['{"a":1,"b":2,"d":3,"e":4}', '{"a":1,"b":2,"d":3,"e":4}']2934 - program: '.[] as {$a, $b, c: {$d}} ?// {$a, $b, c: [{$e}]} | {$a, $b, $d, $e}'2935 input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2936 output: ['{"a":1,"b":2,"d":3,"e":null}', '{"a":1,"b":2,"d":null,"e":4}']2937 - program: '.[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end'2938 input: '[[3]]'2939 output: ['{"a":null,"b":3}']29402941 - title: 'Defining Functions'2942 body: |29432944 You can give a filter a name using "def" syntax:29452946 def increment: . + 1;29472948 From then on, `increment` is usable as a filter just like a2949 builtin function (in fact, this is how many of the builtins2950 are defined). A function may take arguments:29512952 def map(f): [.[] | f];29532954 Arguments are passed as _filters_ (functions with no2955 arguments), _not_ as values. The same argument may be2956 referenced multiple times with different inputs (here `f` is2957 run for each element of the input array). Arguments to a2958 function work more like callbacks than like value arguments.2959 This is important to understand. Consider:29602961 def foo(f): f|f;2962 5|foo(.*2)29632964 The result will be 20 because `f` is `.*2`, and during the2965 first invocation of `f` `.` will be 5, and the second time it2966 will be 10 (5 * 2), so the result will be 20. Function2967 arguments are filters, and filters expect an input when2968 invoked.29692970 If you want the value-argument behaviour for defining simple2971 functions, you can just use a variable:29722973 def addvalue(f): f as $f | map(. + $f);29742975 Or use the short-hand:29762977 def addvalue($f): ...;29782979 With either definition, `addvalue(.foo)` will add the current2980 input's `.foo` field to each element of the array. Do note2981 that calling `addvalue(.[])` will cause the `map(. + $f)` part2982 to be evaluated once per value in the value of `.` at the call2983 site.29842985 Multiple definitions using the same function name are allowed.2986 Each re-definition replaces the previous one for the same2987 number of function arguments, but only for references from2988 functions (or main program) subsequent to the re-definition.2989 See also the section below on scoping.29902991 examples:2992 - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'2993 input: '[[1,2],[10,20]]'2994 output: ['[[1,2,1], [10,20,10]]']2995 - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'2996 input: '[[1,2],[10,20]]'2997 output: ['[[1,2,1,2], [10,20,1,2]]']29982999 - title: 'Scoping'3000 body: |30013002 There are two types of symbols in jq: value bindings (a.k.a.,3003 "variables"), and functions. Both are scoped lexically,3004 with expressions being able to refer only to symbols that3005 have been defined "to the left" of them. The only exception3006 to this rule is that functions can refer to themselves so as3007 to be able to create recursive functions.30083009 For example, in the following expression there is a binding3010 which is visible "to the right" of it, `... | .*3 as3011 $times_three | [. + $times_three] | ...`, but not "to the3012 left". Consider this expression now, `... | (.*3 as3013 $times_three | [. + $times_three]) | ...`: here the binding3014 `$times_three` is _not_ visible past the closing parenthesis.30153016 - title: "`isempty(exp)`"3017 body: |30183019 Returns true if `exp` produces no outputs, false otherwise.30203021 examples:3022 - program: 'isempty(empty)'3023 input: 'null'3024 output: ['true']30253026 - program: 'isempty(.[])'3027 input: '[]'3028 output: ['true']30293030 - program: 'isempty(.[])'3031 input: '[1,2,3]'3032 output: ['false']30333034 - title: "`limit(n; exp)`"3035 body: |30363037 The `limit` function extracts up to `n` outputs from `exp`.30383039 examples:3040 - program: '[limit(3;.[])]'3041 input: '[0,1,2,3,4,5,6,7,8,9]'3042 output: ['[0,1,2]']30433044 - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"3045 body: |30463047 The `first(expr)` and `last(expr)` functions extract the first3048 and last values from `expr`, respectively.30493050 The `nth(n; expr)` function extracts the nth value output by `expr`.3051 Note that `nth(n; expr)` doesn't support negative values of `n`.30523053 examples:3054 - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'3055 input: '10'3056 output: ['[0,9,5]']30573058 - title: "`first`, `last`, `nth(n)`"3059 body: |30603061 The `first` and `last` functions extract the first3062 and last values from any array at `.`.30633064 The `nth(n)` function extracts the nth value of any array at `.`.30653066 examples:3067 - program: '[range(.)]|[first, last, nth(5)]'3068 input: '10'3069 output: ['[0,9,5]']30703071 - title: "`reduce`"3072 body: |30733074 The `reduce` syntax allows you to combine all of the results of3075 an expression by accumulating them into a single answer.3076 The form is `reduce EXP as $var (INIT; UPDATE)`.3077 As an example, we'll pass `[1,2,3]` to this expression:30783079 reduce .[] as $item (0; . + $item)30803081 For each result that `.[]` produces, `. + $item` is run to3082 accumulate a running total, starting from 0 as the input value.3083 In this example, `.[]` produces the results `1`, `2`, and `3`,3084 so the effect is similar to running something like this:30853086 0 | 1 as $item | . + $item |3087 2 as $item | . + $item |3088 3 as $item | . + $item30893090 examples:3091 - program: 'reduce .[] as $item (0; . + $item)'3092 input: '[1,2,3,4,5]'3093 output: ['15']30943095 - program: 'reduce .[] as [$i,$j] (0; . + $i * $j)'3096 input: '[[1,2],[3,4],[5,6]]'3097 output: ['44']30983099 - program: 'reduce .[] as {$x,$y} (null; .x += $x | .y += [$y])'3100 input: '[{"x":"a","y":1},{"x":"b","y":2},{"x":"c","y":3}]'3101 output: ['{"x":"abc","y":[1,2,3]}']31023103 - title: "`foreach`"3104 body: |31053106 The `foreach` syntax is similar to `reduce`, but intended to3107 allow the construction of `limit` and reducers that produce3108 intermediate results.31093110 The form is `foreach EXP as $var (INIT; UPDATE; EXTRACT)`.3111 As an example, we'll pass `[1,2,3]` to this expression:31123113 foreach .[] as $item (0; . + $item; [$item, . * 2])31143115 Like the `reduce` syntax, `. + $item` is run for each result3116 that `.[]` produces, but `[$item, . * 2]` is run for each3117 intermediate values. In this example, since the intermediate3118 values are `1`, `3`, and `6`, the `foreach` expression produces3119 `[1,2]`, `[2,6]`, and `[3,12]`. So the effect is similar3120 to running something like this:31213122 0 | 1 as $item | . + $item | [$item, . * 2],3123 2 as $item | . + $item | [$item, . * 2],3124 3 as $item | . + $item | [$item, . * 2]31253126 When `EXTRACT` is omitted, the identity filter is used.3127 That is, it outputs the intermediate values as they are.31283129 examples:3130 - program: 'foreach .[] as $item (0; . + $item)'3131 input: '[1,2,3,4,5]'3132 output: ['1','3','6','10','15']31333134 - program: 'foreach .[] as $item (0; . + $item; [$item, . * 2])'3135 input: '[1,2,3,4,5]'3136 output: ['[1,2]','[2,6]','[3,12]','[4,20]','[5,30]']31373138 - program: 'foreach .[] as $item (0; . + 1; {index: ., $item})'3139 input: '["foo", "bar", "baz"]'3140 output:3141 - '{"index":1,"item":"foo"}'3142 - '{"index":2,"item":"bar"}'3143 - '{"index":3,"item":"baz"}'31443145 - title: Recursion3146 body: |31473148 As described above, `recurse` uses recursion, and any jq3149 function can be recursive. The `while` builtin is also3150 implemented in terms of recursion.31513152 Tail calls are optimized whenever the expression to the left of3153 the recursive call outputs its last value. In practice this3154 means that the expression to the left of the recursive call3155 should not produce more than one output for each input.31563157 For example:31583159 def recurse(f): def r: ., (f | select(. != null) | r); r;31603161 def while(cond; update):3162 def _while:3163 if cond then ., (update | _while) else empty end;3164 _while;31653166 def repeat(exp):3167 def _repeat:3168 exp, _repeat;3169 _repeat;31703171 - title: Generators and iterators3172 body: |31733174 Some jq operators and functions are actually generators in3175 that they can produce zero, one, or more values for each3176 input, just as one might expect in other programming3177 languages that have generators. For example, `.[]`3178 generates all the values in its input (which must be an3179 array or an object), `range(0; 10)` generates the integers3180 between 0 and 10, and so on.31813182 Even the comma operator is a generator, generating first3183 the values generated by the expression to the left of the3184 comma, then the values generated by the expression on the3185 right of the comma.31863187 The `empty` builtin is the generator that produces zero3188 outputs. The `empty` builtin backtracks to the preceding3189 generator expression.31903191 All jq functions can be generators just by using builtin3192 generators. It is also possible to construct new generators3193 using only recursion and the comma operator. If3194 recursive calls are "in tail position" then the3195 generator will be efficient. In the example below the3196 recursive call by `_range` to itself is in tail position.3197 The example shows off three advanced topics: tail recursion,3198 generator construction, and sub-functions.31993200 examples:3201 - program: 'def range(init; upto; by):3202 def _range:3203 if (by > 0 and . < upto) or (by < 0 and . > upto)3204 then ., ((.+by)|_range)3205 else . end;3206 if by == 0 then init else init|_range end |3207 select((by > 0 and . < upto) or (by < 0 and . > upto));3208 range(0; 10; 3)'3209 input: 'null'3210 output: ['0', '3', '6', '9']3211 - program: 'def while(cond; update):3212 def _while:3213 if cond then ., (update | _while) else empty end;3214 _while;3215 [while(.<100; .*2)]'3216 input: '1'3217 output: ['[1,2,4,8,16,32,64]']32183219 - title: 'Math'3220 body: |32213222 jq currently only has IEEE754 double-precision (64-bit) floating3223 point number support.32243225 Besides simple arithmetic operators such as `+`, jq also has most3226 standard math functions from the C math library. C math functions3227 that take a single input argument (e.g., `sin()`) are available as3228 zero-argument jq functions. C math functions that take two input3229 arguments (e.g., `pow()`) are available as two-argument jq3230 functions that ignore `.`. C math functions that take three input3231 arguments are available as three-argument jq functions that ignore3232 `.`.32333234 Availability of standard math functions depends on the3235 availability of the corresponding math functions in your operating3236 system and C math library. Unavailable math functions will be3237 defined but will raise an error.32383239 One-input C math functions: `acos` `acosh` `asin` `asinh` `atan`3240 `atanh` `cbrt` `ceil` `cos` `cosh` `erf` `erfc` `exp` `exp10`3241 `exp2` `expm1` `fabs` `floor` `gamma` `j0` `j1` `lgamma` `log`3242 `log10` `log1p` `log2` `logb` `nearbyint` `rint` `round`3243 `significand` `sin` `sinh` `sqrt` `tan` `tanh` `tgamma` `trunc`3244 `y0` `y1`.32453246 Two-input C math functions: `atan2` `copysign` `drem` `fdim`3247 `fmax` `fmin` `fmod` `frexp` `hypot` `jn` `ldexp` `modf`3248 `nextafter` `nexttoward` `pow` `remainder` `scalb` `scalbln` `yn`.32493250 Three-input C math functions: `fma`.32513252 See your system's manual for more information on each of these.32533254 - title: 'I/O'3255 body: |32563257 At this time jq has minimal support for I/O, mostly in the3258 form of control over when inputs are read. Two builtins functions3259 are provided for this, `input` and `inputs`, that read from the3260 same sources (e.g., `stdin`, files named on the command-line) as3261 jq itself. These two builtins, and jq's own reading actions, can3262 be interleaved with each other. They are commonly used in combination3263 with the null input option `-n` to prevent one input from being read3264 implicitly.32653266 Two builtins provide minimal output capabilities, `debug`, and3267 `stderr`. (Recall that a jq program's output values are always3268 output as JSON texts on `stdout`.) The `debug` builtin can have3269 application-specific behavior, such as for executables that use3270 the libjq C API but aren't the jq executable itself. The `stderr`3271 builtin outputs its input in raw mode to stder with no additional3272 decoration, not even a newline.32733274 Most jq builtins are referentially transparent, and yield constant3275 and repeatable value streams when applied to constant inputs.3276 This is not true of I/O builtins.32773278 entries:3279 - title: "`input`"3280 body: |32813282 Outputs one new input.32833284 Note that when using `input` it is generally be necessary to3285 invoke jq with the `-n` command-line option, otherwise3286 the first entity will be lost.32873288 echo 1 2 3 4 | jq '[., input]' # [1,2] [3,4]32893290 - title: "`inputs`"3291 body: |32923293 Outputs all remaining inputs, one by one.32943295 This is primarily useful for reductions over a program's3296 inputs. Note that when using `inputs` it is generally necessary3297 to invoke jq with the `-n` command-line option, otherwise3298 the first entity will be lost.32993300 echo 1 2 3 | jq -n 'reduce inputs as $i (0; . + $i)' # 633013302 - title: "`debug`, `debug(msgs)`"3303 body: |33043305 These two filters are like `.` but have as a side-effect the3306 production of one or more messages on stderr.33073308 The message produced by the `debug` filter has the form33093310 ["DEBUG:",<input-value>]33113312 where `<input-value>` is a compact rendition of the input3313 value. This format may change in the future.33143315 The `debug(msgs)` filter is defined as `(msgs | debug | empty), .`3316 thus allowing great flexibility in the content of the message,3317 while also allowing multi-line debugging statements to be created.33183319 For example, the expression:33203321 1 as $x | 2 | debug("Entering function foo with $x == \($x)", .) | (.+1)33223323 would produce the value 3 but with the following two lines3324 being written to stderr:33253326 ["DEBUG:","Entering function foo with $x == 1"]3327 ["DEBUG:",2]33283329 - title: "`stderr`"3330 body: |33313332 Prints its input in raw and compact mode to stderr with no3333 additional decoration, not even a newline.33343335 - title: "`input_filename`"3336 body: |33373338 Returns the name of the file whose input is currently being3339 filtered. Note that this will not work well unless jq is3340 running in a UTF-8 locale.33413342 - title: "`input_line_number`"3343 body: |33443345 Returns the line number of the input currently being filtered.33463347 - title: 'Streaming'3348 body: |33493350 With the `--stream` option jq can parse input texts in a streaming3351 fashion, allowing jq programs to start processing large JSON texts3352 immediately rather than after the parse completes. If you have a3353 single JSON text that is 1GB in size, streaming it will allow you3354 to process it much more quickly.33553356 However, streaming isn't easy to deal with as the jq program will3357 have `[<path>, <leaf-value>]` (and a few other forms) as inputs.33583359 Several builtins are provided to make handling streams easier.33603361 The examples below use the streamed form of `[0,[1]]`, which is3362 `[[0],0],[[1,0],1],[[1,0]],[[1]]`.33633364 Streaming forms include `[<path>, <leaf-value>]` (to indicate any3365 scalar value, empty array, or empty object), and `[<path>]` (to3366 indicate the end of an array or object). Future versions of jq3367 run with `--stream` and `--seq` may output additional forms such3368 as `["error message"]` when an input text fails to parse.33693370 entries:3371 - title: "`truncate_stream(stream_expression)`"3372 body: |33733374 Consumes a number as input and truncates the corresponding3375 number of path elements from the left of the outputs of the3376 given streaming expression.33773378 examples:3379 - program: 'truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])'3380 input: '1'3381 output: ['[[0],2]', '[[0]]']33823383 - title: "`fromstream(stream_expression)`"3384 body: |33853386 Outputs values corresponding to the stream expression's3387 outputs.33883389 examples:3390 - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'3391 input: 'null'3392 output: ['[2]']33933394 - title: "`tostream`"3395 body: |33963397 The `tostream` builtin outputs the streamed form of its input.33983399 examples:3400 - program: '. as $dot|fromstream($dot|tostream)|.==$dot'3401 input: '[0,[1,{"a":1},{"b":2}]]'3402 output: ['true']34033404 - title: Assignment3405 body: |3406 Assignment works a little differently in jq than in most3407 programming languages. jq doesn't distinguish between references3408 to and copies of something - two objects or arrays are either3409 equal or not equal, without any further notion of being "the3410 same object" or "not the same object".34113412 If an object has two fields which are arrays, `.foo` and `.bar`,3413 and you append something to `.foo`, then `.bar` will not get3414 bigger, even if you've previously set `.bar = .foo`. If you're3415 used to programming in languages like Python, Java, Ruby,3416 JavaScript, etc. then you can think of it as though jq does a full3417 deep copy of every object before it does the assignment (for3418 performance it doesn't actually do that, but that's the general3419 idea).34203421 This means that it's impossible to build circular values in jq3422 (such as an array whose first element is itself). This is quite3423 intentional, and ensures that anything a jq program can produce3424 can be represented in JSON.34253426 All the assignment operators in jq have path expressions on the3427 left-hand side (LHS). The right-hand side (RHS) provides values3428 to set to the paths named by the LHS path expressions.34293430 Values in jq are always immutable. Internally, assignment works3431 by using a reduction to compute new, replacement values for `.` that3432 have had all the desired assignments applied to `.`, then3433 outputting the modified value. This might be made clear by this3434 example: `{a:{b:{c:1}}} | (.a.b|=3), .`. This will output3435 `{"a":{"b":3}}` and `{"a":{"b":{"c":1}}}` because the last3436 sub-expression, `.`, sees the original value, not the modified3437 value.34383439 Most users will want to use modification assignment operators,3440 such as `|=` or `+=`, rather than `=`.34413442 Note that the LHS of assignment operators refers to a value in3443 `.`. Thus `$var.foo = 1` won't work as expected (`$var.foo` is3444 not a valid or useful path expression in `.`); use `$var | .foo =3445 1` instead.34463447 Note too that `.a,.b=0` does not set `.a` and `.b`, but3448 `(.a,.b)=0` sets both.34493450 entries:3451 - title: "Update-assignment: `|=`"3452 body: |3453 This is the "update" operator `|=`. It takes a filter on the3454 right-hand side and works out the new value for the property3455 of `.` being assigned to by running the old value through this3456 expression. For instance, `(.foo, .bar) |= .+1` will build an3457 object with the `foo` field set to the input's `foo` plus 1,3458 and the `bar` field set to the input's `bar` plus 1.34593460 The left-hand side can be any general path expression; see `path()`.34613462 Note that the left-hand side of `|=` refers to a value in `.`.3463 Thus `$var.foo |= . + 1` won't work as expected (`$var.foo` is3464 not a valid or useful path expression in `.`); use `$var |3465 .foo |= . + 1` instead.34663467 If the right-hand side outputs no values (i.e., `empty`), then3468 the left-hand side path will be deleted, as with `del(path)`.34693470 If the right-hand side outputs multiple values, only the first3471 one will be used (COMPATIBILITY NOTE: in jq 1.5 and earlier3472 releases, it used to be that only the last one was used).34733474 examples:3475 - program: '(..|select(type=="boolean")) |= if . then 1 else 0 end'3476 input: '[true,false,[5,true,[true,[false]],false]]'3477 output: ['[1,0,[5,1,[1,[0]],0]]']34783479 - title: "Arithmetic update-assignment: `+=`, `-=`, `*=`, `/=`, `%=`, `//=`"3480 body: |34813482 jq has a few operators of the form `a op= b`, which are all3483 equivalent to `a |= . op b`. So, `+= 1` can be used to3484 increment values, being the same as `|= . + 1`.34853486 examples:3487 - program: .foo += 13488 input: '{"foo": 42}'3489 output: ['{"foo": 43}']34903491 - title: "Plain assignment: `=`"3492 body: |34933494 This is the plain assignment operator. Unlike the others, the3495 input to the right-hand side (RHS) is the same as the input to3496 the left-hand side (LHS) rather than the value at the LHS3497 path, and all values output by the RHS will be used (as shown3498 below).34993500 If the RHS of `=` produces multiple values, then for each such3501 value jq will set the paths on the left-hand side to the value3502 and then it will output the modified `.`. For example,3503 `(.a,.b) = range(2)` outputs `{"a":0,"b":0}`, then3504 `{"a":1,"b":1}`. The "update" assignment forms (see above) do3505 not do this.35063507 This example should show the difference between `=` and `|=`:35083509 Provide input `{"a": {"b": 10}, "b": 20}` to the programs35103511 .a = .b35123513 and35143515 .a |= .b35163517 The former will set the `a` field of the input to the `b`3518 field of the input, and produce the output `{"a": 20, "b": 20}`.3519 The latter will set the `a` field of the input to the `a`3520 field's `b` field, producing `{"a": 10, "b": 20}`.35213522 examples:3523 - program: .a = .b3524 input: '{"a": {"b": 10}, "b": 20}'3525 output: ['{"a":20,"b":20}']35263527 - program: .a |= .b3528 input: '{"a": {"b": 10}, "b": 20}'3529 output: ['{"a":10,"b":20}']35303531 - program: (.a, .b) = range(3)3532 input: 'null'3533 output:3534 - '{"a":0,"b":0}'3535 - '{"a":1,"b":1}'3536 - '{"a":2,"b":2}'35373538 - program: (.a, .b) |= range(3)3539 input: 'null'3540 output: ['{"a":0,"b":0}']35413542 - title: Complex assignments3543 body: |3544 Lots more things are allowed on the left-hand side of a jq assignment3545 than in most languages. We've already seen simple field accesses on3546 the left hand side, and it's no surprise that array accesses work just3547 as well:35483549 .posts[0].title = "JQ Manual"35503551 What may come as a surprise is that the expression on the left may3552 produce multiple results, referring to different points in the input3553 document:35543555 .posts[].comments |= . + ["this is great"]35563557 That example appends the string "this is great" to the "comments"3558 array of each post in the input (where the input is an object with a3559 field "posts" which is an array of posts).35603561 When jq encounters an assignment like 'a = b', it records the "path"3562 taken to select a part of the input document while executing a. This3563 path is then used to find which part of the input to change while3564 executing the assignment. Any filter may be used on the3565 left-hand side of an equals - whichever paths it selects from the3566 input will be where the assignment is performed.35673568 This is a very powerful operation. Suppose we wanted to add a comment3569 to blog posts, using the same "blog" input above. This time, we only3570 want to comment on the posts written by "stedolan". We can find those3571 posts using the "select" function described earlier:35723573 .posts[] | select(.author == "stedolan")35743575 The paths provided by this operation point to each of the posts that3576 "stedolan" wrote, and we can comment on each of them in the same way3577 that we did before:35783579 (.posts[] | select(.author == "stedolan") | .comments) |=3580 . + ["terrible."]35813582 - title: Comments35833584 body: |35853586 You can write comments in your jq filters using `#`.35873588 A `#` character (not part of a string) starts a comment.3589 All characters from `#` to the end of the line are ignored.35903591 If the end of the line is preceded by an odd number of backslash3592 characters, the following line is also considered part of the3593 comment and is ignored.35943595 For example, the following code outputs `[1,3,4,7]`35963597 [3598 1,3599 # foo \3600 2,3601 # bar \\3602 3,3603 4, # baz \\\3604 5, \3605 6,3606 73607 # comment \3608 comment \3609 comment3610 ]36113612 Backslash continuing the comment on the next line can be useful3613 when writing the "shebang" for a jq script:36143615 #!/bin/sh --3616 # total - Output the sum of the given arguments (or stdin)3617 # usage: total [numbers...]3618 # \3619 exec jq --args -MRnf "$0" -- "$@"36203621 $ARGS.positional |3622 reduce (3623 if . == []3624 then inputs3625 else .[]3626 end |3627 . as $dot |3628 try tonumber catch false |3629 if not or isnan then3630 @json "total: Invalid number \($dot).\n" | halt_error(1)3631 end3632 ) as $n (0; . + $n)36333634 The `exec` line is considered a comment by jq, so it is ignored.3635 But it is not ignored by `sh`, since in `sh` a backslash at the3636 end of the line does not continue the comment.3637 With this trick, when the script is invoked as `total 1 2`,3638 `/bin/sh -- /path/to/total 1 2` will be run, and `sh` will then3639 run `exec jq --args -MRnf /path/to/total -- 1 2` replacing itself3640 with a `jq` interpreter invoked with the specified options (`-M`,3641 `-R`, `-n`, `--args`), that evaluates the current file (`$0`),3642 with the arguments (`$@`) that were passed to `sh`.36433644 - title: Modules3645 body: |36463647 jq has a library/module system. Modules are files whose names end3648 in `.jq`.36493650 Modules imported by a program are searched for in a default search3651 path (see below). The `import` and `include` directives allow the3652 importer to alter this path.36533654 Paths in the search path are subject to various substitutions.36553656 For paths starting with `~/`, the user's home directory is3657 substituted for `~`.36583659 For paths starting with `$ORIGIN/`, the directory where the jq3660 executable is located is substituted for `$ORIGIN`.36613662 For paths starting with `./` or paths that are `.`, the path of3663 the including file is substituted for `.`. For top-level programs3664 given on the command-line, the current directory is used.36653666 Import directives can optionally specify a search path to which3667 the default is appended.36683669 The default search path is the search path given to the `-L`3670 command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",3671 "$ORIGIN/../lib"]`.36723673 Null and empty string path elements terminate search path3674 processing.36753676 A dependency with relative path `foo/bar` would be searched for in3677 `foo/bar.jq` and `foo/bar/bar.jq` in the given search path. This3678 is intended to allow modules to be placed in a directory along3679 with, for example, version control files, README files, and so on,3680 but also to allow for single-file modules.36813682 Consecutive components with the same name are not allowed to avoid3683 ambiguities (e.g., `foo/foo`).36843685 For example, with `-L$HOME/.jq` a module `foo` can be found in3686 `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.36873688 If `$HOME/.jq` is a file, it is sourced into the main program.36893690 entries:3691 - title: "`import RelativePathString as NAME [<metadata>];`"3692 body: |36933694 Imports a module found at the given path relative to a3695 directory in a search path. A `.jq` suffix will be added to3696 the relative path string. The module's symbols are prefixed3697 with `NAME::`.36983699 The optional metadata must be a constant jq expression. It3700 should be an object with keys like `homepage` and so on. At3701 this time jq only uses the `search` key/value of the metadata.3702 The metadata is also made available to users via the3703 `modulemeta` builtin.37043705 The `search` key in the metadata, if present, should have a3706 string or array value (array of strings); this is the search3707 path to be prefixed to the top-level search path.37083709 - title: "`include RelativePathString [<metadata>];`"3710 body: |37113712 Imports a module found at the given path relative to a3713 directory in a search path as if it were included in place. A3714 `.jq` suffix will be added to the relative path string. The3715 module's symbols are imported into the caller's namespace as3716 if the module's content had been included directly.37173718 The optional metadata must be a constant jq expression. It3719 should be an object with keys like `homepage` and so on. At3720 this time jq only uses the `search` key/value of the metadata.3721 The metadata is also made available to users via the3722 `modulemeta` builtin.37233724 - title: "`import RelativePathString as $NAME [<metadata>];`"3725 body: |37263727 Imports a JSON file found at the given path relative to a3728 directory in a search path. A `.json` suffix will be added to3729 the relative path string. The file's data will be available3730 as `$NAME::NAME`.37313732 The optional metadata must be a constant jq expression. It3733 should be an object with keys like `homepage` and so on. At3734 this time jq only uses the `search` key/value of the metadata.3735 The metadata is also made available to users via the3736 `modulemeta` builtin.37373738 The `search` key in the metadata, if present, should have a3739 string or array value (array of strings); this is the search3740 path to be prefixed to the top-level search path.37413742 - title: "`module <metadata>;`"3743 body: |37443745 This directive is entirely optional. It's not required for3746 proper operation. It serves only the purpose of providing3747 metadata that can be read with the `modulemeta` builtin.37483749 The metadata must be a constant jq expression. It should be3750 an object with keys like `homepage`. At this time jq doesn't3751 use this metadata, but it is made available to users via the3752 `modulemeta` builtin.37533754 - title: "`modulemeta`"3755 body: |37563757 Takes a module name as input and outputs the module's metadata3758 as an object, with the module's imports (including metadata)3759 as an array value for the `deps` key and the module's defined3760 functions as an array value for the `defs` key.37613762 Programs can use this to query a module's metadata, which they3763 could then use to, for example, search for, download, and3764 install missing dependencies.37653766 - title: Colors3767 body: |37683769 To configure alternative colors just set the `JQ_COLORS`3770 environment variable to colon-delimited list of partial terminal3771 escape sequences like `"1;31"`, in this order:37723773 - color for `null`3774 - color for `false`3775 - color for `true`3776 - color for numbers3777 - color for strings3778 - color for arrays3779 - color for objects3780 - color for object keys37813782 The default color scheme is the same as setting3783 `JQ_COLORS="0;90:0;39:0;39:0;39:0;32:1;39:1;39:1;34"`.37843785 This is not a manual for VT100/ANSI escapes. However, each of3786 these color specifications should consist of two numbers separated3787 by a semi-colon, where the first number is one of these:37883789 - 1 (bright)3790 - 2 (dim)3791 - 4 (underscore)3792 - 5 (blink)3793 - 7 (reverse)3794 - 8 (hidden)37953796 and the second is one of these:37973798 - 30 (black)3799 - 31 (red)3800 - 32 (green)3801 - 33 (yellow)3802 - 34 (blue)3803 - 35 (magenta)3804 - 36 (cyan)3805 - 37 (white)1v1.7/manual.yml
modified:docs/templates/manual.html.j2+11 added-1 removed
31 unmodified lines
32 {%- set _ = section_ids.__setitem__(id, true) %}33 {%- endmacro %}34 <main id="main" class="col-md-9" data-bs-spy="scroll" data-bs-target="#contents" data-bs-threshold="0,1" data-bs-root-margin="-30% 0% -70%">35 <h1>{{ headline }}</h1>36 {{ history | markdownify }}36 <p>37 <em>38 For other versions, see39 <a href="{{ root }}/manual/v1.7/">1.7</a>,40 <a href="{{ root }}/manual/v1.6/">1.6</a>,41 <a href="{{ root }}/manual/v1.5/">1.5</a>,42 <a href="{{ root }}/manual/v1.4/">1.4</a>,43 <a href="{{ root }}/manual/v1.3/">1.3</a> or44 <a href="{{ root }}/manual/dev/">development version</a>.45 </em>46 </p>47 {{ body | markdownify }}48 {%- for section in sections %}49 <section id="{{ section.title | section_id }}">{{ check_section_id(section.title | section_id) }}50 <h2>{{ section.title }} <a href="#{{ section.title | section_id }}" class="icon-link" aria-label="Link to this section: {{ section.title }}"><span class="bi bi-link-45deg" aria-hidden="true"></span></a></h2>
70 unmodified lines
modified:docs/build_manpage.py+1 added-1 removed
207 unmodified lines
208209210def convert_manual_to_markdown():211 f = StringIO()212 manual = load_yml_file("content/manual/manual.yml")212 manual = load_yml_file("content/manual/dev/manual.yml")213 f.write(manual.get('manpage_intro', '\n'))214 f.write(dedent_body(manual.get('body', '\n')))215 for section in manual.get('sections', []):216 f.write('## {}\n'.format(section.get('title', '').upper()))
35 unmodified lines
modified:docs/build_mantests.py+1 added-1 removed
3 unmodified lines
45regex_program_pattern = re.compile(6 r'\b(?:test|match|capture|scan|split|splits|sub|gsub)\s*\(')78with open('content/manual/manual.yml') as source, \8with open('content/manual/dev/manual.yml') as source, \9 open('../tests/man.test', 'w') as man, \10 open('../tests/manonig.test', 'w') as manonig:11 manual = yaml.safe_load(source)12 for section in manual.get('sections', []):
9 unmodified lines
modified:docs/manual_schema.yml-3 removed
1type: object2required:3 - headline4 - history4 - body5 - manpage_intro6 - manpage_epilogue7 - sections8additionalProperties: false9properties:10 headline:11 type: string13 history:14 type: string12 body:13 type: string14 manpage_intro:15 type: string
45 unmodified lines
modified:Makefile.am+4 added-4 removed
158 unmodified lines
159# As a result, we need to rebuild the tests if the manual has been updated.160# Making changes to the manpage without having the python deps means your161# tests won't run. If you aren't making changes to the examples, you probably162# don't care. But if you are, then you need to run the tests anyway.163tests/man.test tests/manonig.test: $(srcdir)/docs/content/manual/manual.yml163tests/man.test tests/manonig.test: $(srcdir)/docs/content/manual/dev/manual.yml164if ENABLE_DOCS165 $(AM_V_GEN) ( cd ${abs_srcdir}/docs && \166 $(PIPENV) run python validate_manual_schema.py content/manual/manual.yml && \166 $(PIPENV) run python validate_manual_schema.py content/manual/dev/manual.yml && \167 $(PIPENV) run python build_mantests.py )168else169 @echo Changes to the manual.yml require docs to be enabled to update the manual test.170 @echo As a result, the manual test is out of date.
4 unmodified lines
175# We build the docs from the manpage yml. If no changes have been made to the176# manpage, then we'll end up using the cached version. Otherwise, we need to177# rebuild it.178man_MANS = jq.1179jq.1.prebuilt: $(srcdir)/docs/content/manual/manual.yml179jq.1.prebuilt: $(srcdir)/docs/content/manual/dev/manual.yml180if ENABLE_DOCS181 $(AM_V_GEN) ( cd ${abs_srcdir}/docs && \182 $(PIPENV) run python validate_manual_schema.py content/manual/manual.yml && \182 $(PIPENV) run python validate_manual_schema.py content/manual/dev/manual.yml && \183 $(PIPENV) run python build_manpage.py ) > $@184else185 @echo Changes to the manual.yml require docs to be enabled to update the manpage.186 @echo As a result, the manpage is out of date.
69 unmodified lines