Skip to content
Myr

Update website with details for jq-1.6

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

authored by William Langford · committed by William Langford · parent cd4f61a · Browse files · 4 files+3314 added−2 removed
This commit

State

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

Diff stats

4 files+3314 added−2 removed

  • other:+3314 added−2 removed

4 files+3314 added−2 removed

modified:docs/content/2.download/default.yml+18 added
added:docs/content/3.manual/v1.6/manual.yml+3287 added
1---2headline: jq Manual (development version)34history: |56 *For released versions, see [jq 1.5](/jq/manual/v1.5),7 [jq 1.4](/jq/manual/v1.4) or [jq 1.3](/jq/manual/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/stedolan/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 out, again as a82 sequence of whitespace-separated JSON data.8384 Note: it is important to mind the shell's quoting rules. As a85 general rule it's best to always quote (with single-quote86 characters) the jq program, as too many characters with special87 meaning to jq are also shell meta-characters. For example, `jq88 "foo"` will fail on most Unix shells because that will be the same89 as `jq foo`, which will generally fail because `foo is not90 defined`. When using the Windows command shell (cmd.exe) it's91 best to use double quotes around your jq program when given on the92 command-line (instead of the `-f program-file` option), but then93 double-quotes in the jq program need backslash escaping.9495 You can affect how jq reads and writes its input and output96 using some command-line options:9798 * `--version`:99100 Output the jq version and exit with zero.101102 * `--seq`:103104 Use the `application/json-seq` MIME type scheme for separating105 JSON texts in jq's input and output. This means that an ASCII106 RS (record separator) character is printed before each value on107 output and an ASCII LF (line feed) is printed after every108 output. Input JSON texts that fail to parse are ignored (but109 warned about), discarding all subsequent input until the next110 RS. This mode also parses the output of jq without the `--seq`111 option.112113 * `--stream`:114115 Parse the input in streaming fashion, outputing arrays of path116 and leaf values (scalars and empty arrays or empty objects).117 For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]`118 becomes `[[0],[]]`, `[[1],"a"]`, and `[[1,0],"b"]`.119120 This is useful for processing very large inputs. Use this in121 conjunction with filtering and the `reduce` and `foreach` syntax122 to reduce large inputs incrementally.123124 * `--slurp`/`-s`:125126 Instead of running the filter for each JSON object in the127 input, read the entire input stream into a large array and run128 the filter just once.129130 * `--raw-input`/`-R`:131132 Don't parse the input as JSON. Instead, each line of text is133 passed to the filter as a string. If combined with `--slurp`,134 then the entire input is passed to the filter as a single long135 string.136137 * `--null-input`/`-n`:138139 Don't read any input at all! Instead, the filter is run once140 using `null` as the input. This is useful when using jq as a141 simple calculator or to construct JSON data from scratch.142143 * `--compact-output` / `-c`:144145 By default, jq pretty-prints JSON output. Using this option146 will result in more compact output by instead putting each147 JSON object on a single line.148149 * `--tab`:150151 Use a tab for each indentation level instead of two spaces.152153 * `--indent n`:154155 Use the given number of spaces (no more than 8) for indentation.156157 * `--color-output` / `-C` and `--monochrome-output` / `-M`:158159 By default, jq outputs colored JSON if writing to a160 terminal. You can force it to produce color even if writing to161 a pipe or a file using `-C`, and disable color with `-M`.162163 Colors can be configured with the `JQ_COLORS` environment164 variable (see below).165166 * `--ascii-output` / `-a`:167168 jq usually outputs non-ASCII Unicode codepoints as UTF-8, even169 if the input specified them as escape sequences (like170 "\u03bc"). Using this option, you can force jq to produce pure171 ASCII output with every non-ASCII character replaced with the172 equivalent escape sequence.173174 * `--unbuffered`175176 Flush the output after each JSON object is printed (useful if177 you're piping a slow data source into jq and piping jq's178 output elsewhere).179180 * `--sort-keys` / `-S`:181182 Output the fields of each object with the keys in sorted order.183184 * `--raw-output` / `-r`:185186 With this option, if the filter's result is a string then it187 will be written directly to standard output rather than being188 formatted as a JSON string with quotes. This can be useful for189 making jq filters talk to non-JSON-based systems.190191 * `--join-output` / `-j`:192193 Like `-r` but jq won't print a newline after each output.194195 * `-f filename` / `--from-file filename`:196197 Read filter from the file rather than from a command line, like198 awk's -f option. You can also use '#' to make comments.199200 * `-Ldirectory` / `-L directory`:201202 Prepend `directory` to the search list for modules. If this203 option is used then no builtin search list is used. See the204 section on modules below.205206 * `-e` / `--exit-status`:207208 Sets the exit status of jq to 0 if the last output values was209 neither `false` nor `null`, 1 if the last output value was210 either `false` or `null`, or 4 if no valid result was ever211 produced. Normally jq exits with 2 if there was any usage212 problem or system error, 3 if there was a jq program compile213 error, or 0 if the jq program ran.214215 Another way to set the exit status is with the `halt_error`216 builtin function.217218 * `--arg name value`:219220 This option passes a value to the jq program as a predefined221 variable. If you run jq with `--arg foo bar`, then `$foo` is222 available in the program and has the value `"bar"`. Note that223 `value` will be treated as a string, so `--arg foo 123` will224 bind `$foo` to `"123"`.225226 Named arguments are also available to the jq program as227 `$ARGS.named`.228229 * `--argjson name JSON-text`:230231 This option passes a JSON-encoded value to the jq program as a232 predefined variable. If you run jq with `--argjson foo 123`, then233 `$foo` is available in the program and has the value `123`.234235 * `--slurpfile variable-name filename`:236237 This option reads all the JSON texts in the named file and binds238 an array of the parsed JSON values to the given global variable.239 If you run jq with `--slurpfile foo bar`, then `$foo` is available240 in the program and has an array whose elements correspond to the241 texts in the file named `bar`.242243 * `--rawfile variable-name filename`:244245 This option reads in the named file and binds its contents to the given246 global variable. If you run jq with `--rawfile foo bar`, then `$foo` is247 available in the program and has a string whose contents are to the texs248 in the file named `bar`.249250 * `--argfile variable-name filename`:251252 Do not use. Use `--slurpfile` instead.253254 (This option is like `--slurpfile`, but when the file has just255 one text, then that is used, else an array of texts is used as256 in `--slurpfile`.)257258 * `--args`:259260 Remaining arguments are positional string arguments. These are261 available to the jq program as `$ARGS.positional[]`.262263 * `--jsonargs`:264265 Remaining arguments are positional JSON text arguments. These266 are available to the jq program as `$ARGS.positional[]`.267268 * `--run-tests [filename]`:269270 Runs the tests in the given file or standard input. This must271 be the last option given and does not honor all preceding272 options. The input consists of comment lines, empty lines, and273 program lines followed by one input line, as many lines of274 output as are expected (one per output), and a terminating empty275 line. Compilation failure tests start with a line containing276 only "%%FAIL", then a line containing the program to compile,277 then a line containing an error message to compare to the278 actual.279280 Be warned that this option can change backwards-incompatibly.281282 - title: Basic filters283 entries:284 - title: "Identity: `.`"285 body: |286287 The absolute simplest filter is `.` . This is a filter that288 takes its input and produces it unchanged as output. That is,289 this is the identity operator.290291 Since jq by default pretty-prints all output, this trivial292 program can be a useful way of formatting JSON output from,293 say, `curl`.294295 examples:296 - program: '.'297 input: '"Hello, world!"'298 output: ['"Hello, world!"']299300 - title: "Object Identifier-Index: `.foo`, `.foo.bar`"301 body: |302303 The simplest *useful* filter is `.foo`. When given a304 JSON object (aka dictionary or hash) as input, it produces305 the value at the key "foo", or null if there's none present.306307 A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.308309 This syntax only works for simple, identifier-like keys, that310 is, keys that are all made of alphanumeric characters and311 underscore, and which do not start with a digit.312313 If the key contains special characters, you need to surround314 it with double quotes like this: `."foo$"`, or else `.["foo$"]`.315316 For example `.["foo::bar"]` and `.["foo.bar"]` work while317 `.foo::bar` does not, and `.foo.bar` means `.["foo"].["bar"]`.318319 examples:320 - program: '.foo'321 input: '{"foo": 42, "bar": "less interesting data"}'322 output: [42]323 - program: '.foo'324 input: '{"notfoo": true, "alsonotfoo": false}'325 output: ['null']326 - program: '.["foo"]'327 input: '{"foo": 42}'328 output: [42]329330 - title: "Optional Object Identifier-Index: `.foo?`"331 body: |332333 Just like `.foo`, but does not output even an error when `.`334 is not an array or an object.335336 examples:337 - program: '.foo?'338 input: '{"foo": 42, "bar": "less interesting data"}'339 output: [42]340 - program: '.foo?'341 input: '{"notfoo": true, "alsonotfoo": false}'342 output: ['null']343 - program: '.["foo"]?'344 input: '{"foo": 42}'345 output: [42]346 - program: '[.foo?]'347 input: '[1,2]'348 output: ['[]']349350 - title: "Generic Object Index: `.[<string>]`"351 body: |352353 You can also look up fields of an object using syntax like354 `.["foo"]` (.foo above is a shorthand version of this, but355 only for identifier-like strings).356357 - title: "Array Index: `.[2]`"358 body: |359360 When the index value is an integer, `.[<value>]` can index361 arrays. Arrays are zero-based, so `.[2]` returns the third362 element.363364 Negative indices are allowed, with -1 referring to the last365 element, -2 referring to the next to last element, and so on.366367 examples:368 - program: '.[0]'369 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'370 output: ['{"name":"JSON", "good":true}']371372 - program: '.[2]'373 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'374 output: ['null']375376 - program: '.[-2]'377 input: '[1,2,3]'378 output: ['2']379380 - title: "Array/String Slice: `.[10:15]`"381 body: |382383 The `.[10:15]` syntax can be used to return a subarray of an384 array or substring of a string. The array returned by385 `.[10:15]` will be of length 5, containing the elements from386 index 10 (inclusive) to index 15 (exclusive). Either index may387 be negative (in which case it counts backwards from the end of388 the array), or omitted (in which case it refers to the start389 or end of the array).390391 examples:392 - program: '.[2:4]'393 input: '["a","b","c","d","e"]'394 output: ['["c", "d"]']395396 - program: '.[2:4]'397 input: '"abcdefghi"'398 output: ['"cd"']399400 - program: '.[:3]'401 input: '["a","b","c","d","e"]'402 output: ['["a", "b", "c"]']403404 - program: '.[-2:]'405 input: '["a","b","c","d","e"]'406 output: ['["d", "e"]']407408 - title: "Array/Object Value Iterator: `.[]`"409 body: |410411 If you use the `.[index]` syntax, but omit the index412 entirely, it will return *all* of the elements of an413 array. Running `.[]` with the input `[1,2,3]` will produce the414 numbers as three separate results, rather than as a single415 array.416417 You can also use this on an object, and it will return all418 the values of the object.419420 examples:421 - program: '.[]'422 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'423 output:424 - '{"name":"JSON", "good":true}'425 - '{"name":"XML", "good":false}'426427 - program: '.[]'428 input: '[]'429 output: []430431 - program: '.[]'432 input: '{"a": 1, "b": 1}'433 output: ['1', '1']434435 - title: "`.[]?`"436 body: |437438 Like `.[]`, but no errors will be output if . is not an array439 or object.440441 - title: "Comma: `,`"442 body: |443444 If two filters are separated by a comma, then the445 same input will be fed into both and the two filters' output446 value streams will be concatenated in order: first, all of the447 outputs produced by the left expression, and then all of the448 outputs produced by the right. For instance, filter `.foo,449 .bar`, produces both the "foo" fields and "bar" fields as450 separate outputs.451452 examples:453 - program: '.foo, .bar'454 input: '{"foo": 42, "bar": "something else", "baz": true}'455 output: ['42', '"something else"']456457 - program: ".user, .projects[]"458 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'459 output: ['"stedolan"', '"jq"', '"wikiflow"']460461 - program: '.[4,2]'462 input: '["a","b","c","d","e"]'463 output: ['"e"', '"c"']464465 - title: "Pipe: `|`"466 body: |467468 The | operator combines two filters by feeding the output(s) of469 the one on the left into the input of the one on the right. It's470 pretty much the same as the Unix shell's pipe, if you're used to471 that.472473 If the one on the left produces multiple results, the one on474 the right will be run for each of those results. So, the475 expression `.[] | .foo` retrieves the "foo" field of each476 element of the input array.477478 Note that `.a.b.c` is the same as `.a | .b | .c`.479480 Note too that `.` is the input value at the particular stage481 in a "pipeline", specifically: where the `.` expression appears.482 Thus `.a | . | .b` is the same as `.a.b`, as the `.` in the483 middle refers to whatever value `.a` produced.484485 examples:486 - program: '.[] | .name'487 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'488 output: ['"JSON"', '"XML"']489490 - title: "Parenthesis"491 body: |492493 Parenthesis work as a grouping operator just as in any typical494 programming language.495496 examples:497 - program: '(. + 2) * 5'498 input: '1'499 output: [15]500501 - title: Types and Values502 body: |503504 jq supports the same set of datatypes as JSON - numbers,505 strings, booleans, arrays, objects (which in JSON-speak are506 hashes with only string keys), and "null".507508 Booleans, null, strings and numbers are written the same way as509 in javascript. Just like everything else in jq, these simple510 values take an input and produce an output - `42` is a valid jq511 expression that takes an input, ignores it, and returns 42512 instead.513514 entries:515 - title: "Array construction: `[]`"516 body: |517518 As in JSON, `[]` is used to construct arrays, as in519 `[1,2,3]`. The elements of the arrays can be any jq520 expression, including a pipeline. All of the results produced521 by all of the expressions are collected into one big array.522 You can use it to construct an array out of a known quantity523 of values (as in `[.foo, .bar, .baz]`) or to "collect" all the524 results of a filter into an array (as in `[.items[].name]`)525526 Once you understand the "," operator, you can look at jq's array527 syntax in a different light: the expression `[1,2,3]` is not using a528 built-in syntax for comma-separated arrays, but is instead applying529 the `[]` operator (collect results) to the expression 1,2,3 (which530 produces three different results).531532 If you have a filter `X` that produces four results,533 then the expression `[X]` will produce a single result, an534 array of four elements.535536 examples:537 - program: "[.user, .projects[]]"538 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'539 output: ['["stedolan", "jq", "wikiflow"]']540 - program: "[ .[] | . * 2]"541 input: '[1, 2, 3]'542 output: ['[2, 4, 6]']543544 - title: "Object Construction: `{}`"545 body: |546547 Like JSON, `{}` is for constructing objects (aka548 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.549550 If the keys are "identifier-like", then the quotes can be left551 off, as in `{a:42, b:17}`. Keys generated by expressions need552 to be parenthesized, e.g., `{("a"+"b"):59}`.553554 The value can be any expression (although you may need to555 wrap it in parentheses if it's a complicated one), which gets556 applied to the {} expression's input (remember, all filters557 have an input and an output).558559 {foo: .bar}560561 will produce the JSON object `{"foo": 42}` if given the JSON562 object `{"bar":42, "baz":43}` as its input. You can use this563 to select particular fields of an object: if the input is an564 object with "user", "title", "id", and "content" fields and565 you just want "user" and "title", you can write566567 {user: .user, title: .title}568569 Because that is so common, there's a shortcut syntax for it:570 `{user, title}`.571572 If one of the expressions produces multiple results,573 multiple dictionaries will be produced. If the input's574575 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}576577 then the expression578579 {user, title: .titles[]}580581 will produce two outputs:582583 {"user":"stedolan", "title": "JQ Primer"}584 {"user":"stedolan", "title": "More JQ"}585586 Putting parentheses around the key means it will be evaluated as an587 expression. With the same input as above,588589 {(.user): .titles}590591 produces592593 {"stedolan": ["JQ Primer", "More JQ"]}594595 examples:596 - program: '{user, title: .titles[]}'597 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'598 output:599 - '{"user":"stedolan", "title": "JQ Primer"}'600 - '{"user":"stedolan", "title": "More JQ"}'601 - program: '{(.user): .titles}'602 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'603 output: ['{"stedolan": ["JQ Primer", "More JQ"]}']604605 - title: "Recursive Descent: `..`"606 body: |607608 Recursively descends `.`, producing every value. This is the609 same as the zero-argument `recurse` builtin (see below). This610 is intended to resemble the XPath `//` operator. Note that611 `..a` does not work; use `..|.a` instead. In the example612 below we use `..|.a?` to find all the values of object keys613 "a" in any object found "below" `.`.614615 This is particularly useful in conjunction with `path(EXP)`616 (also see below) and the `?` operator.617618 examples:619 - program: '..|.a?'620 input: '[[{"a":1}]]'621 output: ['1']622623 - title: Builtin operators and functions624 body: |625626 Some jq operator (for instance, `+`) do different things627 depending on the type of their arguments (arrays, numbers,628 etc.). However, jq never does implicit type conversions. If you629 try to add a string to an object you'll get an error message and630 no result.631632 entries:633 - title: "Addition: `+`"634 body: |635636 The operator `+` takes two filters, applies them both637 to the same input, and adds the results together. What638 "adding" means depends on the types involved:639640 - **Numbers** are added by normal arithmetic.641642 - **Arrays** are added by being concatenated into a larger array.643644 - **Strings** are added by being joined into a larger string.645646 - **Objects** are added by merging, that is, inserting all647 the key-value pairs from both objects into a single648 combined object. If both objects contain a value for the649 same key, the object on the right of the `+` wins. (For650 recursive merge use the `*` operator.)651652 `null` can be added to any value, and returns the other653 value unchanged.654655 examples:656 - program: '.a + 1'657 input: '{"a": 7}'658 output: ['8']659 - program: '.a + .b'660 input: '{"a": [1,2], "b": [3,4]}'661 output: ['[1,2,3,4]']662 - program: '.a + null'663 input: '{"a": 1}'664 output: ['1']665 - program: '.a + 1'666 input: '{}'667 output: ['1']668 - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'669 input: 'null'670 output: ['{"a": 42, "b": 2, "c": 3}']671672 - title: "Subtraction: `-`"673 body: |674675 As well as normal arithmetic subtraction on numbers, the `-`676 operator can be used on arrays to remove all occurrences of677 the second array's elements from the first array.678679 examples:680 - program: '4 - .a'681 input: '{"a":3}'682 output: ['1']683 - program: . - ["xml", "yaml"]684 input: '["xml", "yaml", "json"]'685 output: ['["json"]']686687 - title: "Multiplication, division, modulo: `*`, `/`, and `%`"688 body: |689690 These infix operators behave as expected when given two numbers.691 Division by zero raises an error. `x % y` computes x modulo y.692693 Multiplying a string by a number produces the concatenation of694 that string that many times. `"x" * 0` produces **null**.695696 Dividing a string by another splits the first using the second697 as separators.698699 Multiplying two objects will merge them recursively: this works700 like addition but if both objects contain a value for the701 same key, and the values are objects, the two are merged with702 the same strategy.703704 examples:705 - program: '10 / . * 3'706 input: 5707 output: [6]708 - program: '. / ", "'709 input: '"a, b,c,d, e"'710 output: ['["a","b,c,d","e"]']711 - program: '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'712 input: 'null'713 output: ['{"k": {"a": 0, "b": 2, "c": 3}}']714 - program: '.[] | (1 / .)?'715 input: '[1,0,-1]'716 output: ['1', '-1']717718719 - title: "`length`"720 body: |721722 The builtin function `length` gets the length of various723 different types of value:724725 - The length of a **string** is the number of Unicode726 codepoints it contains (which will be the same as its727 JSON-encoded length in bytes if it's pure ASCII).728729 - The length of an **array** is the number of elements.730731 - The length of an **object** is the number of key-value pairs.732733 - The length of **null** is zero.734735 examples:736 - program: '.[] | length'737 input: '[[1,2], "string", {"a":2}, null]'738 output: [2, 6, 1, 0]739740741 - title: "`utf8bytelength`"742 body: |743744 The builtin function `utf8bytelength` outputs the number of745 bytes used to encode a string in UTF-8.746747 examples:748 - program: 'utf8bytelength'749 input: '"\u03bc"'750 output: [2]751752 - title: "`keys`, `keys_unsorted`"753 body: |754755 The builtin function `keys`, when given an object, returns756 its keys in an array.757758 The keys are sorted "alphabetically", by unicode codepoint759 order. This is not an order that makes particular sense in760 any particular language, but you can count on it being the761 same for any two objects with the same set of keys,762 regardless of locale settings.763764 When `keys` is given an array, it returns the valid indices765 for that array: the integers from 0 to length-1.766767 The `keys_unsorted` function is just like `keys`, but if768 the input is an object then the keys will not be sorted,769 instead the keys will roughly be in insertion order.770771 examples:772 - program: 'keys'773 input: '{"abc": 1, "abcd": 2, "Foo": 3}'774 output: ['["Foo", "abc", "abcd"]']775 - program: 'keys'776 input: '[42,3,35]'777 output: ['[0,1,2]']778779 - title: "`has(key)`"780 body: |781782 The builtin function `has` returns whether the input object783 has the given key, or the input array has an element at the784 given index.785786 `has($key)` has the same effect as checking whether `$key`787 is a member of the array returned by `keys`, although `has`788 will be faster.789790 examples:791 - program: 'map(has("foo"))'792 input: '[{"foo": 42}, {}]'793 output: ['[true, false]']794 - program: 'map(has(2))'795 input: '[[0,1], ["a","b","c"]]'796 output: ['[false, true]']797798 - title: "`in`"799 body: |800801 The builtin function `in` returns whether or not the input key is in the802 given object, or the input index corresponds to an element803 in the given array. It is, essentially, an inversed version804 of `has`.805806 examples:807 - program: '.[] | in({"foo": 42})'808 input: '["foo", "bar"]'809 output: ['true', 'false']810 - program: 'map(in([0,1]))'811 input: '[2, 0]'812 output: ['[false, true]']813814 - title: "`map(x)`, `map_values(x)`"815 body: |816817 For any filter `x`, `map(x)` will run that filter for each818 element of the input array, and return the outputs in a new819 array. `map(.+1)` will increment each element of an array of numbers.820821 Similarly, `map_values(x)` will run that filter for each element,822 but it will return an object when an object is passed.823824 `map(x)` is equivalent to `[.[] | x]`. In fact, this is how825 it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`.826827 examples:828 - program: 'map(.+1)'829 input: '[1,2,3]'830 output: ['[2,3,4]']831832 - program: 'map_values(.+1)'833 input: '{"a": 1, "b": 2, "c": 3}'834 output: ['{"a": 2, "b": 3, "c": 4}']835836 - title: "`path(path_expression)`"837 body: |838839 Outputs array representations of the given path expression840 in `.`. The outputs are arrays of strings (object keys)841 and/or numbers (array indices).842843 Path expressions are jq expressions like `.a`, but also `.[]`.844 There are two types of path expressions: ones that can match845 exactly, and ones that cannot. For example, `.a.b.c` is an846 exact match path expression, while `.a[].b` is not.847848 `path(exact_path_expression)` will produce the array849 representation of the path expression even if it does not850 exist in `.`, if `.` is `null` or an array or an object.851852 `path(pattern)` will produce array representations of the853 paths matching `pattern` if the paths exist in `.`.854855 Note that the path expressions are not different from normal856 expressions. The expression857 `path(..|select(type=="boolean"))` outputs all the paths to858 boolean values in `.`, and only those paths.859860 examples:861 - program: 'path(.a[0].b)'862 input: 'null'863 output: ['["a",0,"b"]']864 - program: '[path(..)]'865 input: '{"a":[{"b":1}]}'866 output: ['[[],["a"],["a",0],["a",0,"b"]]']867868 - title: "`del(path_expression)`"869 body: |870871 The builtin function `del` removes a key and its corresponding872 value from an object.873874 examples:875 - program: 'del(.foo)'876 input: '{"foo": 42, "bar": 9001, "baz": 42}'877 output: ['{"bar": 9001, "baz": 42}']878 - program: 'del(.[1, 2])'879 input: '["foo", "bar", "baz"]'880 output: ['["foo"]']881882 - title: "`getpath(PATHS)`"883 body: |884885 The builtin function `getpath` outputs the values in `.` found886 at each path in `PATHS`.887888 examples:889 - program: 'getpath(["a","b"])'890 input: 'null'891 output: ['null']892 - program: '[getpath(["a","b"], ["a","c"])]'893 input: '{"a":{"b":0, "c":1}}'894 output: ['[0, 1]']895896 - title: "`setpath(PATHS; VALUE)`"897 body: |898899 The builtin function `setpath` sets the `PATHS` in `.` to `VALUE`.900901 examples:902 - program: 'setpath(["a","b"]; 1)'903 input: 'null'904 output: ['{"a": {"b": 1}}']905 - program: 'setpath(["a","b"]; 1)'906 input: '{"a":{"b":0}}'907 output: ['{"a": {"b": 1}}']908 - program: 'setpath([0,"a"]; 1)'909 input: 'null'910 output: ['[{"a":1}]']911912 - title: "`delpaths(PATHS)`"913 body: |914915 The builtin function `delpaths` sets the `PATHS` in `.`.916 `PATHS` must be an array of paths, where each path is an array917 of strings and numbers.918919 examples:920 - program: 'delpaths([["a","b"]])'921 input: '{"a":{"b":1},"x":{"y":2}}'922 output: ['{"a":{},"x":{"y":2}}']923924 - title: "`to_entries`, `from_entries`, `with_entries`"925 body: |926927 These functions convert between an object and an array of928 key-value pairs. If `to_entries` is passed an object, then929 for each `k: v` entry in the input, the output array930 includes `{"key": k, "value": v}`.931932 `from_entries` does the opposite conversion, and933 `with_entries(foo)` is a shorthand for `to_entries |934 map(foo) | from_entries`, useful for doing some operation to935 all keys and values of an object. `from_entries` accepts key, Key,936 name, Name, value and Value as keys.937938 examples:939 - program: 'to_entries'940 input: '{"a": 1, "b": 2}'941 output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']942 - program: 'from_entries'943 input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'944 output: ['{"a": 1, "b": 2}']945 - program: 'with_entries(.key |= "KEY_" + .)'946 input: '{"a": 1, "b": 2}'947 output: ['{"KEY_a": 1, "KEY_b": 2}']948949950 - title: "`select(boolean_expression)`"951 body: |952953 The function `select(foo)` produces its input unchanged if954 `foo` returns true for that input, and produces no output955 otherwise.956957 It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`958 will give you `[2,3]`.959960 examples:961 - program: 'map(select(. >= 2))'962 input: '[1,5,3,0,7]'963 output: ['[5,3,7]']964 - program: '.[] | select(.id == "second")'965 input: '[{"id": "first", "val": 1}, {"id": "second", "val": 2}]'966 output: ['{"id": "second", "val": 2}']967968969 - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"970 body: |971972 These built-ins select only inputs that are arrays, objects,973 iterables (arrays or objects), booleans, numbers, normal974 numbers, finite numbers, strings, null, non-null values, and975 non-iterables, respectively.976977 examples:978 - program: '.[]|numbers'979 input: '[[],{},1,"foo",null,true,false]'980 output: ['1']981982 - title: "`empty`"983 body: |984985 `empty` returns no results. None at all. Not even `null`.986987 It's useful on occasion. You'll know if you need it :)988989 examples:990 - program: '1, empty, 2'991 input: 'null'992 output: [1, 2]993 - program: '[1,2,empty,3]'994 input: 'null'995 output: ['[1,2,3]']996997 - title: "`error(message)`"998 body: |9991000 Produces an error, just like `.a` applied to values other than1001 null and objects would, but with the given message as the1002 error's value. Errors can be caught with try/catch; see below.10031004 - title: "`halt`"1005 body: |10061007 Stops the jq program with no further outputs. jq will exit1008 with exit status `0`.10091010 - title: "`halt_error`, `halt_error(exit_code)`"1011 body: |10121013 Stops the jq program with no further outputs. The input will1014 be printed on `stderr` as raw output (i.e., strings will not1015 have double quotes) with no decoration, not even a newline.10161017 The given `exit_code` (defaulting to `5`) will be jq's exit1018 status.10191020 For example, `"Error: somthing went wrong\n"|halt_error(1)`.10211022 - title: "`$__loc__`"1023 body: |10241025 Produces an object with a "file" key and a "line" key, with1026 the filename and line number where `$__loc__` occurs, as1027 values.10281029 examples:1030 - program: 'try error("\($__loc__)") catch .'1031 input: 'null'1032 output: ['"{\"file\":\"<top-level>\",\"line\":1}"']10331034 - title: "`paths`, `paths(node_filter)`, `leaf_paths`"1035 body: |10361037 `paths` outputs the paths to all the elements in its input1038 (except it does not output the empty list, representing .1039 itself).10401041 `paths(f)` outputs the paths to any values for which `f` is true.1042 That is, `paths(numbers)` outputs the paths to all numeric1043 values.10441045 `leaf_paths` is an alias of `paths(scalars)`; `leaf_paths` is1046 *deprecated* and will be removed in the next major release.10471048 examples:1049 - program: '[paths]'1050 input: '[1,[[],{"a":2}]]'1051 output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']1052 - program: '[paths(scalars)]'1053 input: '[1,[[],{"a":2}]]'1054 output: ['[[0],[1,1,"a"]]']10551056 - title: "`add`"1057 body: |10581059 The filter `add` takes as input an array, and produces as1060 output the elements of the array added together. This might1061 mean summed, concatenated or merged depending on the types1062 of the elements of the input array - the rules are the same1063 as those for the `+` operator (described above).10641065 If the input is an empty array, `add` returns `null`.10661067 examples:1068 - program: add1069 input: '["a","b","c"]'1070 output: ['"abc"']1071 - program: add1072 input: '[1, 2, 3]'1073 output: [6]1074 - program: add1075 input: '[]'1076 output: ["null"]10771078 - title: "`any`, `any(condition)`, `any(generator; condition)`"1079 body: |10801081 The filter `any` takes as input an array of boolean values,1082 and produces `true` as output if any of the elements of1083 the array are `true`.10841085 If the input is an empty array, `any` returns `false`.10861087 The `any(condition)` form applies the given condition to the1088 elements of the input array.10891090 The `any(generator; condition)` form applies the given1091 condition to all the outputs of the given generator.10921093 examples:1094 - program: any1095 input: '[true, false]'1096 output: ["true"]1097 - program: any1098 input: '[false, false]'1099 output: ["false"]1100 - program: any1101 input: '[]'1102 output: ["false"]11031104 - title: "`all`, `all(condition)`, `all(generator; condition)`"1105 body: |11061107 The filter `all` takes as input an array of boolean values,1108 and produces `true` as output if all of the elements of1109 the array are `true`.11101111 The `all(condition)` form applies the given condition to the1112 elements of the input array.11131114 The `all(generator; condition)` form applies the given1115 condition to all the outputs of the given generator.11161117 If the input is an empty array, `all` returns `true`.11181119 examples:1120 - program: all1121 input: '[true, false]'1122 output: ["false"]1123 - program: all1124 input: '[true, true]'1125 output: ["true"]1126 - program: all1127 input: '[]'1128 output: ["true"]11291130 - title: "`flatten`, `flatten(depth)`"1131 body: |11321133 The filter `flatten` takes as input an array of nested arrays,1134 and produces a flat array in which all arrays inside the original1135 array have been recursively replaced by their values. You can pass1136 an argument to it to specify how many levels of nesting to flatten.11371138 `flatten(2)` is like `flatten`, but going only up to two1139 levels deep.11401141 examples:1142 - program: flatten1143 input: '[1, [2], [[3]]]'1144 output: ["[1, 2, 3]"]1145 - program: flatten(1)1146 input: '[1, [2], [[3]]]'1147 output: ["[1, 2, [3]]"]1148 - program: flatten1149 input: '[[]]'1150 output: ["[]"]1151 - program: flatten1152 input: '[{"foo": "bar"}, [{"foo": "baz"}]]'1153 output: ['[{"foo": "bar"}, {"foo": "baz"}]']11541155 - title: "`range(upto)`, `range(from;upto)` `range(from;upto;by)`"1156 body: |11571158 The `range` function produces a range of numbers. `range(4;10)`1159 produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers1160 are produced as separate outputs. Use `[range(4;10)]` to get a range as1161 an array.11621163 The one argument form generates numbers from 0 to the given1164 number, with an increment of 1.11651166 The two argument form generates numbers from `from` to `upto`1167 with an increment of 1.11681169 The three argument form generates numbers `from` to `upto`1170 with an increment of `by`.11711172 examples:1173 - program: 'range(2;4)'1174 input: 'null'1175 output: ['2', '3']1176 - program: '[range(2;4)]'1177 input: 'null'1178 output: ['[2,3]']1179 - program: '[range(4)]'1180 input: 'null'1181 output: ['[0,1,2,3]']1182 - program: '[range(0;10;3)]'1183 input: 'null'1184 output: ['[0,3,6,9]']1185 - program: '[range(0;10;-1)]'1186 input: 'null'1187 output: ['[]']1188 - program: '[range(0;-5;-1)]'1189 input: 'null'1190 output: ['[0,-1,-2,-3,-4]']11911192 - title: "`floor`"1193 body: |11941195 The `floor` function returns the floor of its numeric input.11961197 examples:1198 - program: 'floor'1199 input: '3.14159'1200 output: ['3']12011202 - title: "`sqrt`"1203 body: |12041205 The `sqrt` function returns the square root of its numeric input.12061207 examples:1208 - program: 'sqrt'1209 input: '9'1210 output: ['3']12111212 - title: "`tonumber`"1213 body: |12141215 The `tonumber` function parses its input as a number. It1216 will convert correctly-formatted strings to their numeric1217 equivalent, leave numbers alone, and give an error on all other input.12181219 examples:1220 - program: '.[] | tonumber'1221 input: '[1, "1"]'1222 output: [1, 1]12231224 - title: "`tostring`"1225 body: |12261227 The `tostring` function prints its input as a1228 string. Strings are left unchanged, and all other values are1229 JSON-encoded.12301231 examples:1232 - program: '.[] | tostring'1233 input: '[1, "1", [1]]'1234 output: ['"1"', '"1"', '"[1]"']12351236 - title: "`type`"1237 body: |12381239 The `type` function returns the type of its argument as a1240 string, which is one of null, boolean, number, string, array1241 or object.12421243 examples:1244 - program: 'map(type)'1245 input: '[0, false, [], {}, null, "hello"]'1246 output: ['["number", "boolean", "array", "object", "null", "string"]']12471248 - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1249 body: |12501251 Some arithmetic operations can yield infinities and "not a1252 number" (NaN) values. The `isinfinite` builtin returns `true`1253 if its input is infinite. The `isnan` builtin returns `true`1254 if its input is a NaN. The `infinite` builtin returns a1255 positive infinite value. The `nan` builtin returns a NaN.1256 The `isnormal` builtin returns true if its input is a normal1257 number.12581259 Note that division by zero raises an error.12601261 Currently most arithmetic operations operating on infinities,1262 NaNs, and sub-normals do not raise errors.12631264 examples:1265 - program: '.[] | (infinite * .) < 0'1266 input: '[-1, 1]'1267 output: ['true', 'false']1268 - program: 'infinite, nan | type'1269 input: 'null'1270 output: ['"number"', '"number"']12711272 - title: "`sort, sort_by(path_expression)`"1273 body: |12741275 The `sort` functions sorts its input, which must be an1276 array. Values are sorted in the following order:12771278 * `null`1279 * `false`1280 * `true`1281 * numbers1282 * strings, in alphabetical order (by unicode codepoint value)1283 * arrays, in lexical order1284 * objects12851286 The ordering for objects is a little complex: first they're1287 compared by comparing their sets of keys (as arrays in1288 sorted order), and if their keys are equal then the values1289 are compared key by key.12901291 `sort` may be used to sort by a particular field of an1292 object, or by applying any jq filter.12931294 `sort_by(foo)` compares two elements by comparing the result of1295 `foo` on each element.12961297 examples:1298 - program: 'sort'1299 input: '[8,3,null,6]'1300 output: ['[null,3,6,8]']1301 - program: 'sort_by(.foo)'1302 input: '[{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}]'1303 output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']13041305 - title: "`group_by(path_expression)`"1306 body: |13071308 `group_by(.foo)` takes as input an array, groups the1309 elements having the same `.foo` field into separate arrays,1310 and produces all of these arrays as elements of a larger1311 array, sorted by the value of the `.foo` field.13121313 Any jq expression, not just a field access, may be used in1314 place of `.foo`. The sorting order is the same as described1315 in the `sort` function above.13161317 examples:1318 - program: 'group_by(.foo)'1319 input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'1320 output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']13211322 - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1323 body: |13241325 Find the minimum or maximum element of the input array.13261327 The `min_by(path_exp)` and `max_by(path_exp)` functions allow1328 you to specify a particular field or property to examine, e.g.1329 `min_by(.foo)` finds the object with the smallest `foo` field.13301331 examples:1332 - program: 'min'1333 input: '[5,4,2,7]'1334 output: ['2']1335 - program: 'max_by(.foo)'1336 input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'1337 output: ['{"foo":2, "bar":3}']13381339 - title: "`unique`, `unique_by(path_exp)`"1340 body: |13411342 The `unique` function takes as input an array and produces1343 an array of the same elements, in sorted order, with1344 duplicates removed.13451346 The `unique_by(path_exp)` function will keep only one element1347 for each value obtained by applying the argument. Think of it1348 as making an array by taking one element out of every group1349 produced by `group`.13501351 examples:1352 - program: 'unique'1353 input: '[1,2,5,3,5,3,1,3]'1354 output: ['[1,2,3,5]']1355 - program: 'unique_by(.foo)'1356 input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'1357 output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']1358 - program: 'unique_by(length)'1359 input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'1360 output: ['["bacon", "chunky", "asparagus"]']13611362 - title: "`reverse`"1363 body: |13641365 This function reverses an array.13661367 examples:1368 - program: 'reverse'1369 input: '[1,2,3,4]'1370 output: ['[4,3,2,1]']13711372 - title: "`contains(element)`"1373 body: |13741375 The filter `contains(b)` will produce true if b is1376 completely contained within the input. A string B is1377 contained in a string A if B is a substring of A. An array B1378 is contained in an array A if all elements in B are1379 contained in any element in A. An object B is contained in1380 object A if all of the values in B are contained in the1381 value in A with the same key. All other types are assumed to1382 be contained in each other if they are equal.13831384 examples:1385 - program: 'contains("bar")'1386 input: '"foobar"'1387 output: ['true']1388 - program: 'contains(["baz", "bar"])'1389 input: '["foobar", "foobaz", "blarp"]'1390 output: ['true']1391 - program: 'contains(["bazzzzz", "bar"])'1392 input: '["foobar", "foobaz", "blarp"]'1393 output: ['false']1394 - program: 'contains({foo: 12, bar: [{barp: 12}]})'1395 input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1396 output: ['true']1397 - program: 'contains({foo: 12, bar: [{barp: 15}]})'1398 input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1399 output: ['false']14001401 - title: "`indices(s)`"1402 body: |14031404 Outputs an array containing the indices in `.` where `s`1405 occurs. The input may be an array, in which case if `s` is an1406 array then the indices output will be those where all elements1407 in `.` match those of `s`.14081409 examples:1410 - program: 'indices(", ")'1411 input: '"a,b, cd, efg, hijk"'1412 output: ['[3,7,12]']1413 - program: 'indices(1)'1414 input: '[0,1,2,1,3,1,4]'1415 output: ['[1,3,5]']1416 - program: 'indices([1,2])'1417 input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1418 output: ['[1,8]']14191420 - title: "`index(s)`, `rindex(s)`"1421 body: |14221423 Outputs the index of the first (`index`) or last (`rindex`)1424 occurrence of `s` in the input.14251426 examples:1427 - program: 'index(", ")'1428 input: '"a,b, cd, efg, hijk"'1429 output: ['3']1430 - program: 'rindex(", ")'1431 input: '"a,b, cd, efg, hijk"'1432 output: ['12']14331434 - title: "`inside`"1435 body: |14361437 The filter `inside(b)` will produce true if the input is1438 completely contained within b. It is, essentially, an1439 inversed version of `contains`.14401441 examples:1442 - program: 'inside("foobar")'1443 input: '"bar"'1444 output: ['true']1445 - program: 'inside(["foobar", "foobaz", "blarp"])'1446 input: '["baz", "bar"]'1447 output: ['true']1448 - program: 'inside(["foobar", "foobaz", "blarp"])'1449 input: '["bazzzzz", "bar"]'1450 output: ['false']1451 - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1452 input: '{"foo": 12, "bar": [{"barp": 12}]}'1453 output: ['true']1454 - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1455 input: '{"foo": 12, "bar": [{"barp": 15}]}'1456 output: ['false']14571458 - title: "`startswith(str)`"1459 body: |14601461 Outputs `true` if . starts with the given string argument.14621463 examples:1464 - program: '[.[]|startswith("foo")]'1465 input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1466 output: ['[false, true, false, true, false]']14671468 - title: "`endswith(str)`"1469 body: |14701471 Outputs `true` if . ends with the given string argument.14721473 examples:1474 - program: '[.[]|endswith("foo")]'1475 input: '["foobar", "barfoo"]'1476 output: ['[false, true]']14771478 - title: "`combinations`, `combinations(n)`"1479 body: |14801481 Outputs all combinations of the elements of the arrays in the1482 input array. If given an argument `n`, it outputs all combinations1483 of `n` repetitions of the input array.14841485 examples:1486 - program: 'combinations'1487 input: '[[1,2], [3, 4]]'1488 output: ['[1, 3]', '[1, 4]', '[2, 3]', '[2, 4]']1489 - program: 'combinations(2)'1490 input: '[0, 1]'1491 output: ['[0, 0]', '[0, 1]', '[1, 0]', '[1, 1]']14921493 - title: "`ltrimstr(str)`"1494 body: |14951496 Outputs its input with the given prefix string removed, if it1497 starts with it.14981499 examples:1500 - program: '[.[]|ltrimstr("foo")]'1501 input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1502 output: ['["fo","","barfoo","bar","afoo"]']15031504 - title: "`rtrimstr(str)`"1505 body: |15061507 Outputs its input with the given suffix string removed, if it1508 ends with it.15091510 examples:1511 - program: '[.[]|rtrimstr("foo")]'1512 input: '["fo", "foo", "barfoo", "foobar", "foob"]'1513 output: ['["fo","","bar","foobar","foob"]']15141515 - title: "`explode`"1516 body: |15171518 Converts an input string into an array of the string's1519 codepoint numbers.15201521 examples:1522 - program: 'explode'1523 input: '"foobar"'1524 output: ['[102,111,111,98,97,114]']15251526 - title: "`implode`"1527 body: |15281529 The inverse of explode.15301531 examples:1532 - program: 'implode'1533 input: '[65, 66, 67]'1534 output: ['"ABC"']15351536 - title: "`split(str)`"1537 body: |15381539 Splits an input string on the separator argument.15401541 examples:1542 - program: 'split(", ")'1543 input: '"a, b,c,d, e, "'1544 output: ['["a","b,c,d","e",""]']15451546 - title: "`join(str)`"1547 body: |15481549 Joins the array of elements given as input, using the1550 argument as separator. It is the inverse of `split`: that is,1551 running `split("foo") | join("foo")` over any input string1552 returns said input string.15531554 Numbers and booleans in the input are converted to strings.1555 Null values are treated as empty strings. Arrays and objects1556 in the input are not supported.15571558 examples:1559 - program: 'join(", ")'1560 input: '["a","b,c,d","e"]'1561 output: ['"a, b,c,d, e"']1562 - program: 'join(" ")'1563 input: '["a",1,2.3,true,null,false]'1564 output: ['"a 1 2.3 true false"']15651566 - title: "`ascii_downcase`, `ascii_upcase`"1567 body: |15681569 Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1570 converted to the specified case.15711572 example:1573 - program: 'ascii_upcase'1574 input: '"useful but not for é"'1575 output: '"USEFUL BUT NOT FOR é"'15761577 - title: "`while(cond; update)`"1578 body: |15791580 The `while(cond; update)` function allows you to repeatedly1581 apply an update to `.` until `cond` is false.15821583 Note that `while(cond; update)` is internally defined as a1584 recursive jq function. Recursive calls within `while` will1585 not consume additional memory if `update` produces at most one1586 output for each input. See advanced topics below.15871588 examples:1589 - program: '[while(.<100; .*2)]'1590 input: '1'1591 output: ['[1,2,4,8,16,32,64]']15921593 - title: "`until(cond; next)`"1594 body: |15951596 The `until(cond; next)` function allows you to repeatedly1597 apply the expression `next`, initially to `.` then to its own1598 output, until `cond` is true. For example, this can be used1599 to implement a factorial function (see below).16001601 Note that `until(cond; next)` is internally defined as a1602 recursive jq function. Recursive calls within `until()` will1603 not consume additional memory if `next` produces at most one1604 output for each input. See advanced topics below.16051606 examples:1607 - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1608 input: '4'1609 output: ['24']161016111612 - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`, `recurse_down`"1613 body: |16141615 The `recurse(f)` function allows you to search through a1616 recursive structure, and extract interesting data from all1617 levels. Suppose your input represents a filesystem:16181619 {"name": "/", "children": [1620 {"name": "/bin", "children": [1621 {"name": "/bin/ls", "children": []},1622 {"name": "/bin/sh", "children": []}]},1623 {"name": "/home", "children": [1624 {"name": "/home/stephen", "children": [1625 {"name": "/home/stephen/jq", "children": []}]}]}]}16261627 Now suppose you want to extract all of the filenames1628 present. You need to retrieve `.name`, `.children[].name`,1629 `.children[].children[].name`, and so on. You can do this1630 with:16311632 recurse(.children[]) | .name16331634 When called without an argument, `recurse` is equivalent to1635 `recurse(.[]?)`.16361637 `recurse(f)` is identical to `recurse(f; . != null)` and can be1638 used without concerns about recursion depth.16391640 `recurse(f; condition)` is a generator which begins by1641 emitting . and then emits in turn .|f, .|f|f, .|f|f|f, ... so long1642 as the computed value satisfies the condition. For example,1643 to generate all the integers, at least in principle, one1644 could write `recurse(.+1; true)`.16451646 For legacy reasons, `recurse_down` exists as an alias to1647 calling `recurse` without arguments. This alias is considered1648 *deprecated* and will be removed in the next major release.16491650 The recursive calls in `recurse` will not consume additional1651 memory whenever `f` produces at most a single output for each1652 input.16531654 examples:1655 - program: 'recurse(.foo[])'1656 input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'1657 output:1658 - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'1659 - '{"foo":[]}'1660 - '{"foo":[{"foo":[]}]}'1661 - '{"foo":[]}'16621663 - program: 'recurse'1664 input: '{"a":0,"b":[1]}'1665 output:1666 - '{"a":0,"b":[1]}'1667 - '0'1668 - '[1]'1669 - '1'16701671 - program: 'recurse(. * .; . < 20)'1672 input: 21673 output:1674 - 21675 - 41676 - 1616771678 - title: "`walk(f)`"1679 body: |16801681 The `walk(f)` function applies f recursively to every1682 component of the input entity. When an array is1683 encountered, f is first applied to its elements and then to1684 the array itself; when an object is encountered, f is first1685 applied to all the values and then to the object. In1686 practice, f will usually test the type of its input, as1687 illustrated in the following examples. The first example1688 highlights the usefulness of processing the elements of an1689 array of arrays before processing the array itself. The second1690 example shows how all the keys of all the objects within the1691 input can be considered for alteration.16921693 examples:1694 - program: 'walk(if type == "array" then sort else . end)'1695 input: '[[4, 1, 7], [8, 5, 2], [3, 6, 9]]'1696 output:1697 - '[[1,4,7],[2,5,8],[3,6,9]]'16981699 - program: 'walk( if type == "object" then with_entries( .key |= sub( "^_+"; "") ) else . end )'1700 input: '[ { "_a": { "__b": 2 } } ]'1701 output:1702 - '[{"a":{"b":2}}]'17031704 - title: "`$ENV`, `env`"1705 body: |17061707 `$ENV` is an object representing the environment variables as1708 set when the jq program started.17091710 `env` outputs an object representing jq's current environment.17111712 At the moment there is no builtin for setting environment1713 variables.17141715 examples:1716 - program: '$ENV.PAGER'1717 input: 'null'1718 output: ['"less"']17191720 - program: 'env.PAGER'1721 input: 'null'1722 output: ['"less"']17231724 - title: "`transpose`"1725 body: |17261727 Transpose a possibly jagged matrix (an array of arrays).1728 Rows are padded with nulls so the result is always rectangular.17291730 examples:1731 - program: 'transpose'1732 input: '[[1], [2,3]]'1733 output: ['[[1,2],[null,3]]']17341735 - title: "`bsearch(x)`"1736 body: |17371738 bsearch(x) conducts a binary search for x in the input1739 array. If the input is sorted and contains x, then1740 bsearch(x) will return its index in the array; otherwise, if1741 the array is sorted, it will return (-1 - ix) where ix is an1742 insertion point such that the array would still be sorted1743 after the insertion of x at ix. If the array is not sorted,1744 bsearch(x) will return an integer that is probably of no1745 interest.17461747 examples:1748 - program: 'bsearch(0)'1749 input: '[0,1]'1750 output: ['0']1751 - program: 'bsearch(0)'1752 input: '[1,2,3]'1753 output: ['-1']1754 - program: 'bsearch(4) as $ix | if $ix < 0 then .[-(1+$ix)] = 4 else . end'1755 input: '[1,2,3]'1756 output: ['[1,2,3,4]']17571758 - title: "String interpolation - `\\(foo)`"1759 body: |17601761 Inside a string, you can put an expression inside parens1762 after a backslash. Whatever the expression returns will be1763 interpolated into the string.17641765 examples:1766 - program: '"The input was \(.), which is one less than \(.+1)"'1767 input: '42'1768 output: ['"The input was 42, which is one less than 43"']17691770 - title: "Convert to/from JSON"1771 body: |17721773 The `tojson` and `fromjson` builtins dump values as JSON texts1774 or parse JSON texts into values, respectively. The tojson1775 builtin differs from tostring in that tostring returns strings1776 unmodified, while tojson encodes strings as JSON strings.17771778 examples:1779 - program: '[.[]|tostring]'1780 input: '[1, "foo", ["foo"]]'1781 output: ['["1","foo","[\"foo\"]"]']1782 - program: '[.[]|tojson]'1783 input: '[1, "foo", ["foo"]]'1784 output: ['["1","\"foo\"","[\"foo\"]"]']1785 - program: '[.[]|tojson|fromjson]'1786 input: '[1, "foo", ["foo"]]'1787 output: ['[1,"foo",["foo"]]']17881789 - title: "Format strings and escaping"1790 body: |17911792 The `@foo` syntax is used to format and escape strings,1793 which is useful for building URLs, documents in a language1794 like HTML or XML, and so forth. `@foo` can be used as a1795 filter on its own, the possible escapings are:17961797 * `@text`:17981799 Calls `tostring`, see that function for details.18001801 * `@json`:18021803 Serializes the input as JSON.18041805 * `@html`:18061807 Applies HTML/XML escaping, by mapping the characters1808 `<>&'"` to their entity equivalents `&lt;`, `&gt;`,1809 `&amp;`, `&apos;`, `&quot;`.18101811 * `@uri`:18121813 Applies percent-encoding, by mapping all reserved URI1814 characters to a `%XX` sequence.18151816 * `@csv`:18171818 The input must be an array, and it is rendered as CSV1819 with double quotes for strings, and quotes escaped by1820 repetition.18211822 * `@tsv`:18231824 The input must be an array, and it is rendered as TSV1825 (tab-separated values). Each input array will be printed as1826 a single line. Fields are separated by a single1827 tab (ascii `0x09`). Input characters line-feed (ascii `0x0a`),1828 carriage-return (ascii `0x0d`), tab (ascii `0x09`) and1829 backslash (ascii `0x5c`) will be output as escape sequences1830 `\n`, `\r`, `\t`, `\\` respectively.18311832 * `@sh`:18331834 The input is escaped suitable for use in a command-line1835 for a POSIX shell. If the input is an array, the output1836 will be a series of space-separated strings.18371838 * `@base64`:18391840 The input is converted to base64 as specified by RFC 4648.18411842 * `@base64d`:18431844 The inverse of `@base64`, input is decoded as specified by RFC 4648.1845 Note\: If the decoded string is not UTF-8, the results are undefined.18461847 This syntax can be combined with string interpolation in a1848 useful way. You can follow a `@foo` token with a string1849 literal. The contents of the string literal will *not* be1850 escaped. However, all interpolations made inside that string1851 literal will be escaped. For instance,18521853 @uri "https://www.google.com/search?q=\(.search)"18541855 will produce the following output for the input1856 `{"search":"what is jq?"}`:18571858 "https://www.google.com/search?q=what%20is%20jq%3F"18591860 Note that the slashes, question mark, etc. in the URL are1861 not escaped, as they were part of the string literal.18621863 examples:1864 - program: '@html'1865 input: '"This works if x < y"'1866 output: ['"This works if x &lt; y"']18671868# - program: '@html "<span>Anonymous said: \(.)</span>"'1869# input: '"<script>alert(\"lol hax\");</script>"'1870# output: ["<span>Anonymous said: &lt;script&gt;alert(&quot;lol hax&quot;);&lt;/script&gt;</span>"]18711872 - program: '@sh "echo \(.)"'1873 input: "\"O'Hara's Ale\""1874 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]18751876 - program: '@base64'1877 input: '"This is a message"'1878 output: ['"VGhpcyBpcyBhIG1lc3NhZ2U="']18791880 - program: '@base64d'1881 input: '"VGhpcyBpcyBhIG1lc3NhZ2U="'1882 output: ['"This is a message"']18831884 - title: "Dates"1885 body: |18861887 jq provides some basic date handling functionality, with some1888 high-level and low-level builtins. In all cases these1889 builtins deal exclusively with time in UTC.18901891 The `fromdateiso8601` builtin parses datetimes in the ISO 86011892 format to a number of seconds since the Unix epoch1893 (1970-01-01T00:00:00Z). The `todateiso8601` builtin does the1894 inverse.18951896 The `fromdate` builtin parses datetime strings. Currently1897 `fromdate` only supports ISO 8601 datetime strings, but in the1898 future it will attempt to parse datetime strings in more1899 formats.19001901 The `todate` builtin is an alias for `todateiso8601`.19021903 The `now` builtin outputs the current time, in seconds since1904 the Unix epoch.19051906 Low-level jq interfaces to the C-library time functions are1907 also provided: `strptime`, `strftime`, `strflocaltime`,1908 `mktime`, `gmtime`, and `localtime`. Refer to your host1909 operating system's documentation for the format strings used1910 by `strptime` and `strftime`. Note: these are not necessarily1911 stable interfaces in jq, particularly as to their localization1912 functionality.19131914 The `gmtime` builtin consumes a number of seconds since the1915 Unix epoch and outputs a "broken down time" representation of1916 Greenwhich Meridian time as an array of numbers representing1917 (in this order): the year, the month (zero-based), the day of1918 the month (one-based), the hour of the day, the minute of the1919 hour, the second of the minute, the day of the week, and the1920 day of the year -- all one-based unless otherwise stated. The1921 day of the week number may be wrong on some systems for dates1922 before March 1st 1900, or after December 31 2099.19231924 The `localtime` builtin works like the `gmtime` builtin, but1925 using the local timezone setting.19261927 The `mktime` builtin consumes "broken down time"1928 representations of time output by `gmtime` and `strptime`.19291930 The `strptime(fmt)` builtin parses input strings matching the1931 `fmt` argument. The output is in the "broken down time"1932 representation consumed by `gmtime` and output by `mktime`.19331934 The `strftime(fmt)` builtin formats a time (GMT) with the1935 given format. The `strflocaltime` does the same, but using1936 the local timezone setting.19371938 The format strings for `strptime` and `strftime` are described1939 in typical C library documentation. The format string for ISO1940 8601 datetime is `"%Y-%m-%dT%H:%M:%SZ"`.19411942 jq may not support some or all of this date functionality on1943 some systems. In particular, the `%u` and `%j` specifiers for1944 `strptime(fmt)` are not supported on macOS.19451946 examples:1947 - program: 'fromdate'1948 input: '"2015-03-05T23:51:47Z"'1949 output: ['1425599507']19501951 - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")'1952 input: '"2015-03-05T23:51:47Z"'1953 output: ['[2015,2,5,23,51,47,4,63]']19541955 - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'1956 input: '"2015-03-05T23:51:47Z"'1957 output: ['1425599507']19581959 - title: "SQL-Style Operators"1960 body: |19611962 jq provides a few SQL-style operators.19631964 * INDEX(stream; index_expression):19651966 This builtin produces an object whose keys are computed by1967 the given index expression applied to each value from the1968 given stream.19691970 * JOIN($idx; stream; idx_expr; join_expr):19711972 This builtin joins the values from the given stream to the1973 given index. The index's keys are computed by applying the1974 given index expression to each value from the given stream.1975 An array of the value in the stream and the corresponding1976 value from the index is fed to the given join expression to1977 produce each result.19781979 * JOIN($idx; stream; idx_expr):19801981 Same as `JOIN($idx; stream; idx_expr; .)`.19821983 * JOIN($idx; idx_expr):19841985 This builtin joins the input `.` to the given index, applying1986 the given index expression to `.` to compute the index key.1987 The join operation is as described above.19881989 * IN(s):19901991 This builtin outputs `true` if `.` appears in the given1992 stream, otherwise it outputs `false`.19931994 * IN(source; s):19951996 This builtin outputs `true` if any value in the source stream1997 appears in the second stream, otherwise it outputs `false`.19981999 - title: "`builtins`"2000 body: |20012002 Returns a list of all builtin functions in the format `name/arity`.2003 Since functions with the same name but different arities are considered2004 separate functions, `all/0`, `all/1`, and `all/2` would all be present2005 in the list.20062007 - title: Conditionals and Comparisons2008 entries:2009 - title: "`==`, `!=`"2010 body: |20112012 The expression 'a == b' will produce 'true' if the result of a and b2013 are equal (that is, if they represent equivalent JSON documents) and2014 'false' otherwise. In particular, strings are never considered equal2015 to numbers. If you're coming from Javascript, jq's == is like2016 Javascript's === - considering values equal only when they have the2017 same type as well as the same value.20182019 != is "not equal", and 'a != b' returns the opposite value of 'a == b'20202021 examples:2022 - program: '.[] == 1'2023 input: '[1, 1.0, "1", "banana"]'2024 output: ['true', 'true', 'false', 'false']20252026 - title: if-then-else2027 body: |20282029 `if A then B else C end` will act the same as `B` if `A`2030 produces a value other than false or null, but act the same2031 as `C` otherwise.20322033 Checking for false or null is a simpler notion of2034 "truthiness" than is found in Javascript or Python, but it2035 means that you'll sometimes have to be more explicit about2036 the condition you want: you can't test whether, e.g. a2037 string is empty using `if .name then A else B end`, you'll2038 need something more like `if (.name | length) > 0 then A else2039 B end` instead.20402041 If the condition `A` produces multiple results, then `B` is evaluated2042 once for each result that is not false or null, and `C` is evaluated2043 once for each false or null.20442045 More cases can be added to an if using `elif A then B` syntax.20462047 examples:2048 - program: |-2049 if . == 0 then2050 "zero"2051 elif . == 1 then2052 "one"2053 else2054 "many"2055 end2056 input: 22057 output: ['"many"']20582059 - title: "`>, >=, <=, <`"2060 body: |20612062 The comparison operators `>`, `>=`, `<=`, `<` return whether2063 their left argument is greater than, greater than or equal2064 to, less than or equal to or less than their right argument2065 (respectively).20662067 The ordering is the same as that described for `sort`, above.20682069 examples:2070 - program: '. < 5'2071 input: 22072 output: ['true']20732074 - title: and/or/not2075 body: |20762077 jq supports the normal Boolean operators and/or/not. They have the2078 same standard of truth as if expressions - false and null are2079 considered "false values", and anything else is a "true value".20802081 If an operand of one of these operators produces multiple2082 results, the operator itself will produce a result for each input.20832084 `not` is in fact a builtin function rather than an operator,2085 so it is called as a filter to which things can be piped2086 rather than with special syntax, as in `.foo and .bar |2087 not`.20882089 These three only produce the values "true" and "false", and2090 so are only useful for genuine Boolean operations, rather2091 than the common Perl/Python/Ruby idiom of2092 "value_that_may_be_null or default". If you want to use this2093 form of "or", picking between two values rather than2094 evaluating a condition, see the "//" operator below.20952096 examples:2097 - program: '42 and "a string"'2098 input: 'null'2099 output: ['true']2100 - program: '(true, false) or false'2101 input: 'null'2102 output: ['true', 'false']2103# - program: '(true, false) and (true, false)'2104# input: 'null'2105# output: ['true', 'false', 'false', 'false']2106 - program: '(true, true) and (true, false)'2107 input: 'null'2108 output: ['true', 'false', 'true', 'false']2109 - program: '[true, false | not]'2110 input: 'null'2111 output: ['[false, true]']21122113 - title: "Alternative operator: `//`"2114 body: |21152116 A filter of the form `a // b` produces the same2117 results as `a`, if `a` produces results other than `false`2118 and `null`. Otherwise, `a // b` produces the same results as `b`.21192120 This is useful for providing defaults: `.foo // 1` will2121 evaluate to `1` if there's no `.foo` element in the2122 input. It's similar to how `or` is sometimes used in Python2123 (jq's `or` operator is reserved for strictly Boolean2124 operations).21252126 examples:2127 - program: '.foo // 42'2128 input: '{"foo": 19}'2129 output: [19]2130 - program: '.foo // 42'2131 input: '{}'2132 output: [42]21332134 - title: try-catch2135 body: |21362137 Errors can be caught by using `try EXP catch EXP`. The first2138 expression is executed, and if it fails then the second is2139 executed with the error message. The output of the handler,2140 if any, is output as if it had been the output of the2141 expression to try.21422143 The `try EXP` form uses `empty` as the exception handler.21442145 examples:2146 - program: 'try .a catch ". is not an object"'2147 input: 'true'2148 output: ['". is not an object"']2149 - program: '[.[]|try .a]'2150 input: '[{}, true, {"a":1}]'2151 output: ['[null, 1]']2152 - program: 'try error("some exception") catch .'2153 input: 'true'2154 output: ['"some exception"']21552156 - title: Breaking out of control structures2157 body: |21582159 A convenient use of try/catch is to break out of control2160 structures like `reduce`, `foreach`, `while`, and so on.21612162 For example:21632164 # Repeat an expression until it raises "break" as an2165 # error, then stop repeating without re-raising the error.2166 # But if the error caught is not "break" then re-raise it.2167 try repeat(exp) catch .=="break" then empty else error;21682169 jq has a syntax for named lexical labels to "break" or "go (back) to":21702171 label $out | ... break $out ...21722173 The `break $label_name` expression will cause the program to2174 to act as though the nearest (to the left) `label $label_name`2175 produced `empty`.21762177 The relationship between the `break` and corresponding `label`2178 is lexical: the label has to be "visible" from the break.21792180 To break out of a `reduce`, for example:21812182 label $out | reduce .[] as $item (null; if .==false then break $out else ... end)21832184 The following jq program produces a syntax error:21852186 break $out21872188 because no label `$out` is visible.21892190 - title: "Error Suppression / Optional Operator: `?`"2191 body: |21922193 The `?` operator, used as `EXP?`, is shorthand for `try EXP`.21942195 examples:2196 - program: '[.[]|(.a)?]'2197 input: '[{}, true, {"a":1}]'2198 output: ['[null, 1]']219922002201 - title: Regular expressions (PCRE)2202 body: |22032204 jq uses the Oniguruma regular expression library, as do php,2205 ruby, TextMate, Sublime Text, etc, so the description here2206 will focus on jq specifics.22072208 The jq regex filters are defined so that they can be used using2209 one of these patterns:22102211 STRING | FILTER( REGEX )2212 STRING | FILTER( REGEX; FLAGS )2213 STRING | FILTER( [REGEX] )2214 STRING | FILTER( [REGEX, FLAGS] )22152216 where:2217 * STRING, REGEX and FLAGS are jq strings and subject to jq string interpolation;2218 * REGEX, after string interpolation, should be a valid PCRE regex;2219 * FILTER is one of `test`, `match`, or `capture`, as described below.22202221 FLAGS is a string consisting of one of more of the supported flags:22222223 * `g` - Global search (find all matches, not just the first)2224 * `i` - Case insensitive search2225 * `m` - Multi line mode ('.' will match newlines)2226 * `n` - Ignore empty matches2227 * `p` - Both s and m modes are enabled2228 * `s` - Single line mode ('^' -> '\A', '$' -> '\Z')2229 * `l` - Find longest possible matches2230 * `x` - Extended regex format (ignore whitespace and comments)22312232 To match whitespace in an x pattern use an escape such as \s, e.g.22332234 * test( "a\\sb", "x" ).22352236 Note that certain flags may also be specified within REGEX, e.g.22372238 * jq -n '("test", "TEst", "teST", "TEST") | test( "(?i)te(?-i)st" )'22392240 evaluates to: true, true, false, false.22412242 entries:2243 - title: "`test(val)`, `test(regex; flags)`"2244 body: |22452246 Like `match`, but does not return match objects, only `true` or `false`2247 for whether or not the regex matches the input.22482249 examples:2250 - program: 'test("foo")'2251 input: '"foo"'2252 output: ['true']2253 - program: '.[] | test("a b c # spaces are ignored"; "ix")'2254 input: '["xabcd", "ABC"]'2255 output: ['true', 'true']22562257 - title: "`match(val)`, `match(regex; flags)`"2258 body: |22592260 **match** outputs an object for each match it finds. Matches have2261 the following fields:22622263 * `offset` - offset in UTF-8 codepoints from the beginning of the input2264 * `length` - length in UTF-8 codepoints of the match2265 * `string` - the string that it matched2266 * `captures` - an array of objects representing capturing groups.22672268 Capturing group objects have the following fields:22692270 * `offset` - offset in UTF-8 codepoints from the beginning of the input2271 * `length` - length in UTF-8 codepoints of this capturing group2272 * `string` - the string that was captured2273 * `name` - the name of the capturing group (or `null` if it was unnamed)22742275 Capturing groups that did not match anything return an offset of -122762277 examples:2278 - program: 'match("(abc)+"; "g")'2279 input: '"abc abc"'2280 output:2281 - '{"offset": 0, "length": 3, "string": "abc", "captures": [{"offset": 0, "length": 3, "string": "abc", "name": null}]}'2282 - '{"offset": 4, "length": 3, "string": "abc", "captures": [{"offset": 4, "length": 3, "string": "abc", "name": null}]}'2283 - program: 'match("foo")'2284 input: '"foo bar foo"'2285 output: ['{"offset": 0, "length": 3, "string": "foo", "captures": []}']2286 - program: 'match(["foo", "ig"])'2287 input: '"foo bar FOO"'2288 output:2289 - '{"offset": 0, "length": 3, "string": "foo", "captures": []}'2290 - '{"offset": 8, "length": 3, "string": "FOO", "captures": []}'2291 - program: 'match("foo (?<bar123>bar)? foo"; "ig")'2292 input: '"foo bar foo foo foo"'2293 output:2294 - '{"offset": 0, "length": 11, "string": "foo bar foo", "captures": [{"offset": 4, "length": 3, "string": "bar", "name": "bar123"}]}'2295 - '{"offset": 12, "length": 8, "string": "foo foo", "captures": [{"offset": -1, "length": 0, "string": null, "name": "bar123"}]}'22962297 - program: '[ match("."; "g")] | length'2298 input: '"abc"'2299 output: [3]230023012302 - title: "`capture(val)`, `capture(regex; flags)`"2303 body: |23042305 Collects the named captures in a JSON object, with the name2306 of each capture as the key, and the matched string as the2307 corresponding value.23082309 examples:2310 - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2311 input: '"xyzzy-14"'2312 output: ['{ "a": "xyzzy", "n": "14" }']23132314 - title: "`scan(regex)`, `scan(regex; flags)`"2315 body: |23162317 Emit a stream of the non-overlapping substrings of the input2318 that match the regex in accordance with the flags, if any2319 have been specified. If there is no match, the stream is empty.2320 To capture all the matches for each input string, use the idiom2321 `[ expr ]`, e.g. `[ scan(regex) ]`.23222323 example:2324 - program: 'scan("c")'2325 input: '"abcdefabc"'2326 output: ['"c"', '"c"']23272328 - program: 'scan("b")'2329 input: ("", "")2330 output: ['[]', '[]']23312332 - title: "`split(regex; flags)`"2333 body: |23342335 For backwards compatibility, `split` splits on a string, not a regex.23362337 example:2338 - program: 'split(", *"; null)'2339 input: '"ab,cd, ef"'2340 output: ['"ab","cd","ef"']234123422343 - title: "`splits(regex)`, `splits(regex; flags)`"2344 body: |23452346 These provide the same results as their `split` counterparts,2347 but as a stream instead of an array.23482349 example:2350 - program: 'splits(", *")'2351 input: '("ab,cd", "ef, gh")'2352 output: ['"ab"', '"cd"', '"ef"', '"gh"']23532354 - title: "`sub(regex; tostring)` `sub(regex; string; flags)`"2355 body: |23562357 Emit the string obtained by replacing the first match of regex in the2358 input string with `tostring`, after interpolation. `tostring` should2359 be a jq string, and may contain references to named captures. The2360 named captures are, in effect, presented as a JSON object (as2361 constructed by `capture`) to `tostring`, so a reference to a captured2362 variable named "x" would take the form: "\(.x)".23632364 example:2365 - program: 'sub("^[^a-z]*(?<x>[a-z]*).*")'2366 input: '"123abc456"'2367 output: '"ZabcZabc"'236823692370 - title: "`gsub(regex; string)`, `gsub(regex; string; flags)`"2371 body: |23722373 `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2374 replaced by the string, after interpolation.23752376 example:2377 - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2378 input: '"Abcabc"'2379 output: '"+A-+a-"'238023812382 - title: Advanced features2383 body: |2384 Variables are an absolute necessity in most programming languages, but2385 they're relegated to an "advanced feature" in jq.23862387 In most languages, variables are the only means of passing around2388 data. If you calculate a value, and you want to use it more than once,2389 you'll need to store it in a variable. To pass a value to another part2390 of the program, you'll need that part of the program to define a2391 variable (as a function parameter, object member, or whatever) in2392 which to place the data.23932394 It is also possible to define functions in jq, although this is2395 is a feature whose biggest use is defining jq's standard library2396 (many jq functions such as `map` and `find` are in fact written2397 in jq).23982399 jq has reduction operators, which are very powerful but a bit2400 tricky. Again, these are mostly used internally, to define some2401 useful bits of jq's standard library.24022403 It may not be obvious at first, but jq is all about generators2404 (yes, as often found in other languages). Some utilities are2405 provided to help deal with generators.24062407 Some minimal I/O support (besides reading JSON from standard2408 input, and writing JSON to standard output) is available.24092410 Finally, there is a module/library system.24112412 entries:2413 - title: "Variable / Symbolic Binding Operator: `... as $identifier | ...`"2414 body: |24152416 In jq, all filters have an input and an output, so manual2417 plumbing is not necessary to pass a value from one part of a program2418 to the next. Many expressions, for instance `a + b`, pass their input2419 to two distinct subexpressions (here `a` and `b` are both passed the2420 same input), so variables aren't usually necessary in order to use a2421 value twice.24222423 For instance, calculating the average value of an array of numbers2424 requires a few variables in most languages - at least one to hold the2425 array, perhaps one for each element or for a loop counter. In jq, it's2426 simply `add / length` - the `add` expression is given the array and2427 produces its sum, and the `length` expression is given the array and2428 produces its length.24292430 So, there's generally a cleaner way to solve most problems in jq than2431 defining variables. Still, sometimes they do make things easier, so jq2432 lets you define variables using `expression as $variable`. All2433 variable names start with `$`. Here's a slightly uglier version of the2434 array-averaging example:24352436 length as $array_length | add / $array_length24372438 We'll need a more complicated problem to find a situation where using2439 variables actually makes our lives easier.244024412442 Suppose we have an array of blog posts, with "author" and "title"2443 fields, and another object which is used to map author usernames to2444 real names. Our input looks like:24452446 {"posts": [{"title": "Frist psot", "author": "anon"},2447 {"title": "A well-written article", "author": "person1"}],2448 "realnames": {"anon": "Anonymous Coward",2449 "person1": "Person McPherson"}}24502451 We want to produce the posts with the author field containing a real2452 name, as in:24532454 {"title": "Frist psot", "author": "Anonymous Coward"}2455 {"title": "A well-written article", "author": "Person McPherson"}24562457 We use a variable, $names, to store the realnames object, so that we2458 can refer to it later when looking up author usernames:24592460 .realnames as $names | .posts[] | {title, author: $names[.author]}24612462 The expression `exp as $x | ...` means: for each value of expression2463 `exp`, run the rest of the pipeline with the entire original input, and2464 with `$x` set to that value. Thus `as` functions as something of a2465 foreach loop.24662467 Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2468 `{$foo}` is a handy way of writing `{foo:$foo}`.24692470 Multiple variables may be declared using a single `as` expression by2471 providing a pattern that matches the structure of the input2472 (this is known as "destructuring"):24732474 . as {realnames: $names, posts: [$first, $second]} | ...24752476 The variable declarations in array patterns (e.g., `. as2477 [$first, $second]`) bind to the elements of the array in from2478 the element at index zero on up, in order. When there is no2479 value at the index for an array pattern element, `null` is2480 bound to that variable.24812482 Variables are scoped over the rest of the expression that defines2483 them, so24842485 .realnames as $names | (.posts[] | {title, author: $names[.author]})24862487 will work, but24882489 (.realnames as $names | .posts[]) | {title, author: $names[.author]}24902491 won't.24922493 For programming language theorists, it's more accurate to2494 say that jq variables are lexically-scoped bindings. In2495 particular there's no way to change the value of a binding;2496 one can only setup a new binding with the same name, but which2497 will not be visible where the old one was.24982499 examples:2500 - program: '.bar as $x | .foo | . + $x'2501 input: '{"foo":10, "bar":200}'2502 output: ['210']2503 - program: '. as $i|[(.*2|. as $i| $i), $i]'2504 input: '5'2505 output: ['[10,5]']2506 - program: '. as [$a, $b, {c: $c}] | $a + $b + $c'2507 input: '[2, 3, {"c": 4, "d": 5}]'2508 output: ['9']2509 - program: '.[] as [$a, $b] | {a: $a, b: $b}'2510 input: '[[0], [0, 1], [2, 1, 0]]'2511 output: ['{"a":0,"b":null}', '{"a":0,"b":1}', '{"a":2,"b":1}']25122513 - title: 'Destructuring Alternative Operator: `?//`'2514 body: |2515 2516 The destructuring alternative operator provides a concise mechanism2517 for destructuring an input that can take one of several forms.25182519 Suppose we have an API that returns a list of resources and events2520 associated with them, and we want to get the user_id and timestamp of2521 the first event for each resource. The API (having been clumsily2522 converted from XML) will only wrap the events in an array if the resource2523 has multiple events:2524 2525 {"resources": [{"id": 1, "kind": "widget", "events": {"action": "create", "user_id": 1, "ts": 13}},2526 {"id": 2, "kind": "widget", "events": [{"action": "create", "user_id": 1, "ts": 14}, {"action": "destroy", "user_id": 1, "ts": 15}]}]}2527 2528 We can use the destructuring alternative operator to handle this structural change simply:25292530 .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$user_id, $ts}]} | {$user_id, $kind, $id, $ts}25312532 Or, if we aren't sure if the input is an array of values or an object:25332534 .[] as [$id, $kind, $user_id, $ts] ?// {$id, $kind, $user_id, $ts} | ...25352536 Each alternative need not define all of the same variables, but all named2537 variables will be available to the subsequent expression. Variables not2538 matched in the alternative that succeeded will be `null`:25392540 .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}25412542 Additionally, if the subsequent expression returns an error, the2543 alternative operator will attempt to try the next binding. Errors2544 that occur during the final alternative are passed through.25452546 [[3]] | .[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end25472548 examples:2549 - program: '.[] as {$a, $b, c: {$d, $e}} ?// {$a, $b, c: [{$d, $e}]} | {$a, $b, $d, $e}'2550 input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2551 output: ['{"a":1,"b":2,"d":3,"e":4}', '{"a":1,"b":2,"d":3,"e":4}']2552 - program: '.[] as {$a, $b, c: {$d}} ?// {$a, $b, c: [{$e}]} | {$a, $b, $d, $e}'2553 input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2554 output: ['{"a":1,"b":2,"d":3,"e":null}', '{"a":1,"b":2,"d":null,"e":4}']2555 - program: '.[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end'2556 input: '[[3]]'2557 output: ['{"a":null,"b":3}']25582559 - title: 'Defining Functions'2560 body: |25612562 You can give a filter a name using "def" syntax:25632564 def increment: . + 1;25652566 From then on, `increment` is usable as a filter just like a2567 builtin function (in fact, this is how many of the builtins2568 are defined). A function may take arguments:25692570 def map(f): [.[] | f];25712572 Arguments are passed as _filters_ (functions with no2573 arguments), _not_ as values. The same argument may be2574 referenced multiple times with different inputs (here `f` is2575 run for each element of the input array). Arguments to a2576 function work more like callbacks than like value arguments.2577 This is important to understand. Consider:25782579 def foo(f): f|f;2580 5|foo(.*2)25812582 The result will be 20 because `f` is `.*2`, and during the2583 first invocation of `f` `.` will be 5, and the second time it2584 will be 10 (5 * 2), so the result will be 20. Function2585 arguments are filters, and filters expect an input when2586 invoked.25872588 If you want the value-argument behaviour for defining simple2589 functions, you can just use a variable:25902591 def addvalue(f): f as $f | map(. + $f);25922593 Or use the short-hand:25942595 def addvalue($f): ...;25962597 With either definition, `addvalue(.foo)` will add the current2598 input's `.foo` field to each element of the array. Do note2599 that calling `addvalue(.[])` will cause the `map(. + $f)` part2600 to be evaluated once per value in the value of `.` at the call2601 site.26022603 Multiple definitions using the same function name are allowed.2604 Each re-definition replaces the previous one for the same2605 number of function arguments, but only for references from2606 functions (or main program) subsequent to the re-definition.2607 See also the section below on scoping.26082609 examples:2610 - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'2611 input: '[[1,2],[10,20]]'2612 output: ['[[1,2,1], [10,20,10]]']2613 - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'2614 input: '[[1,2],[10,20]]'2615 output: ['[[1,2,1,2], [10,20,1,2]]']26162617 - title: 'Scoping'2618 body: |26192620 There are two types of symbols in jq: value bindings (a.k.a.,2621 "variables"), and functions. Both are scoped lexically,2622 with expressions being able to refer only to symbols that2623 have been defined "to the left" of them. The only exception2624 to this rule is that functions can refer to themselves so as2625 to be able to create recursive functions.26262627 For example, in the following expression there is a binding2628 which is visible "to the right" of it, `... | .*3 as2629 $times_three | [. + $times_three] | ...`, but not "to the2630 left". Consider this expression now, `... | (.*3 as2631 $times_three | [.+ $times_three]) | ...`: here the binding2632 `$times_three` is _not_ visible past the closing parenthesis.26332634 - title: Reduce2635 body: |26362637 The `reduce` syntax in jq allows you to combine all of the2638 results of an expression by accumulating them into a single2639 answer. As an example, we'll pass `[3,2,1]` to this expression:26402641 reduce .[] as $item (0; . + $item)26422643 For each result that `.[]` produces, `. + $item` is run to2644 accumulate a running total, starting from 0. In this2645 example, `.[]` produces the results 3, 2, and 1, so the2646 effect is similar to running something like this:26472648 0 | (3 as $item | . + $item) |2649 (2 as $item | . + $item) |2650 (1 as $item | . + $item)26512652 examples:2653 - program: 'reduce .[] as $item (0; . + $item)'2654 input: '[10,2,5,3]'2655 output: ['20']26562657 - title: "`isempty(exp)`"2658 body: |26592660 Returns true if `exp` produces no outputs, false otherwise.26612662 examples:2663 - program: 'isempty(empty)'2664 input: 'null'2665 output: ['true']26662667 - title: "`limit(n; exp)`"2668 body: |26692670 The `limit` function extracts up to `n` outputs from `exp`.26712672 examples:2673 - program: '[limit(3;.[])]'2674 input: '[0,1,2,3,4,5,6,7,8,9]'2675 output: ['[0,1,2]']26762677 - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"2678 body: |26792680 The `first(expr)` and `last(expr)` functions extract the first2681 and last values from `expr`, respectively.26822683 The `nth(n; expr)` function extracts the nth value output by2684 `expr`. This can be defined as `def nth(n; expr):2685 last(limit(n + 1; expr));`. Note that `nth(n; expr)` doesn't2686 support negative values of `n`.26872688 examples:2689 - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'2690 input: '10'2691 output: ['[0,9,5]']26922693 - title: "`first`, `last`, `nth(n)`"2694 body: |26952696 The `first` and `last` functions extract the first2697 and last values from any array at `.`.26982699 The `nth(n)` function extracts the nth value of any array at `.`.27002701 examples:2702 - program: '[range(.)]|[first, last, nth(5)]'2703 input: '10'2704 output: ['[0,9,5]']27052706 - title: "`foreach`"2707 body: |27082709 The `foreach` syntax is similar to `reduce`, but intended to2710 allow the construction of `limit` and reducers that produce2711 intermediate results (see example).27122713 The form is `foreach EXP as $var (INIT; UPDATE; EXTRACT)`.2714 Like `reduce`, `INIT` is evaluated once to produce a state2715 value, then each output of `EXP` is bound to `$var`, `UPDATE`2716 is evaluated for each output of `EXP` with the current state2717 and with `$var` visible. Each value output by `UPDATE`2718 replaces the previous state. Finally, `EXTRACT` is evaluated2719 for each new state to extract an output of `foreach`.27202721 This is mostly useful only for constructing `reduce`- and2722 `limit`-like functions. But it is much more general, as it2723 allows for partial reductions (see the example below).27242725 examples:2726 - program: '[foreach .[] as $item2727 ([[],[]];2728 if $item == null then [[],.[0]] else [(.[0] + [$item]),[]] end;2729 if $item == null then .[1] else empty end)]'2730 input: '[1,2,3,4,null,"a","b",null]'2731 output: ['[[1,2,3,4],["a","b"]]']27322733 - title: Recursion2734 body: |27352736 As described above, `recurse` uses recursion, and any jq2737 function can be recursive. The `while` builtin is also2738 implemented in terms of recursion.27392740 Tail calls are optimized whenever the expression to the left of2741 the recursive call outputs its last value. In practice this2742 means that the expression to the left of the recursive call2743 should not produce more than one output for each input.27442745 For example:27462747 def recurse(f): def r: ., (f | select(. != null) | r); r;27482749 def while(cond; update):2750 def _while:2751 if cond then ., (update | _while) else empty end;2752 _while;27532754 def repeat(exp):2755 def _repeat:2756 exp, _repeat;2757 _repeat;27582759 - title: Generators and iterators2760 body: |27612762 Some jq operators and functions are actually generators in2763 that they can produce zero, one, or more values for each2764 input, just as one might expect in other programming2765 languages that have generators. For example, `.[]`2766 generates all the values in its input (which must be an2767 array or an object), `range(0; 10)` generates the integers2768 between 0 and 10, and so on.27692770 Even the comma operator is a generator, generating first the2771 values generated by the expression to the left of the comma,2772 then for each of those, the values generate by the2773 expression on the right of the comma.27742775 The `empty` builtin is the generator that produces zero2776 outputs. The `empty` builtin backtracks to the preceding2777 generator expression.27782779 All jq functions can be generators just by using builtin2780 generators. It is also possible to define new generators2781 using only recursion and the comma operator. If the2782 recursive call(s) is(are) "in tail position" then the2783 generator will be efficient. In the example below the2784 recursive call by `_range` to itself is in tail position.2785 The example shows off three advanced topics: tail recursion,2786 generator construction, and sub-functions.27872788 examples:2789 - program: 'def range(init; upto; by):2790 def _range:2791 if (by > 0 and . < upto) or (by < 0 and . > upto)2792 then ., ((.+by)|_range)2793 else . end;2794 if by == 0 then init else init|_range end |2795 select((by > 0 and . < upto) or (by < 0 and . > upto));2796 range(0; 10; 3)'2797 input: 'null'2798 output: ['0', '3', '6', '9']2799 - program: 'def while(cond; update):2800 def _while:2801 if cond then ., (update | _while) else empty end;2802 _while;2803 [while(.<100; .*2)]'2804 input: '1'2805 output: ['[1,2,4,8,16,32,64]']28062807 - title: 'Math'2808 body: |28092810 jq currently only has IEEE754 double-precision (64-bit) floating2811 point number support.28122813 Besides simple arithmetic operators such as `+`, jq also has most2814 standard math functions from the C math library. C math functions2815 that take a single input argument (e.g., `sin()`) are available as2816 zero-argument jq functions. C math functions that take two input2817 arguments (e.g., `pow()`) are available as two-argument jq2818 functions that ignore `.`. C math functions that take three input2819 arguments are available as three-argument jq functions that ignore2820 `.`.28212822 Availability of standard math functions depends on the2823 availability of the corresponding math functions in your operating2824 system and C math library. Unavailable math functions will be2825 defined but will raise an error.28262827 One-input C math functions: `acos` `acosh` `asin` `asinh` `atan`2828 `atanh` `cbrt` `ceil` `cos` `cosh` `erf` `erfc` `exp` `exp10`2829 `exp2` `expm1` `fabs` `floor` `gamma` `j0` `j1` `lgamma` `log`2830 `log10` `log1p` `log2` `logb` `nearbyint` `pow10` `rint` `round`2831 `significand` `sin` `sinh` `sqrt` `tan` `tanh` `tgamma` `trunc`2832 `y0` `y1`.28332834 Two-input C math functions: `atan2` `copysign` `drem` `fdim`2835 `fmax` `fmin` `fmod` `frexp` `hypot` `jn` `ldexp` `modf`2836 `nextafter` `nexttoward` `pow` `remainder` `scalb` `scalbln` `yn`.28372838 Three-input C math functions: `fma`.28392840 See your system's manual for more information on each of these.28412842 - title: 'I/O'2843 body: |28442845 At this time jq has minimal support for I/O, mostly in the2846 form of control over when inputs are read. Two builtins functions2847 are provided for this, `input` and `inputs`, that read from the2848 same sources (e.g., `stdin`, files named on the command-line) as2849 jq itself. These two builtins, and jq's own reading actions, can2850 be interleaved with each other.28512852 Two builtins provide minimal output capabilities, `debug`, and2853 `stderr`. (Recall that a jq program's output values are always2854 output as JSON texts on `stdout`.) The `debug` builtin can have2855 application-specific behavior, such as for executables that use2856 the libjq C API but aren't the jq executable itself. The `stderr`2857 builtin outputs its input in raw mode to stder with no additional2858 decoration, not even a newline.28592860 Most jq builtins are referentially transparent, and yield constant2861 and repeatable value streams when applied to constant inputs.2862 This is not true of I/O builtins.28632864 entries:2865 - title: "`input`"2866 body: |28672868 Outputs one new input.28692870 - title: "`inputs`"2871 body: |28722873 Outputs all remaining inputs, one by one.28742875 This is primarily useful for reductions over a program's2876 inputs.28772878 - title: "`debug`"2879 body: |28802881 Causes a debug message based on the input value to be2882 produced. The jq executable wraps the input value with2883 `["DEBUG:", <input-value>]` and prints that and a newline on2884 stderr, compactly. This may change in the future.28852886 - title: "`stderr`"2887 body: |28882889 Prints its input in raw and compact mode to stderr with no2890 additional decoration, not even a newline.28912892 - title: "`input_filename`"2893 body: |28942895 Returns the name of the file whose input is currently being2896 filtered. Note that this will not work well unless jq is2897 running in a UTF-8 locale.28982899 - title: "`input_line_number`"2900 body: |29012902 Returns the line number of the input currently being filtered.29032904 - title: 'Streaming'2905 body: |29062907 With the `--stream` option jq can parse input texts in a streaming2908 fashion, allowing jq programs to start processing large JSON texts2909 immediately rather than after the parse completes. If you have a2910 single JSON text that is 1GB in size, streaming it will allow you2911 to process it much more quickly.29122913 However, streaming isn't easy to deal with as the jq program will2914 have `[<path>, <leaf-value>]` (and a few other forms) as inputs.29152916 Several builtins are provided to make handling streams easier.29172918 The examples below use the streamed form of `[0,[1]]`, which is2919 `[[0],0],[[1,0],1],[[1,0]],[[1]]`.29202921 Streaming forms include `[<path>, <leaf-value>]` (to indicate any2922 scalar value, empty array, or empty object), and `[<path>]` (to2923 indicate the end of an array or object). Future versions of jq2924 run with `--stream` and `-seq` may output additional forms such as2925 `["error message"]` when an input text fails to parse.29262927 entries:2928 - title: "`truncate_stream(stream_expression)`"2929 body: |29302931 Consumes a number as input and truncates the corresponding2932 number of path elements from the left of the outputs of the2933 given streaming expression.29342935 examples:2936 - program: '[1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]'2937 input: '1'2938 output: ['[[[0],2],[[0]]]']29392940 - title: "`fromstream(stream_expression)`"2941 body: |29422943 Outputs values corresponding to the stream expression's2944 outputs.29452946 examples:2947 - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'2948 input: 'null'2949 output: ['[2]']29502951 - title: "`tostream`"2952 body: |29532954 The `tostream` builtin outputs the streamed form of its input.29552956 examples:2957 - program: '. as $dot|fromstream($dot|tostream)|.==$dot'2958 input: '[0,[1,{"a":1},{"b":2}]]'2959 output: ['true']29602961 - title: Assignment2962 body: |2963 Assignment works a little differently in jq than in most2964 programming languages. jq doesn't distinguish between references2965 to and copies of something - two objects or arrays are either2966 equal or not equal, without any further notion of being "the2967 same object" or "not the same object".29682969 If an object has two fields which are arrays, `.foo` and `.bar`,2970 and you append something to `.foo`, then `.bar` will not get2971 bigger, even if you've previously set `.bar = .foo`. If you're2972 used to programming in languages like Python, Java, Ruby,2973 Javascript, etc. then you can think of it as though jq does a full2974 deep copy of every object before it does the assignment (for2975 performance it doesn't actually do that, but that's the general2976 idea).29772978 This means that it's impossible to build circular values in jq2979 (such as an array whose first element is itself). This is quite2980 intentional, and ensures that anything a jq program can produce2981 can be represented in JSON.29822983 All the assignment operators in jq have path expressions on the2984 left-hand side (LHS). The right-hand side (RHS) provides values2985 to set to the paths named by the LHS path expressions.29862987 Values in jq are always immutable. Internally, assignment works2988 by using a reduction to compute new, replacement values for `.` that2989 have had all the desired assignments applied to `.`, then2990 outputting the modified value. This might be made clear by this2991 example: `{a:{b:{c:1}}} | (.a.b|=3), .`. This will output2992 `{"a":{"b":3}}` and `{"a":{"b":{"c":1}}}` because the last2993 sub-expression, `.`, sees the original value, not the modified2994 value.29952996 Most users will want to use modification assignment operators,2997 such as `|=` or `+=`, rather than `=`.29982999 Note that the LHS of assignment operators refers to a value in3000 `.`. Thus `$var.foo = 1` won't work as expected (`$var.foo` is3001 not a valid or useful path expression in `.`); use `$var | .foo =3002 1` instead.30033004 Note too that `.a,.b=0` does not set `.a` and `.b`, but3005 `(.a,.b)=0` sets both.30063007 entries:3008 - title: "Update-assignment: `|=`"3009 body: |3010 This is the "update" operator '|='. It takes a filter on the3011 right-hand side and works out the new value for the property3012 of `.` being assigned to by running the old value through this3013 expression. For instance, (.foo, .bar) |= .+1 will build an3014 object with the "foo" field set to the input's "foo" plus 1,3015 and the "bar" field set to the input's "bar" plus 1.30163017 The left-hand side can be any general path expression; see `path()`.30183019 Note that the left-hand side of '|=' refers to a value in `.`.3020 Thus `$var.foo |= . + 1` won't work as expected (`$var.foo` is3021 not a valid or useful path expression in `.`); use `$var |3022 .foo |= . + 1` instead.30233024 If the right-hand side outputs no values (i.e., `empty`), then3025 the left-hand side path will be deleted, as with `del(path)`.30263027 If the right-hand side outputs multiple values, only the first3028 one will be used (COMPATIBILITY NOTE: in jq 1.5 and earlier3029 releases, it used to be that only the last one was used).30303031 examples:3032 - program: '(..|select(type=="boolean")) |= if . then 1 else 0 end'3033 input: '[true,false,[5,true,[true,[false]],false]]'3034 output: ['[1,0,[5,1,[1,[0]],0]]']30353036 - title: "Arithmetic update-assignment: `+=`, `-=`, `*=`, `/=`, `%=`, `//=`"3037 body: |30383039 jq has a few operators of the form `a op= b`, which are all3040 equivalent to `a |= . op b`. So, `+= 1` can be used to3041 increment values, being the same as `|= . + 1`.30423043 examples:3044 - program: .foo += 13045 input: '{"foo": 42}'3046 output: ['{"foo": 43}']30473048 - title: "Plain assignment: `=`"3049 body: |30503051 This is the plain assignment operator. Unlike the others, the3052 input to the right-hand-side (RHS) is the same as the input to3053 the left-hand-side (LHS) rather than the value at the LHS3054 path, and all values output by the RHS will be used (as shown3055 below).30563057 If the RHS of '=' produces multiple values, then for each such3058 value jq will set the paths on the left-hand side to the value3059 and then it will output the modified `.`. For example,3060 `(.a,.b)=range(2)` outputs `{"a":0,"b":0}`, then3061 `{"a":1,"b":1}`. The "update" assignment forms (see above) do3062 not do this.30633064 This example should show the difference between '=' and '|=':30653066 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:30673068 .a = .b30693070 .a |= .b30713072 The former will set the "a" field of the input to the "b"3073 field of the input, and produce the output {"a": 20, "b": 20}.3074 The latter will set the "a" field of the input to the "a"3075 field's "b" field, producing {"a": 10, "b": 20}.30763077 Another example of the difference between '=' and '|=':30783079 null|(.a,.b)=range(3)30803081 outputs '{"a":0,"b":0}', '{"a":1,"b":1}', and '{"a":2,"b":2}',3082 while30833084 null|(.a,.b)|=range(3)30853086 outputs just '{"a":0,"b":0}'.30873088 - title: Complex assignments3089 body: |3090 Lots more things are allowed on the left-hand side of a jq assignment3091 than in most languages. We've already seen simple field accesses on3092 the left hand side, and it's no surprise that array accesses work just3093 as well:30943095 .posts[0].title = "JQ Manual"30963097 What may come as a surprise is that the expression on the left may3098 produce multiple results, referring to different points in the input3099 document:31003101 .posts[].comments |= . + ["this is great"]31023103 That example appends the string "this is great" to the "comments"3104 array of each post in the input (where the input is an object with a3105 field "posts" which is an array of posts).31063107 When jq encounters an assignment like 'a = b', it records the "path"3108 taken to select a part of the input document while executing a. This3109 path is then used to find which part of the input to change while3110 executing the assignment. Any filter may be used on the3111 left-hand side of an equals - whichever paths it selects from the3112 input will be where the assignment is performed.31133114 This is a very powerful operation. Suppose we wanted to add a comment3115 to blog posts, using the same "blog" input above. This time, we only3116 want to comment on the posts written by "stedolan". We can find those3117 posts using the "select" function described earlier:31183119 .posts[] | select(.author == "stedolan")31203121 The paths provided by this operation point to each of the posts that3122 "stedolan" wrote, and we can comment on each of them in the same way3123 that we did before:31243125 (.posts[] | select(.author == "stedolan") | .comments) |=3126 . + ["terrible."]31273128 - title: Modules3129 body: |31303131 jq has a library/module system. Modules are files whose names end3132 in `.jq`.31333134 Modules imported by a program are searched for in a default search3135 path (see below). The `import` and `include` directives allow the3136 importer to alter this path.31373138 Paths in the a search path are subject to various substitutions.31393140 For paths starting with "~/", the user's home directory is3141 substituted for "~".31423143 For paths starting with "$ORIGIN/", the path of the jq executable3144 is substituted for "$ORIGIN".31453146 For paths starting with "./" or paths that are ".", the path of3147 the including file is substituted for ".". For top-level programs3148 given on the command-line, the current directory is used.31493150 Import directives can optionally specify a search path to which3151 the default is appended.31523153 The default search path is the search path given to the `-L`3154 command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",3155 "$ORIGIN/../lib"]`.31563157 Null and empty string path elements terminate search path3158 processing.31593160 A dependency with relative path "foo/bar" would be searched for in3161 "foo/bar.jq" and "foo/bar/bar.jq" in the given search path. This3162 is intended to allow modules to be placed in a directory along3163 with, for example, version control files, README files, and so on,3164 but also to allow for single-file modules.31653166 Consecutive components with the same name are not allowed to avoid3167 ambiguities (e.g., "foo/foo").31683169 For example, with `-L$HOME/.jq` a module `foo` can be found in3170 `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.31713172 If "$HOME/.jq" is a file, it is sourced into the main program.31733174 entries:3175 - title: "`import RelativePathString as NAME [<metadata>];`"3176 body: |31773178 Imports a module found at the given path relative to a3179 directory in a search path. A ".jq" suffix will be added to3180 the relative path string. The module's symbols are prefixed3181 with "NAME::".31823183 The optional metadata must be a constant jq expression. It3184 should be an object with keys like "homepage" and so on. At3185 this time jq only uses the "search" key/value of the metadata.3186 The metadata is also made available to users via the3187 `modulemeta` builtin.31883189 The "search" key in the metadata, if present, should have a3190 string or array value (array of strings); this is the search3191 path to be prefixed to the top-level search path.31923193 - title: "`include RelativePathString [<metadata>];`"3194 body: |31953196 Imports a module found at the given path relative to a3197 directory in a search path as if it were included in place. A3198 ".jq" suffix will be added to the relative path string. The3199 module's symbols are imported into the caller's namespace as3200 if the module's content had been included directly.32013202 The optional metadata must be a constant jq expression. It3203 should be an object with keys like "homepage" and so on. At3204 this time jq only uses the "search" key/value of the metadata.3205 The metadata is also made available to users via the3206 `modulemeta` builtin.32073208 - title: "`import RelativePathString as $NAME [<metadata>];`"3209 body: |32103211 Imports a JSON file found at the given path relative to a3212 directory in a search path. A ".json" suffix will be added to3213 the relative path string. The file's data will be available3214 as `$NAME::NAME`.32153216 The optional metadata must be a constant jq expression. It3217 should be an object with keys like "homepage" and so on. At3218 this time jq only uses the "search" key/value of the metadata.3219 The metadata is also made available to users via the3220 `modulemeta` builtin.32213222 The "search" key in the metadata, if present, should have a3223 string or array value (array of strings); this is the search3224 path to be prefixed to the top-level search path.32253226 - title: "`module <metadata>;`"3227 body: |32283229 This directive is entirely optional. It's not required for3230 proper operation. It serves only the purpose of providing3231 metadata that can be read with the `modulemeta` builtin.32323233 The metadata must be a constant jq expression. It should be3234 an object with keys like "homepage". At this time jq doesn't3235 use this metadata, but it is made available to users via the3236 `modulemeta` builtin.32373238 - title: "`modulemeta`"3239 body: |32403241 Takes a module name as input and outputs the module's metadata3242 as an object, with the module's imports (including metadata)3243 as an array value for the "deps" key.32443245 Programs can use this to query a module's metadata, which they3246 could then use to, for example, search for, download, and3247 install missing dependencies.32483249 - title: Colors3250 body: |32513252 To configure alternative colors just set the `JQ_COLORS`3253 environment variable to colon-delimited list of partial terminal3254 escape sequences like `"1;31"`, in this order:32553256 - color for `null`3257 - color for `false`3258 - color for `true`3259 - color for numbers3260 - color for strings3261 - color for arrays3262 - color for objects32633264 The default color scheme is the same as setting3265 `"JQ_COLORS=1;30:0;39:0;39:0;39:0;32:1;39:1;39"`.32663267 This is not a manual for VT100/ANSI escapes. However, each of3268 these color specifications should consist of two numbers separated3269 by a semi-colon, where the first number is one of these:32703271 - 1 (bright)3272 - 2 (dim)3273 - 4 (underscore)3274 - 5 (blink)3275 - 7 (reverse)3276 - 8 (hidden)32773278 and the second is one of these:32793280 - 30 (black)3281 - 31 (red)3282 - 32 (green)3283 - 33 (yellow)3284 - 34 (blue)3285 - 35 (magenta)3286 - 36 (cyan)3287 - 37 (white)
modified:docs/content/3.manual/manual.yml+3 added-2 removed
1 unmodified line
2headline: jq Manual (development version)34history: |56 *For released versions, see [jq 1.5](/jq/manual/v1.5),7 [jq 1.4](/jq/manual/v1.4) or [jq 1.3](/jq/manual/v1.3).*6 *For released versions, see [jq 1.6](/jq/manual/v1.6),7 [jq 1.5](/jq/manual/v1.5), [jq 1.4](/jq/manual/v1.4)8 or [jq 1.3](/jq/manual/v1.3).*910body: |1112 A jq program is a "filter": it takes an input, and produces an
3276 unmodified lines
modified:docs/content/index/index.yml+6 added
31 unmodified lines
32 [#jq](http://irc.lc/freenode/%23jq/) channel on33 [Freenode](https://webchat.freenode.net/).3435news:36 - date: 1 November 201837 body: |38 jq 1.6 released. See installation options on the [download](/jq/download/)39 page, and the [release notes](https://github.com/stedolan/jq/releases/tag/jq-1.6)40 for details.4142 - date: 15 August 201543 body: |4445 jq 1.5 released, including new datetime, math, and regexp functions,
28 unmodified lines