website: Make latest release (1.7) be default manual (#3130)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fixes issue with confusion about features that has not been released yet. Move deveopment manual.yml to dev/manual.yml Symlink manual.yml to v1.7/manual.yml Refactor to share history header with links to other manual versions. Change man.test and man page generation to use dev/manual.yml Related to #3078 #3127
authored by Mattias Wadman · committed by GitHub · parent 2ee20ca · Browse files · 12 files·+3818 added−3840 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+3818 added−3840 removed
- other:+3818 added−3840 removed
Provenance
- Commit
c1d885b- Tree
97d1671- Author
Mattias Wadman <mattias.wadman@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
2ee20ca
12 files changed+3818 added−3840 removed
added:docs/content/manual/dev/manual.yml+3800 added
1+---2+headline: jq Manual (development version)3+4+body: |5+6+ A jq program is a "filter": it takes an input, and produces an7+ output. There are a lot of builtin filters for extracting a8+ particular field of an object, or converting a number to a string,9+ or various other standard tasks.10+11+ Filters can be combined in various ways - you can pipe the output of12+ one filter into another filter, or collect the output of a filter13+ into an array.14+15+ Some filters produce multiple results, for instance there's one that16+ produces all the elements of its input array. Piping that filter17+ into a second runs the second filter for each element of the18+ array. Generally, things that would be done with loops and iteration19+ in other languages are just done by gluing filters together in jq.20+21+ It's important to remember that every filter has an input and an22+ output. Even literals like "hello" or 42 are filters - they take an23+ input but always produce the same literal as output. Operations that24+ combine two filters, like addition, generally feed the same input to25+ both and combine the results. So, you can implement an averaging26+ filter as `add / length` - feeding the input array both to the `add`27+ filter and the `length` filter and then performing the division.28+29+ But that's getting ahead of ourselves. :) Let's start with something30+ simpler:31+32+manpage_intro: |33+ jq(1) -- Command-line JSON processor34+ ====================================35+36+ ## SYNOPSIS37+38+ `jq` [<options>...] <filter> [<files>...]39+40+ `jq` can transform JSON in various ways, by selecting, iterating,41+ reducing and otherwise mangling JSON documents. For instance,42+ running the command `jq 'map(.price) | add'` will take an array of43+ JSON objects as input and return the sum of their "price" fields.44+45+ `jq` can accept text input as well, but by default, `jq` reads a46+ stream of JSON entities (including numbers and other literals) from47+ `stdin`. Whitespace is only needed to separate entities such as 148+ and 2, and true and false. One or more <files> may be specified, in49+ which case `jq` will read input from those instead.50+51+ The <options> are described in the [INVOKING JQ] section; they52+ mostly concern input and output formatting. The <filter> is written53+ in the jq language and specifies how to transform the input54+ file or document.55+56+ ## FILTERS57+58+manpage_epilogue: |59+ ## BUGS60+61+ Presumably. Report them or discuss them at:62+63+ https://github.com/jqlang/jq/issues64+65+ ## AUTHOR66+67+ Stephen Dolan `<mu@netsoc.tcd.ie>`68+69+sections:70+ - title: Invoking jq71+ body: |72+73+ jq filters run on a stream of JSON data. The input to jq is74+ parsed as a sequence of whitespace-separated JSON values which75+ are passed through the provided filter one at a time. The76+ output(s) of the filter are written to standard output, as a77+ sequence of newline-separated JSON data.78+79+ The simplest and most common filter (or jq program) is `.`,80+ which is the identity operator, copying the inputs of the jq81+ processor to the output stream. Because the default behavior of82+ the jq processor is to read JSON texts from the input stream,83+ and to pretty-print outputs, the `.` program's main use is to84+ validate and pretty-print the inputs. The jq programming85+ language is quite rich and allows for much more than just86+ validation and pretty-printing.87+88+ Note: it is important to mind the shell's quoting rules. As a89+ general rule it's best to always quote (with single-quote90+ characters on Unix shells) the jq program, as too many characters with special91+ meaning to jq are also shell meta-characters. For example, `jq92+ "foo"` will fail on most Unix shells because that will be the same93+ as `jq foo`, which will generally fail because `foo is not94+ defined`. When using the Windows command shell (cmd.exe) it's95+ best to use double quotes around your jq program when given on the96+ command-line (instead of the `-f program-file` option), but then97+ double-quotes in the jq program need backslash escaping. When using98+ the Powershell (`powershell.exe`) or the Powershell Core99+ (`pwsh`/`pwsh.exe`), use single-quote characters around the jq100+ program and backslash-escaped double-quotes (`\"`) inside the jq101+ program.102+103+ * Unix shells: `jq '.["foo"]'`104+ * Powershell: `jq '.[\"foo\"]'`105+ * Windows command shell: `jq ".[\"foo\"]"`106+107+ Note: jq allows user-defined functions, but every jq program108+ must have a top-level expression.109+110+ You can affect how jq reads and writes its input and output111+ using some command-line options:112+113+ * `--null-input` / `-n`:114+115+ Don't read any input at all. Instead, the filter is run once116+ using `null` as the input. This is useful when using jq as a117+ simple calculator or to construct JSON data from scratch.118+119+ * `--raw-input` / `-R`:120+121+ Don't parse the input as JSON. Instead, each line of text is122+ passed to the filter as a string. If combined with `--slurp`,123+ then the entire input is passed to the filter as a single long124+ string.125+126+ * `--slurp` / `-s`:127+128+ Instead of running the filter for each JSON object in the129+ input, read the entire input stream into a large array and run130+ the filter just once.131+132+ * `--compact-output` / `-c`:133+134+ By default, jq pretty-prints JSON output. Using this option135+ will result in more compact output by instead putting each136+ JSON object on a single line.137+138+ * `--raw-output` / `-r`:139+140+ With this option, if the filter's result is a string then it141+ will be written directly to standard output rather than being142+ formatted as a JSON string with quotes. This can be useful for143+ making jq filters talk to non-JSON-based systems.144+145+ * `--raw-output0`:146+147+ Like `-r` but jq will print NUL instead of newline after each output.148+ This can be useful when the values being output can contain newlines.149+ When the output value contains NUL, jq exits with non-zero code.150+151+ * `--join-output` / `-j`:152+153+ Like `-r` but jq won't print a newline after each output.154+155+ * `--ascii-output` / `-a`:156+157+ jq usually outputs non-ASCII Unicode codepoints as UTF-8, even158+ if the input specified them as escape sequences (like159+ "\u03bc"). Using this option, you can force jq to produce pure160+ ASCII output with every non-ASCII character replaced with the161+ equivalent escape sequence.162+163+ * `--sort-keys` / `-S`:164+165+ Output the fields of each object with the keys in sorted order.166+167+ * `--color-output` / `-C` and `--monochrome-output` / `-M`:168+169+ By default, jq outputs colored JSON if writing to a170+ terminal. You can force it to produce color even if writing to171+ a pipe or a file using `-C`, and disable color with `-M`.172+ When the `NO_COLOR` environment variable is not empty, jq disables173+ colored output by default, but you can enable it by `-C`.174+175+ Colors can be configured with the `JQ_COLORS` environment176+ variable (see below).177+178+ * `--tab`:179+180+ Use a tab for each indentation level instead of two spaces.181+182+ * `--indent n`:183+184+ Use the given number of spaces (no more than 7) for indentation.185+186+ * `--unbuffered`:187+188+ Flush the output after each JSON object is printed (useful if189+ you're piping a slow data source into jq and piping jq's190+ output elsewhere).191+192+ * `--stream`:193+194+ Parse the input in streaming fashion, outputting arrays of path195+ and leaf values (scalars and empty arrays or empty objects).196+ For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]`197+ becomes `[[0],[]]`, `[[1],"a"]`, and `[[2,0],"b"]`.198+199+ This is useful for processing very large inputs. Use this in200+ conjunction with filtering and the `reduce` and `foreach` syntax201+ to reduce large inputs incrementally.202+203+ * `--stream-errors`:204+205+ Like `--stream`, but invalid JSON inputs yield array values206+ where the first element is the error and the second is a path.207+ For example, `["a",n]` produces `["Invalid literal at line 1,208+ column 7",[1]]`.209+210+ Implies `--stream`. Invalid JSON inputs produce no error values211+ when `--stream` without `--stream-errors`.212+213+ * `--seq`:214+215+ Use the `application/json-seq` MIME type scheme for separating216+ JSON texts in jq's input and output. This means that an ASCII217+ RS (record separator) character is printed before each value on218+ output and an ASCII LF (line feed) is printed after every219+ output. Input JSON texts that fail to parse are ignored (but220+ warned about), discarding all subsequent input until the next221+ RS. This mode also parses the output of jq without the `--seq`222+ option.223+224+ * `-f filename` / `--from-file filename`:225+226+ Read filter from the file rather than from a command line, like227+ awk's -f option.228+229+ * `-L directory`:230+231+ Prepend `directory` to the search list for modules. If this232+ option is used then no builtin search list is used. See the233+ section on modules below.234+235+ * `--arg name value`:236+237+ This option passes a value to the jq program as a predefined238+ variable. If you run jq with `--arg foo bar`, then `$foo` is239+ available in the program and has the value `"bar"`. Note that240+ `value` will be treated as a string, so `--arg foo 123` will241+ bind `$foo` to `"123"`.242+243+ Named arguments are also available to the jq program as244+ `$ARGS.named`.245+246+ * `--argjson name JSON-text`:247+248+ This option passes a JSON-encoded value to the jq program as a249+ predefined variable. If you run jq with `--argjson foo 123`, then250+ `$foo` is available in the program and has the value `123`.251+252+ * `--slurpfile variable-name filename`:253+254+ This option reads all the JSON texts in the named file and binds255+ an array of the parsed JSON values to the given global variable.256+ If you run jq with `--slurpfile foo bar`, then `$foo` is available257+ in the program and has an array whose elements correspond to the258+ texts in the file named `bar`.259+260+ * `--rawfile variable-name filename`:261+262+ This option reads in the named file and binds its contents to the given263+ global variable. If you run jq with `--rawfile foo bar`, then `$foo` is264+ available in the program and has a string whose contents are to the texts265+ in the file named `bar`.266+267+ * `--args`:268+269+ Remaining arguments are positional string arguments. These are270+ available to the jq program as `$ARGS.positional[]`.271+272+ * `--jsonargs`:273+274+ Remaining arguments are positional JSON text arguments. These275+ are available to the jq program as `$ARGS.positional[]`.276+277+ * `--exit-status` / `-e`:278+279+ Sets the exit status of jq to 0 if the last output value was280+ neither `false` nor `null`, 1 if the last output value was281+ either `false` or `null`, or 4 if no valid result was ever282+ produced. Normally jq exits with 2 if there was any usage283+ problem or system error, 3 if there was a jq program compile284+ error, or 0 if the jq program ran.285+286+ Another way to set the exit status is with the `halt_error`287+ builtin function.288+289+ * `--binary` / `-b`:290+291+ Windows users using WSL, MSYS2, or Cygwin, should use this option292+ when using a native jq.exe, otherwise jq will turn newlines (LFs)293+ into carriage-return-then-newline (CRLF).294+295+ * `--version` / `-V`:296+297+ Output the jq version and exit with zero.298+299+ * `--build-configuration`:300+301+ Output the build configuration of jq and exit with zero.302+ This output has no supported format or structure and may change303+ without notice in future releases.304+305+ * `--help` / `-h`:306+307+ Output the jq help and exit with zero.308+309+ * `--`:310+311+ Terminates argument processing. Remaining arguments are not312+ interpreted as options.313+314+ * `--run-tests [filename]`:315+316+ Runs the tests in the given file or standard input. This must317+ be the last option given and does not honor all preceding318+ options. The input consists of comment lines, empty lines, and319+ program lines followed by one input line, as many lines of320+ output as are expected (one per output), and a terminating empty321+ line. Compilation failure tests start with a line containing322+ only `%%FAIL`, then a line containing the program to compile,323+ then a line containing an error message to compare to the324+ actual.325+326+ Be warned that this option can change backwards-incompatibly.327+328+ - title: Basic filters329+ entries:330+ - title: "Identity: `.`"331+ body: |332+333+ The absolute simplest filter is `.` . This filter takes its334+ input and produces the same value as output. That is, this335+ is the identity operator.336+337+ Since jq by default pretty-prints all output, a trivial338+ program consisting of nothing but `.` can be used to format339+ JSON output from, say, `curl`.340+341+ Although the identity filter never modifies the value of its342+ input, jq processing can sometimes make it appear as though343+ it does. For example, using the current implementation of344+ jq, we would see that the expression:345+346+ 1E1234567890 | .347+348+ produces `1.7976931348623157e+308` on at least one platform.349+ This is because, in the process of parsing the number, this350+ particular version of jq has converted it to an IEEE754351+ double-precision representation, losing precision.352+353+ The way in which jq handles numbers has changed over time354+ and further changes are likely within the parameters set by355+ the relevant JSON standards. Moreover, build configuration356+ options can alter how jq processes numbers.357+358+ The following remarks are therefore offered with the359+ understanding that they are intended to be descriptive of the360+ current version of jq and should not be interpreted as being361+ prescriptive:362+363+ (1) Any arithmetic operation on a number that has not364+ already been converted to an IEEE754 double precision365+ representation will trigger a conversion to the IEEE754366+ representation.367+368+ (2) jq will attempt to maintain the original decimal369+ precision of number literals (if the `--disable-decnum`370+ build configuration option was not used), but in expressions371+ such `1E1234567890`, precision will be lost if the exponent372+ is too large.373+374+ (3) In jq programs, a leading minus sign will trigger the375+ conversion of the number to an IEEE754 representation.376+377+ (4) Comparisons are carried out using the untruncated378+ big decimal representation of numbers if available, as379+ illustrated in one of the following examples.380+381+ The examples below use the builtin function `have_decnum` in382+ order to demonstrate the expected effects of using / not383+ using the `--disable-decnum` build configuration option, and384+ also to allow automated tests derived from these examples to385+ pass regardless of whether that option is used.386+387+ examples:388+ - program: '.'389+ input: '"Hello, world!"'390+ output: ['"Hello, world!"']391+392+ - program: '.'393+ input: '0.12345678901234567890123456789'394+ output: ['0.12345678901234567890123456789']395+396+ - program: '[., tojson] | . == if have_decnum then [12345678909876543212345,"12345678909876543212345"] else [12345678909876543000000,"12345678909876543000000"] end'397+ input: '12345678909876543212345'398+ output: ['true']399+400+ - program: '. < 0.12345678901234567890123456788'401+ input: '0.12345678901234567890123456789'402+ output: ['false']403+404+ - program: 'map([., . == 1]) | tojson | . == if have_decnum then "[[1,true],[1.000,true],[1.0,true],[1.00,true]]" else "[[1,true],[1,true],[1,true],[1,true]]" end'405+ input: '[1, 1.000, 1.0, 100e-2]'406+ output: ['true']407+408+ - program: '. as $big | [$big, $big + 1] | map(. > 10000000000000000000000000000000) | . == if have_decnum then [true, false] else [false, false] end'409+ input: '10000000000000000000000000000001'410+ output: ['true']411+412+ - title: "Object Identifier-Index: `.foo`, `.foo.bar`"413+ body: |414+415+ The simplest *useful* filter has the form `.foo`. When given a416+ JSON object (aka dictionary or hash) as input, `.foo` produces417+ the value at the key "foo" if the key is present, or null otherwise.418+419+ A filter of the form `.foo.bar` is equivalent to `.foo | .bar`.420+421+ The `.foo` syntax only works for simple, identifier-like keys, that422+ is, keys that are all made of alphanumeric characters and423+ underscore, and which do not start with a digit.424+425+ If the key contains special characters or starts with a digit,426+ you need to surround it with double quotes like this:427+ `."foo$"`, or else `.["foo$"]`.428+429+ For example `.["foo::bar"]` and `.["foo.bar"]` work while430+ `.foo::bar` does not.431+432+ examples:433+ - program: '.foo'434+ input: '{"foo": 42, "bar": "less interesting data"}'435+ output: ['42']436+437+ - program: '.foo'438+ input: '{"notfoo": true, "alsonotfoo": false}'439+ output: ['null']440+441+ - program: '.["foo"]'442+ input: '{"foo": 42}'443+ output: ['42']444+445+ - title: "Optional Object Identifier-Index: `.foo?`"446+ body: |447+448+ Just like `.foo`, but does not output an error when `.` is not an449+ object.450+451+ examples:452+ - program: '.foo?'453+ input: '{"foo": 42, "bar": "less interesting data"}'454+ output: ['42']455+ - program: '.foo?'456+ input: '{"notfoo": true, "alsonotfoo": false}'457+ output: ['null']458+ - program: '.["foo"]?'459+ input: '{"foo": 42}'460+ output: ['42']461+ - program: '[.foo?]'462+ input: '[1,2]'463+ output: ['[]']464+465+ - title: "Object Index: `.[<string>]`"466+ body: |467+468+ You can also look up fields of an object using syntax like469+ `.["foo"]` (`.foo` above is a shorthand version of this, but470+ only for identifier-like strings).471+472+ - title: "Array Index: `.[<number>]`"473+ body: |474+475+ When the index value is an integer, `.[<number>]` can index476+ arrays. Arrays are zero-based, so `.[2]` returns the third477+ element.478+479+ Negative indices are allowed, with -1 referring to the last480+ element, -2 referring to the next to last element, and so on.481+482+ examples:483+ - program: '.[0]'484+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'485+ output: ['{"name":"JSON", "good":true}']486+487+ - program: '.[2]'488+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'489+ output: ['null']490+491+ - program: '.[-2]'492+ input: '[1,2,3]'493+ output: ['2']494+495+ - title: "Array/String Slice: `.[<number>:<number>]`"496+ body: |497+498+ The `.[<number>:<number>]` syntax can be used to return a499+ subarray of an array or substring of a string. The array500+ returned by `.[10:15]` will be of length 5, containing the501+ elements from index 10 (inclusive) to index 15 (exclusive).502+ Either index may be negative (in which case it counts503+ backwards from the end of the array), or omitted (in which504+ case it refers to the start or end of the array).505+ Indices are zero-based.506+507+ examples:508+ - program: '.[2:4]'509+ input: '["a","b","c","d","e"]'510+ output: ['["c", "d"]']511+512+ - program: '.[2:4]'513+ input: '"abcdefghi"'514+ output: ['"cd"']515+516+ - program: '.[:3]'517+ input: '["a","b","c","d","e"]'518+ output: ['["a", "b", "c"]']519+520+ - program: '.[-2:]'521+ input: '["a","b","c","d","e"]'522+ output: ['["d", "e"]']523+524+ - title: "Array/Object Value Iterator: `.[]`"525+ body: |526+527+ If you use the `.[index]` syntax, but omit the index528+ entirely, it will return *all* of the elements of an529+ array. Running `.[]` with the input `[1,2,3]` will produce the530+ numbers as three separate results, rather than as a single531+ array. A filter of the form `.foo[]` is equivalent to532+ `.foo | .[]`.533+534+ You can also use this on an object, and it will return all535+ the values of the object.536+537+ Note that the iterator operator is a generator of values.538+539+ examples:540+ - program: '.[]'541+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'542+ output:543+ - '{"name":"JSON", "good":true}'544+ - '{"name":"XML", "good":false}'545+546+ - program: '.[]'547+ input: '[]'548+ output: []549+550+ - program: '.foo[]'551+ input: '{"foo":[1,2,3]}'552+ output: ['1','2','3']553+554+ - program: '.[]'555+ input: '{"a": 1, "b": 1}'556+ output: ['1', '1']557+558+ - title: "`.[]?`"559+ body: |560+561+ Like `.[]`, but no errors will be output if . is not an array562+ or object. A filter of the form `.foo[]?` is equivalent to563+ `.foo | .[]?`.564+565+ - title: "Comma: `,`"566+ body: |567+568+ If two filters are separated by a comma, then the569+ same input will be fed into both and the two filters' output570+ value streams will be concatenated in order: first, all of the571+ outputs produced by the left expression, and then all of the572+ outputs produced by the right. For instance, filter `.foo,573+ .bar`, produces both the "foo" fields and "bar" fields as574+ separate outputs.575+576+ The `,` operator is one way to construct generators.577+578+ examples:579+ - program: '.foo, .bar'580+ input: '{"foo": 42, "bar": "something else", "baz": true}'581+ output: ['42', '"something else"']582+583+ - program: ".user, .projects[]"584+ input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'585+ output: ['"stedolan"', '"jq"', '"wikiflow"']586+587+ - program: '.[4,2]'588+ input: '["a","b","c","d","e"]'589+ output: ['"e"', '"c"']590+591+ - title: "Pipe: `|`"592+ body: |593+594+ The | operator combines two filters by feeding the output(s) of595+ the one on the left into the input of the one on the right. It's596+ similar to the Unix shell's pipe, if you're used to that.597+598+ If the one on the left produces multiple results, the one on599+ the right will be run for each of those results. So, the600+ expression `.[] | .foo` retrieves the "foo" field of each601+ element of the input array. This is a cartesian product,602+ which can be surprising.603+604+ Note that `.a.b.c` is the same as `.a | .b | .c`.605+606+ Note too that `.` is the input value at the particular stage607+ in a "pipeline", specifically: where the `.` expression appears.608+ Thus `.a | . | .b` is the same as `.a.b`, as the `.` in the609+ middle refers to whatever value `.a` produced.610+611+ examples:612+ - program: '.[] | .name'613+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'614+ output: ['"JSON"', '"XML"']615+616+ - title: "Parenthesis"617+ body: |618+619+ Parenthesis work as a grouping operator just as in any typical620+ programming language.621+622+ examples:623+ - program: '(. + 2) * 5'624+ input: '1'625+ output: ['15']626+627+ - title: Types and Values628+ body: |629+630+ jq supports the same set of datatypes as JSON - numbers,631+ strings, booleans, arrays, objects (which in JSON-speak are632+ hashes with only string keys), and "null".633+634+ Booleans, null, strings and numbers are written the same way as635+ in JSON. Just like everything else in jq, these simple636+ values take an input and produce an output - `42` is a valid jq637+ expression that takes an input, ignores it, and returns 42638+ instead.639+640+ Numbers in jq are internally represented by their IEEE754 double641+ precision approximation. Any arithmetic operation with numbers,642+ whether they are literals or results of previous filters, will643+ produce a double precision floating point result.644+645+ However, when parsing a literal jq will store the original literal646+ string. If no mutation is applied to this value then it will make647+ to the output in its original form, even if conversion to double648+ would result in a loss.649+650+ entries:651+ - title: "Array construction: `[]`"652+ body: |653+654+ As in JSON, `[]` is used to construct arrays, as in655+ `[1,2,3]`. The elements of the arrays can be any jq656+ expression, including a pipeline. All of the results produced657+ by all of the expressions are collected into one big array.658+ You can use it to construct an array out of a known quantity659+ of values (as in `[.foo, .bar, .baz]`) or to "collect" all the660+ results of a filter into an array (as in `[.items[].name]`)661+662+ Once you understand the "," operator, you can look at jq's array663+ syntax in a different light: the expression `[1,2,3]` is not using a664+ built-in syntax for comma-separated arrays, but is instead applying665+ the `[]` operator (collect results) to the expression 1,2,3 (which666+ produces three different results).667+668+ If you have a filter `X` that produces four results,669+ then the expression `[X]` will produce a single result, an670+ array of four elements.671+672+ examples:673+ - program: "[.user, .projects[]]"674+ input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'675+ output: ['["stedolan", "jq", "wikiflow"]']676+ - program: "[ .[] | . * 2]"677+ input: '[1, 2, 3]'678+ output: ['[2, 4, 6]']679+680+ - title: "Object Construction: `{}`"681+ body: |682+683+ Like JSON, `{}` is for constructing objects (aka684+ dictionaries or hashes), as in: `{"a": 42, "b": 17}`.685+686+ If the keys are "identifier-like", then the quotes can be left687+ off, as in `{a:42, b:17}`. Variable references as key688+ expressions use the value of the variable as the key. Key689+ expressions other than constant literals, identifiers, or690+ variable references, need to be parenthesized, e.g.,691+ `{("a"+"b"):59}`.692+693+ The value can be any expression (although you may need to wrap694+ it in parentheses if, for example, it contains colons), which695+ gets applied to the {} expression's input (remember, all696+ filters have an input and an output).697+698+ {foo: .bar}699+700+ will produce the JSON object `{"foo": 42}` if given the JSON701+ object `{"bar":42, "baz":43}` as its input. You can use this702+ to select particular fields of an object: if the input is an703+ object with "user", "title", "id", and "content" fields and704+ you just want "user" and "title", you can write705+706+ {user: .user, title: .title}707+708+ Because that is so common, there's a shortcut syntax for it:709+ `{user, title}`.710+711+ If one of the expressions produces multiple results,712+ multiple dictionaries will be produced. If the input's713+714+ {"user":"stedolan","titles":["JQ Primer", "More JQ"]}715+716+ then the expression717+718+ {user, title: .titles[]}719+720+ will produce two outputs:721+722+ {"user":"stedolan", "title": "JQ Primer"}723+ {"user":"stedolan", "title": "More JQ"}724+725+ Putting parentheses around the key means it will be evaluated as an726+ expression. With the same input as above,727+728+ {(.user): .titles}729+730+ produces731+732+ {"stedolan": ["JQ Primer", "More JQ"]}733+734+ Variable references as keys use the value of the variable as735+ the key. Without a value then the variable's name becomes the736+ key and its value becomes the value,737+738+ "f o o" as $foo | "b a r" as $bar | {$foo, $bar:$foo}739+740+ produces741+742+ {"foo":"f o o","b a r":"f o o"}743+744+ examples:745+ - program: '{user, title: .titles[]}'746+ input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'747+ output:748+ - '{"user":"stedolan", "title": "JQ Primer"}'749+ - '{"user":"stedolan", "title": "More JQ"}'750+ - program: '{(.user): .titles}'751+ input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'752+ output: ['{"stedolan": ["JQ Primer", "More JQ"]}']753+754+ - title: "Recursive Descent: `..`"755+ body: |756+757+ Recursively descends `.`, producing every value. This is the758+ same as the zero-argument `recurse` builtin (see below). This759+ is intended to resemble the XPath `//` operator. Note that760+ `..a` does not work; use `.. | .a` instead. In the example761+ below we use `.. | .a?` to find all the values of object keys762+ "a" in any object found "below" `.`.763+764+ This is particularly useful in conjunction with `path(EXP)`765+ (also see below) and the `?` operator.766+767+ examples:768+ - program: '.. | .a?'769+ input: '[[{"a":1}]]'770+ output: ['1']771+772+ - title: Builtin operators and functions773+ body: |774+775+ Some jq operators (for instance, `+`) do different things776+ depending on the type of their arguments (arrays, numbers,777+ etc.). However, jq never does implicit type conversions. If you778+ try to add a string to an object you'll get an error message and779+ no result.780+781+ Please note that all numbers are converted to IEEE754 double precision782+ floating point representation. Arithmetic and logical operators are working783+ with these converted doubles. Results of all such operations are also limited784+ to the double precision.785+786+ The only exception to this behaviour of number is a snapshot of original number787+ literal. When a number which originally was provided as a literal is never788+ mutated until the end of the program then it is printed to the output in its789+ original literal form. This also includes cases when the original literal790+ would be truncated when converted to the IEEE754 double precision floating point791+ number.792+793+ entries:794+ - title: "Addition: `+`"795+ body: |796+797+ The operator `+` takes two filters, applies them both798+ to the same input, and adds the results together. What799+ "adding" means depends on the types involved:800+801+ - **Numbers** are added by normal arithmetic.802+803+ - **Arrays** are added by being concatenated into a larger array.804+805+ - **Strings** are added by being joined into a larger string.806+807+ - **Objects** are added by merging, that is, inserting all808+ the key-value pairs from both objects into a single809+ combined object. If both objects contain a value for the810+ same key, the object on the right of the `+` wins. (For811+ recursive merge use the `*` operator.)812+813+ `null` can be added to any value, and returns the other814+ value unchanged.815+816+ examples:817+ - program: '.a + 1'818+ input: '{"a": 7}'819+ output: ['8']820+ - program: '.a + .b'821+ input: '{"a": [1,2], "b": [3,4]}'822+ output: ['[1,2,3,4]']823+ - program: '.a + null'824+ input: '{"a": 1}'825+ output: ['1']826+ - program: '.a + 1'827+ input: '{}'828+ output: ['1']829+ - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'830+ input: 'null'831+ output: ['{"a": 42, "b": 2, "c": 3}']832+833+ - title: "Subtraction: `-`"834+ body: |835+836+ As well as normal arithmetic subtraction on numbers, the `-`837+ operator can be used on arrays to remove all occurrences of838+ the second array's elements from the first array.839+840+ examples:841+ - program: '4 - .a'842+ input: '{"a":3}'843+ output: ['1']844+ - program: . - ["xml", "yaml"]845+ input: '["xml", "yaml", "json"]'846+ output: ['["json"]']847+848+ - title: "Multiplication, division, modulo: `*`, `/`, `%`"849+ body: |850+851+ These infix operators behave as expected when given two numbers.852+ Division by zero raises an error. `x % y` computes x modulo y.853+854+ Multiplying a string by a number produces the concatenation of855+ that string that many times. `"x" * 0` produces `""`.856+857+ Dividing a string by another splits the first using the second858+ as separators.859+860+ Multiplying two objects will merge them recursively: this works861+ like addition but if both objects contain a value for the862+ same key, and the values are objects, the two are merged with863+ the same strategy.864+865+ examples:866+ - program: '10 / . * 3'867+ input: '5'868+ output: ['6']869+ - program: '. / ", "'870+ input: '"a, b,c,d, e"'871+ output: ['["a","b,c,d","e"]']872+ - program: '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'873+ input: 'null'874+ output: ['{"k": {"a": 0, "b": 2, "c": 3}}']875+ - program: '.[] | (1 / .)?'876+ input: '[1,0,-1]'877+ output: ['1', '-1']878+879+ - title: "`abs`"880+ body: |881+882+ The builtin function `abs` is defined naively as: `if . < 0 then - . else . end`.883+884+ For numeric input, this is the absolute value. See the885+ section on the identity filter for the implications of this886+ definition for numeric input.887+888+ To compute the absolute value of a number as a floating point number, you may wish use `fabs`.889+890+ examples:891+ - program: 'map(abs)'892+ input: '[-10, -1.1, -1e-1]'893+ output: ['[10,1.1,1e-1]']894+895+ - title: "`length`"896+ body: |897+898+ The builtin function `length` gets the length of various899+ different types of value:900+901+ - The length of a **string** is the number of Unicode902+ codepoints it contains (which will be the same as its903+ JSON-encoded length in bytes if it's pure ASCII).904+905+ - The length of a **number** is its absolute value.906+907+ - The length of an **array** is the number of elements.908+909+ - The length of an **object** is the number of key-value pairs.910+911+ - The length of **null** is zero.912+913+ - It is an error to use `length` on a **boolean**.914+915+ examples:916+ - program: '.[] | length'917+ input: '[[1,2], "string", {"a":2}, null, -5]'918+ output: ['2', '6', '1', '0', '5']919+920+921+ - title: "`utf8bytelength`"922+ body: |923+924+ The builtin function `utf8bytelength` outputs the number of925+ bytes used to encode a string in UTF-8.926+927+ examples:928+ - program: 'utf8bytelength'929+ input: '"\u03bc"'930+ output: ['2']931+932+ - title: "`keys`, `keys_unsorted`"933+ body: |934+935+ The builtin function `keys`, when given an object, returns936+ its keys in an array.937+938+ The keys are sorted "alphabetically", by unicode codepoint939+ order. This is not an order that makes particular sense in940+ any particular language, but you can count on it being the941+ same for any two objects with the same set of keys,942+ regardless of locale settings.943+944+ When `keys` is given an array, it returns the valid indices945+ for that array: the integers from 0 to length-1.946+947+ The `keys_unsorted` function is just like `keys`, but if948+ the input is an object then the keys will not be sorted,949+ instead the keys will roughly be in insertion order.950+951+ examples:952+ - program: 'keys'953+ input: '{"abc": 1, "abcd": 2, "Foo": 3}'954+ output: ['["Foo", "abc", "abcd"]']955+ - program: 'keys'956+ input: '[42,3,35]'957+ output: ['[0,1,2]']958+959+ - title: "`has(key)`"960+ body: |961+962+ The builtin function `has` returns whether the input object963+ has the given key, or the input array has an element at the964+ given index.965+966+ `has($key)` has the same effect as checking whether `$key`967+ is a member of the array returned by `keys`, although `has`968+ will be faster.969+970+ examples:971+ - program: 'map(has("foo"))'972+ input: '[{"foo": 42}, {}]'973+ output: ['[true, false]']974+ - program: 'map(has(2))'975+ input: '[[0,1], ["a","b","c"]]'976+ output: ['[false, true]']977+978+ - title: "`in`"979+ body: |980+981+ The builtin function `in` returns whether or not the input key is in the982+ given object, or the input index corresponds to an element983+ in the given array. It is, essentially, an inversed version984+ of `has`.985+986+ examples:987+ - program: '.[] | in({"foo": 42})'988+ input: '["foo", "bar"]'989+ output: ['true', 'false']990+ - program: 'map(in([0,1]))'991+ input: '[2, 0]'992+ output: ['[false, true]']993+994+ - title: "`map(f)`, `map_values(f)`"995+ body: |996+997+ For any filter `f`, `map(f)` and `map_values(f)` apply `f`998+ to each of the values in the input array or object, that is,999+ to the values of `.[]`.1000+1001+ In the absence of errors, `map(f)` always outputs an array1002+ whereas `map_values(f)` outputs an array if given an array,1003+ or an object if given an object.1004+1005+ When the input to `map_values(f)` is an object, the output1006+ object has the same keys as the input object except for1007+ those keys whose values when piped to `f` produce no values1008+ at all.1009+1010+ The key difference between `map(f)` and `map_values(f)` is1011+ that the former simply forms an array from all the values of1012+ `($x|f)` for each value, $x, in the input array or object,1013+ but `map_values(f)` only uses `first($x|f)`.1014+1015+ Specifically, for object inputs, `map_values(f)` constructs1016+ the output object by examining in turn the value of1017+ `first(.[$k]|f)` for each key, $k, of the input. If this1018+ expression produces no values, then the corresponding key1019+ will be dropped; otherwise, the output object will have that1020+ value at the key, $k.1021+1022+ Here are some examples to clarify the behavior of `map` and1023+ `map_values` when applied to arrays. These examples assume the1024+ input is `[1]` in all cases:1025+1026+ map(.+1) #=> [2]1027+ map(., .) #=> [1,1]1028+ map(empty) #=> []1029+1030+ map_values(.+1) #=> [2]1031+ map_values(., .) #=> [1]1032+ map_values(empty) #=> []1033+1034+ `map(f)` is equivalent to `[.[] | f]` and1035+ `map_values(f)` is equivalent to `.[] |= f`.1036+1037+ In fact, these are their implementations.1038+1039+1040+ examples:1041+ - program: 'map(.+1)'1042+ input: '[1,2,3]'1043+ output: ['[2,3,4]']1044+1045+ - program: 'map_values(.+1)'1046+ input: '{"a": 1, "b": 2, "c": 3}'1047+ output: ['{"a": 2, "b": 3, "c": 4}']1048+1049+ - program: 'map(., .)'1050+ input: '[1,2]'1051+ output: ['[1,1,2,2]']1052+1053+ - program: 'map_values(. // empty)'1054+ input: '{"a": null, "b": true, "c": false}'1055+ output: ['{"b":true}']1056+1057+1058+ - title: "`pick(pathexps)`"1059+ body: |1060+1061+ Emit the projection of the input object or array defined by the1062+ specified sequence of path expressions, such that if `p` is any1063+ one of these specifications, then `(. | p)` will evaluate to the1064+ same value as `(. | pick(pathexps) | p)`. For arrays, negative1065+ indices and `.[m:n]` specifications should not be used.1066+1067+ examples:1068+ - program: 'pick(.a, .b.c, .x)'1069+ input: '{"a": 1, "b": {"c": 2, "d": 3}, "e": 4}'1070+ output: ['{"a":1,"b":{"c":2},"x":null}']1071+1072+ - program: 'pick(.[2], .[0], .[0])'1073+ input: '[1,2,3,4]'1074+ output: ['[1,null,3]']1075+1076+1077+ - title: "`path(path_expression)`"1078+ body: |1079+1080+ Outputs array representations of the given path expression1081+ in `.`. The outputs are arrays of strings (object keys)1082+ and/or numbers (array indices).1083+1084+ Path expressions are jq expressions like `.a`, but also `.[]`.1085+ There are two types of path expressions: ones that can match1086+ exactly, and ones that cannot. For example, `.a.b.c` is an1087+ exact match path expression, while `.a[].b` is not.1088+1089+ `path(exact_path_expression)` will produce the array1090+ representation of the path expression even if it does not1091+ exist in `.`, if `.` is `null` or an array or an object.1092+1093+ `path(pattern)` will produce array representations of the1094+ paths matching `pattern` if the paths exist in `.`.1095+1096+ Note that the path expressions are not different from normal1097+ expressions. The expression1098+ `path(..|select(type=="boolean"))` outputs all the paths to1099+ boolean values in `.`, and only those paths.1100+1101+ examples:1102+ - program: 'path(.a[0].b)'1103+ input: 'null'1104+ output: ['["a",0,"b"]']1105+ - program: '[path(..)]'1106+ input: '{"a":[{"b":1}]}'1107+ output: ['[[],["a"],["a",0],["a",0,"b"]]']1108+1109+ - title: "`del(path_expression)`"1110+ body: |1111+1112+ The builtin function `del` removes a key and its corresponding1113+ value from an object.1114+1115+ examples:1116+ - program: 'del(.foo)'1117+ input: '{"foo": 42, "bar": 9001, "baz": 42}'1118+ output: ['{"bar": 9001, "baz": 42}']1119+ - program: 'del(.[1, 2])'1120+ input: '["foo", "bar", "baz"]'1121+ output: ['["foo"]']1122+1123+ - title: "`getpath(PATHS)`"1124+ body: |1125+1126+ The builtin function `getpath` outputs the values in `.` found1127+ at each path in `PATHS`.1128+1129+ examples:1130+ - program: 'getpath(["a","b"])'1131+ input: 'null'1132+ output: ['null']1133+ - program: '[getpath(["a","b"], ["a","c"])]'1134+ input: '{"a":{"b":0, "c":1}}'1135+ output: ['[0, 1]']1136+1137+ - title: "`setpath(PATHS; VALUE)`"1138+ body: |1139+1140+ The builtin function `setpath` sets the `PATHS` in `.` to `VALUE`.1141+1142+ examples:1143+ - program: 'setpath(["a","b"]; 1)'1144+ input: 'null'1145+ output: ['{"a": {"b": 1}}']1146+ - program: 'setpath(["a","b"]; 1)'1147+ input: '{"a":{"b":0}}'1148+ output: ['{"a": {"b": 1}}']1149+ - program: 'setpath([0,"a"]; 1)'1150+ input: 'null'1151+ output: ['[{"a":1}]']1152+1153+ - title: "`delpaths(PATHS)`"1154+ body: |1155+1156+ The builtin function `delpaths` deletes the `PATHS` in `.`.1157+ `PATHS` must be an array of paths, where each path is an array1158+ of strings and numbers.1159+1160+ examples:1161+ - program: 'delpaths([["a","b"]])'1162+ input: '{"a":{"b":1},"x":{"y":2}}'1163+ output: ['{"a":{},"x":{"y":2}}']1164+1165+ - title: "`to_entries`, `from_entries`, `with_entries(f)`"1166+ body: |1167+1168+ These functions convert between an object and an array of1169+ key-value pairs. If `to_entries` is passed an object, then1170+ for each `k: v` entry in the input, the output array1171+ includes `{"key": k, "value": v}`.1172+1173+ `from_entries` does the opposite conversion, and `with_entries(f)`1174+ is a shorthand for `to_entries | map(f) | from_entries`, useful for1175+ doing some operation to all keys and values of an object.1176+ `from_entries` accepts `"key"`, `"Key"`, `"name"`, `"Name"`,1177+ `"value"`, and `"Value"` as keys.1178+1179+ examples:1180+ - program: 'to_entries'1181+ input: '{"a": 1, "b": 2}'1182+ output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']1183+ - program: 'from_entries'1184+ input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'1185+ output: ['{"a": 1, "b": 2}']1186+ - program: 'with_entries(.key |= "KEY_" + .)'1187+ input: '{"a": 1, "b": 2}'1188+ output: ['{"KEY_a": 1, "KEY_b": 2}']1189+1190+1191+ - title: "`select(boolean_expression)`"1192+ body: |1193+1194+ The function `select(f)` produces its input unchanged if1195+ `f` returns true for that input, and produces no output1196+ otherwise.1197+1198+ It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`1199+ will give you `[2,3]`.1200+1201+ examples:1202+ - program: 'map(select(. >= 2))'1203+ input: '[1,5,3,0,7]'1204+ output: ['[5,3,7]']1205+ - program: '.[] | select(.id == "second")'1206+ input: '[{"id": "first", "val": 1}, {"id": "second", "val": 2}]'1207+ output: ['{"id": "second", "val": 2}']1208+1209+1210+ - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"1211+ body: |1212+1213+ These built-ins select only inputs that are arrays, objects,1214+ iterables (arrays or objects), booleans, numbers, normal1215+ numbers, finite numbers, strings, null, non-null values, and1216+ non-iterables, respectively.1217+1218+ examples:1219+ - program: '.[]|numbers'1220+ input: '[[],{},1,"foo",null,true,false]'1221+ output: ['1']1222+1223+ - title: "`empty`"1224+ body: |1225+1226+ `empty` returns no results. None at all. Not even `null`.1227+1228+ It's useful on occasion. You'll know if you need it :)1229+1230+ examples:1231+ - program: '1, empty, 2'1232+ input: 'null'1233+ output: ['1', '2']1234+ - program: '[1,2,empty,3]'1235+ input: 'null'1236+ output: ['[1,2,3]']1237+1238+ - title: "`error`, `error(message)`"1239+ body: |1240+1241+ Produces an error with the input value, or with the message1242+ given as the argument. Errors can be caught with try/catch;1243+ see below.1244+1245+ examples:1246+ - program: 'try error catch .'1247+ input: '"error message"'1248+ output: ['"error message"']1249+1250+ - program: 'try error("invalid value: \(.)") catch .'1251+ input: '42'1252+ output: ['"invalid value: 42"']1253+1254+ - title: "`halt`"1255+ body: |1256+1257+ Stops the jq program with no further outputs. jq will exit1258+ with exit status `0`.1259+1260+ - title: "`halt_error`, `halt_error(exit_code)`"1261+ body: |1262+1263+ Stops the jq program with no further outputs. The input will1264+ be printed on `stderr` as raw output (i.e., strings will not1265+ have double quotes) with no decoration, not even a newline.1266+1267+ The given `exit_code` (defaulting to `5`) will be jq's exit1268+ status.1269+1270+ For example, `"Error: something went wrong\n"|halt_error(1)`.1271+1272+ - title: "`$__loc__`"1273+ body: |1274+1275+ Produces an object with a "file" key and a "line" key, with1276+ the filename and line number where `$__loc__` occurs, as1277+ values.1278+1279+ examples:1280+ - program: 'try error("\($__loc__)") catch .'1281+ input: 'null'1282+ output: ['"{\"file\":\"<top-level>\",\"line\":1}"']1283+1284+ - title: "`paths`, `paths(node_filter)`"1285+ body: |1286+1287+ `paths` outputs the paths to all the elements in its input1288+ (except it does not output the empty list, representing .1289+ itself).1290+1291+ `paths(f)` outputs the paths to any values for which `f` is `true`.1292+ That is, `paths(type == "number")` outputs the paths to all numeric1293+ values.1294+1295+ examples:1296+ - program: '[paths]'1297+ input: '[1,[[],{"a":2}]]'1298+ output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']1299+ - program: '[paths(type == "number")]'1300+ input: '[1,[[],{"a":2}]]'1301+ output: ['[[0],[1,1,"a"]]']1302+1303+ - title: "`add`"1304+ body: |1305+1306+ The filter `add` takes as input an array, and produces as1307+ output the elements of the array added together. This might1308+ mean summed, concatenated or merged depending on the types1309+ of the elements of the input array - the rules are the same1310+ as those for the `+` operator (described above).1311+1312+ If the input is an empty array, `add` returns `null`.1313+1314+ examples:1315+ - program: add1316+ input: '["a","b","c"]'1317+ output: ['"abc"']1318+ - program: add1319+ input: '[1, 2, 3]'1320+ output: ['6']1321+ - program: add1322+ input: '[]'1323+ output: ["null"]1324+1325+ - title: "`any`, `any(condition)`, `any(generator; condition)`"1326+ body: |1327+1328+ The filter `any` takes as input an array of boolean values,1329+ and produces `true` as output if any of the elements of1330+ the array are `true`.1331+1332+ If the input is an empty array, `any` returns `false`.1333+1334+ The `any(condition)` form applies the given condition to the1335+ elements of the input array.1336+1337+ The `any(generator; condition)` form applies the given1338+ condition to all the outputs of the given generator.1339+1340+ examples:1341+ - program: any1342+ input: '[true, false]'1343+ output: ["true"]1344+ - program: any1345+ input: '[false, false]'1346+ output: ["false"]1347+ - program: any1348+ input: '[]'1349+ output: ["false"]1350+1351+ - title: "`all`, `all(condition)`, `all(generator; condition)`"1352+ body: |1353+1354+ The filter `all` takes as input an array of boolean values,1355+ and produces `true` as output if all of the elements of1356+ the array are `true`.1357+1358+ The `all(condition)` form applies the given condition to the1359+ elements of the input array.1360+1361+ The `all(generator; condition)` form applies the given1362+ condition to all the outputs of the given generator.1363+1364+ If the input is an empty array, `all` returns `true`.1365+1366+ examples:1367+ - program: all1368+ input: '[true, false]'1369+ output: ["false"]1370+ - program: all1371+ input: '[true, true]'1372+ output: ["true"]1373+ - program: all1374+ input: '[]'1375+ output: ["true"]1376+1377+ - title: "`flatten`, `flatten(depth)`"1378+ body: |1379+1380+ The filter `flatten` takes as input an array of nested arrays,1381+ and produces a flat array in which all arrays inside the original1382+ array have been recursively replaced by their values. You can pass1383+ an argument to it to specify how many levels of nesting to flatten.1384+1385+ `flatten(2)` is like `flatten`, but going only up to two1386+ levels deep.1387+1388+ examples:1389+ - program: flatten1390+ input: '[1, [2], [[3]]]'1391+ output: ["[1, 2, 3]"]1392+ - program: flatten(1)1393+ input: '[1, [2], [[3]]]'1394+ output: ["[1, 2, [3]]"]1395+ - program: flatten1396+ input: '[[]]'1397+ output: ["[]"]1398+ - program: flatten1399+ input: '[{"foo": "bar"}, [{"foo": "baz"}]]'1400+ output: ['[{"foo": "bar"}, {"foo": "baz"}]']1401+1402+ - title: "`range(upto)`, `range(from; upto)`, `range(from; upto; by)`"1403+ body: |1404+1405+ The `range` function produces a range of numbers. `range(4; 10)`1406+ produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers1407+ are produced as separate outputs. Use `[range(4; 10)]` to get a range as1408+ an array.1409+1410+ The one argument form generates numbers from 0 to the given1411+ number, with an increment of 1.1412+1413+ The two argument form generates numbers from `from` to `upto`1414+ with an increment of 1.1415+1416+ The three argument form generates numbers `from` to `upto`1417+ with an increment of `by`.1418+1419+ examples:1420+ - program: 'range(2; 4)'1421+ input: 'null'1422+ output: ['2', '3']1423+ - program: '[range(2; 4)]'1424+ input: 'null'1425+ output: ['[2,3]']1426+ - program: '[range(4)]'1427+ input: 'null'1428+ output: ['[0,1,2,3]']1429+ - program: '[range(0; 10; 3)]'1430+ input: 'null'1431+ output: ['[0,3,6,9]']1432+ - program: '[range(0; 10; -1)]'1433+ input: 'null'1434+ output: ['[]']1435+ - program: '[range(0; -5; -1)]'1436+ input: 'null'1437+ output: ['[0,-1,-2,-3,-4]']1438+1439+ - title: "`floor`"1440+ body: |1441+1442+ The `floor` function returns the floor of its numeric input.1443+1444+ examples:1445+ - program: 'floor'1446+ input: '3.14159'1447+ output: ['3']1448+1449+ - title: "`sqrt`"1450+ body: |1451+1452+ The `sqrt` function returns the square root of its numeric input.1453+1454+ examples:1455+ - program: 'sqrt'1456+ input: '9'1457+ output: ['3']1458+1459+ - title: "`tonumber`"1460+ body: |1461+1462+ The `tonumber` function parses its input as a number. It1463+ will convert correctly-formatted strings to their numeric1464+ equivalent, leave numbers alone, and give an error on all other input.1465+1466+ examples:1467+ - program: '.[] | tonumber'1468+ input: '[1, "1"]'1469+ output: ['1', '1']1470+1471+ - title: "`tostring`"1472+ body: |1473+1474+ The `tostring` function prints its input as a1475+ string. Strings are left unchanged, and all other values are1476+ JSON-encoded.1477+1478+ examples:1479+ - program: '.[] | tostring'1480+ input: '[1, "1", [1]]'1481+ output: ['"1"', '"1"', '"[1]"']1482+1483+ - title: "`type`"1484+ body: |1485+1486+ The `type` function returns the type of its argument as a1487+ string, which is one of null, boolean, number, string, array1488+ or object.1489+1490+ examples:1491+ - program: 'map(type)'1492+ input: '[0, false, [], {}, null, "hello"]'1493+ output: ['["number", "boolean", "array", "object", "null", "string"]']1494+1495+ - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1496+ body: |1497+1498+ Some arithmetic operations can yield infinities and "not a1499+ number" (NaN) values. The `isinfinite` builtin returns `true`1500+ if its input is infinite. The `isnan` builtin returns `true`1501+ if its input is a NaN. The `infinite` builtin returns a1502+ positive infinite value. The `nan` builtin returns a NaN.1503+ The `isnormal` builtin returns true if its input is a normal1504+ number.1505+1506+ Note that division by zero raises an error.1507+1508+ Currently most arithmetic operations operating on infinities,1509+ NaNs, and sub-normals do not raise errors.1510+1511+ examples:1512+ - program: '.[] | (infinite * .) < 0'1513+ input: '[-1, 1]'1514+ output: ['true', 'false']1515+ - program: 'infinite, nan | type'1516+ input: 'null'1517+ output: ['"number"', '"number"']1518+1519+ - title: "`sort`, `sort_by(path_expression)`"1520+ body: |1521+1522+ The `sort` functions sorts its input, which must be an1523+ array. Values are sorted in the following order:1524+1525+ * `null`1526+ * `false`1527+ * `true`1528+ * numbers1529+ * strings, in alphabetical order (by unicode codepoint value)1530+ * arrays, in lexical order1531+ * objects1532+1533+ The ordering for objects is a little complex: first they're1534+ compared by comparing their sets of keys (as arrays in1535+ sorted order), and if their keys are equal then the values1536+ are compared key by key.1537+1538+ `sort_by` may be used to sort by a particular field of an1539+ object, or by applying any jq filter. `sort_by(f)` compares1540+ two elements by comparing the result of `f` on each element.1541+ When `f` produces multiple values, it firstly compares the1542+ first values, and the second values if the first values are1543+ equal, and so on.1544+1545+ examples:1546+ - program: 'sort'1547+ input: '[8,3,null,6]'1548+ output: ['[null,3,6,8]']1549+1550+ - program: 'sort_by(.foo)'1551+ input: '[{"foo":4, "bar":10}, {"foo":3, "bar":10}, {"foo":2, "bar":1}]'1552+ output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":10}, {"foo":4, "bar":10}]']1553+1554+ - program: 'sort_by(.foo, .bar)'1555+ input: '[{"foo":4, "bar":10}, {"foo":3, "bar":20}, {"foo":2, "bar":1}, {"foo":3, "bar":10}]'1556+ output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":10}, {"foo":3, "bar":20}, {"foo":4, "bar":10}]']1557+1558+ - title: "`group_by(path_expression)`"1559+ body: |1560+1561+ `group_by(.foo)` takes as input an array, groups the1562+ elements having the same `.foo` field into separate arrays,1563+ and produces all of these arrays as elements of a larger1564+ array, sorted by the value of the `.foo` field.1565+1566+ Any jq expression, not just a field access, may be used in1567+ place of `.foo`. The sorting order is the same as described1568+ in the `sort` function above.1569+1570+ examples:1571+ - program: 'group_by(.foo)'1572+ input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'1573+ output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']1574+1575+ - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1576+ body: |1577+1578+ Find the minimum or maximum element of the input array.1579+1580+ The `min_by(path_exp)` and `max_by(path_exp)` functions allow1581+ you to specify a particular field or property to examine, e.g.1582+ `min_by(.foo)` finds the object with the smallest `foo` field.1583+1584+ examples:1585+ - program: 'min'1586+ input: '[5,4,2,7]'1587+ output: ['2']1588+ - program: 'max_by(.foo)'1589+ input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'1590+ output: ['{"foo":2, "bar":3}']1591+1592+ - title: "`unique`, `unique_by(path_exp)`"1593+ body: |1594+1595+ The `unique` function takes as input an array and produces1596+ an array of the same elements, in sorted order, with1597+ duplicates removed.1598+1599+ The `unique_by(path_exp)` function will keep only one element1600+ for each value obtained by applying the argument. Think of it1601+ as making an array by taking one element out of every group1602+ produced by `group`.1603+1604+ examples:1605+ - program: 'unique'1606+ input: '[1,2,5,3,5,3,1,3]'1607+ output: ['[1,2,3,5]']1608+ - program: 'unique_by(.foo)'1609+ input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'1610+ output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']1611+ - program: 'unique_by(length)'1612+ input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'1613+ output: ['["bacon", "chunky", "asparagus"]']1614+1615+ - title: "`reverse`"1616+ body: |1617+1618+ This function reverses an array.1619+1620+ examples:1621+ - program: 'reverse'1622+ input: '[1,2,3,4]'1623+ output: ['[4,3,2,1]']1624+1625+ - title: "`contains(element)`"1626+ body: |1627+1628+ The filter `contains(b)` will produce true if b is1629+ completely contained within the input. A string B is1630+ contained in a string A if B is a substring of A. An array B1631+ is contained in an array A if all elements in B are1632+ contained in any element in A. An object B is contained in1633+ object A if all of the values in B are contained in the1634+ value in A with the same key. All other types are assumed to1635+ be contained in each other if they are equal.1636+1637+ examples:1638+ - program: 'contains("bar")'1639+ input: '"foobar"'1640+ output: ['true']1641+ - program: 'contains(["baz", "bar"])'1642+ input: '["foobar", "foobaz", "blarp"]'1643+ output: ['true']1644+ - program: 'contains(["bazzzzz", "bar"])'1645+ input: '["foobar", "foobaz", "blarp"]'1646+ output: ['false']1647+ - program: 'contains({foo: 12, bar: [{barp: 12}]})'1648+ input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1649+ output: ['true']1650+ - program: 'contains({foo: 12, bar: [{barp: 15}]})'1651+ input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1652+ output: ['false']1653+1654+ - title: "`indices(s)`"1655+ body: |1656+1657+ Outputs an array containing the indices in `.` where `s`1658+ occurs. The input may be an array, in which case if `s` is an1659+ array then the indices output will be those where all elements1660+ in `.` match those of `s`.1661+1662+ examples:1663+ - program: 'indices(", ")'1664+ input: '"a,b, cd, efg, hijk"'1665+ output: ['[3,7,12]']1666+ - program: 'indices(1)'1667+ input: '[0,1,2,1,3,1,4]'1668+ output: ['[1,3,5]']1669+ - program: 'indices([1,2])'1670+ input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1671+ output: ['[1,8]']1672+1673+ - title: "`index(s)`, `rindex(s)`"1674+ body: |1675+1676+ Outputs the index of the first (`index`) or last (`rindex`)1677+ occurrence of `s` in the input.1678+1679+ examples:1680+ - program: 'index(", ")'1681+ input: '"a,b, cd, efg, hijk"'1682+ output: ['3']1683+ - program: 'index(1)'1684+ input: '[0,1,2,1,3,1,4]'1685+ output: ['1']1686+ - program: 'index([1,2])'1687+ input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1688+ output: ['1']1689+ - program: 'rindex(", ")'1690+ input: '"a,b, cd, efg, hijk"'1691+ output: ['12']1692+ - program: 'rindex(1)'1693+ input: '[0,1,2,1,3,1,4]'1694+ output: ['5']1695+ - program: 'rindex([1,2])'1696+ input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1697+ output: ['8']1698+1699+ - title: "`inside`"1700+ body: |1701+1702+ The filter `inside(b)` will produce true if the input is1703+ completely contained within b. It is, essentially, an1704+ inversed version of `contains`.1705+1706+ examples:1707+ - program: 'inside("foobar")'1708+ input: '"bar"'1709+ output: ['true']1710+ - program: 'inside(["foobar", "foobaz", "blarp"])'1711+ input: '["baz", "bar"]'1712+ output: ['true']1713+ - program: 'inside(["foobar", "foobaz", "blarp"])'1714+ input: '["bazzzzz", "bar"]'1715+ output: ['false']1716+ - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1717+ input: '{"foo": 12, "bar": [{"barp": 12}]}'1718+ output: ['true']1719+ - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1720+ input: '{"foo": 12, "bar": [{"barp": 15}]}'1721+ output: ['false']1722+1723+ - title: "`startswith(str)`"1724+ body: |1725+1726+ Outputs `true` if . starts with the given string argument.1727+1728+ examples:1729+ - program: '[.[]|startswith("foo")]'1730+ input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1731+ output: ['[false, true, false, true, false]']1732+1733+ - title: "`endswith(str)`"1734+ body: |1735+1736+ Outputs `true` if . ends with the given string argument.1737+1738+ examples:1739+ - program: '[.[]|endswith("foo")]'1740+ input: '["foobar", "barfoo"]'1741+ output: ['[false, true]']1742+1743+ - title: "`combinations`, `combinations(n)`"1744+ body: |1745+1746+ Outputs all combinations of the elements of the arrays in the1747+ input array. If given an argument `n`, it outputs all combinations1748+ of `n` repetitions of the input array.1749+1750+ examples:1751+ - program: 'combinations'1752+ input: '[[1,2], [3, 4]]'1753+ output: ['[1, 3]', '[1, 4]', '[2, 3]', '[2, 4]']1754+ - program: 'combinations(2)'1755+ input: '[0, 1]'1756+ output: ['[0, 0]', '[0, 1]', '[1, 0]', '[1, 1]']1757+1758+ - title: "`ltrimstr(str)`"1759+ body: |1760+1761+ Outputs its input with the given prefix string removed, if it1762+ starts with it.1763+1764+ examples:1765+ - program: '[.[]|ltrimstr("foo")]'1766+ input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1767+ output: ['["fo","","barfoo","bar","afoo"]']1768+1769+ - title: "`rtrimstr(str)`"1770+ body: |1771+1772+ Outputs its input with the given suffix string removed, if it1773+ ends with it.1774+1775+ examples:1776+ - program: '[.[]|rtrimstr("foo")]'1777+ input: '["fo", "foo", "barfoo", "foobar", "foob"]'1778+ output: ['["fo","","bar","foobar","foob"]']1779+1780+ - title: "`trim`, `ltrim`, `rtrim`"1781+ body: |1782+1783+ `trim` trims both leading and trailing whitespace.1784+1785+ `ltrim` trims only leading (left side) whitespace.1786+1787+ `rtrim` trims only trailing (right side) whitespace.1788+1789+ Whitespace characters are the usual `" "`, `"\n"` `"\t"`, `"\r"`1790+ and also all characters in the Unicode character database with the1791+ whitespace property. Note that what considers whitespace might1792+ change in the future.1793+1794+ examples:1795+ - program: 'trim, ltrim, rtrim'1796+ input: '" abc "'1797+ output: ['"abc"', '"abc "', '" abc"']1798+1799+ - title: "`explode`"1800+ body: |1801+1802+ Converts an input string into an array of the string's1803+ codepoint numbers.1804+1805+ examples:1806+ - program: 'explode'1807+ input: '"foobar"'1808+ output: ['[102,111,111,98,97,114]']1809+1810+ - title: "`implode`"1811+ body: |1812+1813+ The inverse of explode.1814+1815+ examples:1816+ - program: 'implode'1817+ input: '[65, 66, 67]'1818+ output: ['"ABC"']1819+1820+ - title: "`split(str)`"1821+ body: |1822+1823+ Splits an input string on the separator argument.1824+1825+ `split` can also split on regex matches when called with1826+ two arguments (see the regular expressions section below).1827+1828+ examples:1829+ - program: 'split(", ")'1830+ input: '"a, b,c,d, e, "'1831+ output: ['["a","b,c,d","e",""]']1832+1833+ - title: "`join(str)`"1834+ body: |1835+1836+ Joins the array of elements given as input, using the1837+ argument as separator. It is the inverse of `split`: that is,1838+ running `split("foo") | join("foo")` over any input string1839+ returns said input string.1840+1841+ Numbers and booleans in the input are converted to strings.1842+ Null values are treated as empty strings. Arrays and objects1843+ in the input are not supported.1844+1845+ examples:1846+ - program: 'join(", ")'1847+ input: '["a","b,c,d","e"]'1848+ output: ['"a, b,c,d, e"']1849+ - program: 'join(" ")'1850+ input: '["a",1,2.3,true,null,false]'1851+ output: ['"a 1 2.3 true false"']1852+1853+ - title: "`ascii_downcase`, `ascii_upcase`"1854+ body: |1855+1856+ Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1857+ converted to the specified case.1858+1859+ examples:1860+ - program: 'ascii_upcase'1861+ input: '"useful but not for é"'1862+ output: ['"USEFUL BUT NOT FOR é"']1863+1864+ - title: "`while(cond; update)`"1865+ body: |1866+1867+ The `while(cond; update)` function allows you to repeatedly1868+ apply an update to `.` until `cond` is false.1869+1870+ Note that `while(cond; update)` is internally defined as a1871+ recursive jq function. Recursive calls within `while` will1872+ not consume additional memory if `update` produces at most one1873+ output for each input. See advanced topics below.1874+1875+ examples:1876+ - program: '[while(.<100; .*2)]'1877+ input: '1'1878+ output: ['[1,2,4,8,16,32,64]']1879+1880+ - title: "`repeat(exp)`"1881+ body: |1882+1883+ The `repeat(exp)` function allows you to repeatedly1884+ apply expression `exp` to `.` until an error is raised.1885+1886+ Note that `repeat(exp)` is internally defined as a1887+ recursive jq function. Recursive calls within `repeat` will1888+ not consume additional memory if `exp` produces at most one1889+ output for each input. See advanced topics below.1890+1891+ examples:1892+ - program: '[repeat(.*2, error)?]'1893+ input: '1'1894+ output: ['[2]']1895+1896+ - title: "`until(cond; next)`"1897+ body: |1898+1899+ The `until(cond; next)` function allows you to repeatedly1900+ apply the expression `next`, initially to `.` then to its own1901+ output, until `cond` is true. For example, this can be used1902+ to implement a factorial function (see below).1903+1904+ Note that `until(cond; next)` is internally defined as a1905+ recursive jq function. Recursive calls within `until()` will1906+ not consume additional memory if `next` produces at most one1907+ output for each input. See advanced topics below.1908+1909+ examples:1910+ - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1911+ input: '4'1912+ output: ['24']1913+1914+1915+ - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`"1916+ body: |1917+1918+ The `recurse(f)` function allows you to search through a1919+ recursive structure, and extract interesting data from all1920+ levels. Suppose your input represents a filesystem:1921+1922+ {"name": "/", "children": [1923+ {"name": "/bin", "children": [1924+ {"name": "/bin/ls", "children": []},1925+ {"name": "/bin/sh", "children": []}]},1926+ {"name": "/home", "children": [1927+ {"name": "/home/stephen", "children": [1928+ {"name": "/home/stephen/jq", "children": []}]}]}]}1929+1930+ Now suppose you want to extract all of the filenames1931+ present. You need to retrieve `.name`, `.children[].name`,1932+ `.children[].children[].name`, and so on. You can do this1933+ with:1934+1935+ recurse(.children[]) | .name1936+1937+ When called without an argument, `recurse` is equivalent to1938+ `recurse(.[]?)`.1939+1940+ `recurse(f)` is identical to `recurse(f; true)` and can be1941+ used without concerns about recursion depth.1942+1943+ `recurse(f; condition)` is a generator which begins by1944+ emitting . and then emits in turn .|f, .|f|f, .|f|f|f, ... so long1945+ as the computed value satisfies the condition. For example,1946+ to generate all the integers, at least in principle, one1947+ could write `recurse(.+1; true)`.1948+1949+ The recursive calls in `recurse` will not consume additional1950+ memory whenever `f` produces at most a single output for each1951+ input.1952+1953+ examples:1954+ - program: 'recurse(.foo[])'1955+ input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'1956+ output:1957+ - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'1958+ - '{"foo":[]}'1959+ - '{"foo":[{"foo":[]}]}'1960+ - '{"foo":[]}'1961+1962+ - program: 'recurse'1963+ input: '{"a":0,"b":[1]}'1964+ output:1965+ - '{"a":0,"b":[1]}'1966+ - '0'1967+ - '[1]'1968+ - '1'1969+1970+ - program: 'recurse(. * .; . < 20)'1971+ input: '2'1972+ output: ['2', '4', '16']1973+1974+ - title: "`walk(f)`"1975+ body: |1976+1977+ The `walk(f)` function applies f recursively to every1978+ component of the input entity. When an array is1979+ encountered, f is first applied to its elements and then to1980+ the array itself; when an object is encountered, f is first1981+ applied to all the values and then to the object. In1982+ practice, f will usually test the type of its input, as1983+ illustrated in the following examples. The first example1984+ highlights the usefulness of processing the elements of an1985+ array of arrays before processing the array itself. The second1986+ example shows how all the keys of all the objects within the1987+ input can be considered for alteration.1988+1989+ examples:1990+ - program: 'walk(if type == "array" then sort else . end)'1991+ input: '[[4, 1, 7], [8, 5, 2], [3, 6, 9]]'1992+ output:1993+ - '[[1,4,7],[2,5,8],[3,6,9]]'1994+1995+ - program: 'walk( if type == "object" then with_entries( .key |= sub( "^_+"; "") ) else . end )'1996+ input: '[ { "_a": { "__b": 2 } } ]'1997+ output:1998+ - '[{"a":{"b":2}}]'1999+2000+ - title: "`have_literal_numbers`"2001+ body: |2002+2003+ This builtin returns true if jq's build configuration2004+ includes support for preservation of input number literals.2005+2006+ - title: "`have_decnum`"2007+ body: |2008+2009+ This builtin returns true if jq was built with "decnum",2010+ which is the current literal number preserving numeric2011+ backend implementation for jq.2012+2013+ - title: "`$JQ_BUILD_CONFIGURATION`"2014+ body: |2015+2016+ This builtin binding shows the jq executable's build2017+ configuration. Its value has no particular format, but2018+ it can be expected to be at least the `./configure`2019+ command-line arguments, and may be enriched in the2020+ future to include the version strings for the build2021+ tooling used.2022+2023+ Note that this can be overriden in the command-line2024+ with `--arg` and related options.2025+2026+ - title: "`$ENV`, `env`"2027+ body: |2028+2029+ `$ENV` is an object representing the environment variables as2030+ set when the jq program started.2031+2032+ `env` outputs an object representing jq's current environment.2033+2034+ At the moment there is no builtin for setting environment2035+ variables.2036+2037+ examples:2038+ - program: '$ENV.PAGER'2039+ input: 'null'2040+ output: ['"less"']2041+2042+ - program: 'env.PAGER'2043+ input: 'null'2044+ output: ['"less"']2045+2046+ - title: "`transpose`"2047+ body: |2048+2049+ Transpose a possibly jagged matrix (an array of arrays).2050+ Rows are padded with nulls so the result is always rectangular.2051+2052+ examples:2053+ - program: 'transpose'2054+ input: '[[1], [2,3]]'2055+ output: ['[[1,2],[null,3]]']2056+2057+ - title: "`bsearch(x)`"2058+ body: |2059+2060+ `bsearch(x)` conducts a binary search for x in the input2061+ array. If the input is sorted and contains x, then2062+ `bsearch(x)` will return its index in the array; otherwise, if2063+ the array is sorted, it will return (-1 - ix) where ix is an2064+ insertion point such that the array would still be sorted2065+ after the insertion of x at ix. If the array is not sorted,2066+ `bsearch(x)` will return an integer that is probably of no2067+ interest.2068+2069+ examples:2070+ - program: 'bsearch(0)'2071+ input: '[0,1]'2072+ output: ['0']2073+ - program: 'bsearch(0)'2074+ input: '[1,2,3]'2075+ output: ['-1']2076+ - program: 'bsearch(4) as $ix | if $ix < 0 then .[-(1+$ix)] = 4 else . end'2077+ input: '[1,2,3]'2078+ output: ['[1,2,3,4]']2079+2080+ - title: "String interpolation: `\\(exp)`"2081+ body: |2082+2083+ Inside a string, you can put an expression inside parens2084+ after a backslash. Whatever the expression returns will be2085+ interpolated into the string.2086+2087+ examples:2088+ - program: '"The input was \(.), which is one less than \(.+1)"'2089+ input: '42'2090+ output: ['"The input was 42, which is one less than 43"']2091+2092+ - title: "Convert to/from JSON"2093+ body: |2094+2095+ The `tojson` and `fromjson` builtins dump values as JSON texts2096+ or parse JSON texts into values, respectively. The `tojson`2097+ builtin differs from `tostring` in that `tostring` returns strings2098+ unmodified, while `tojson` encodes strings as JSON strings.2099+2100+ examples:2101+ - program: '[.[]|tostring]'2102+ input: '[1, "foo", ["foo"]]'2103+ output: ['["1","foo","[\"foo\"]"]']2104+ - program: '[.[]|tojson]'2105+ input: '[1, "foo", ["foo"]]'2106+ output: ['["1","\"foo\"","[\"foo\"]"]']2107+ - program: '[.[]|tojson|fromjson]'2108+ input: '[1, "foo", ["foo"]]'2109+ output: ['[1,"foo",["foo"]]']2110+2111+ - title: "Format strings and escaping"2112+ body: |2113+2114+ The `@foo` syntax is used to format and escape strings,2115+ which is useful for building URLs, documents in a language2116+ like HTML or XML, and so forth. `@foo` can be used as a2117+ filter on its own, the possible escapings are:2118+2119+ * `@text`:2120+2121+ Calls `tostring`, see that function for details.2122+2123+ * `@json`:2124+2125+ Serializes the input as JSON.2126+2127+ * `@html`:2128+2129+ Applies HTML/XML escaping, by mapping the characters2130+ `<>&'"` to their entity equivalents `<`, `>`,2131+ `&`, `'`, `"`.2132+2133+ * `@uri`:2134+2135+ Applies percent-encoding, by mapping all reserved URI2136+ characters to a `%XX` sequence.2137+2138+ * `@csv`:2139+2140+ The input must be an array, and it is rendered as CSV2141+ with double quotes for strings, and quotes escaped by2142+ repetition.2143+2144+ * `@tsv`:2145+2146+ The input must be an array, and it is rendered as TSV2147+ (tab-separated values). Each input array will be printed as2148+ a single line. Fields are separated by a single2149+ tab (ascii `0x09`). Input characters line-feed (ascii `0x0a`),2150+ carriage-return (ascii `0x0d`), tab (ascii `0x09`) and2151+ backslash (ascii `0x5c`) will be output as escape sequences2152+ `\n`, `\r`, `\t`, `\\` respectively.2153+2154+ * `@sh`:2155+2156+ The input is escaped suitable for use in a command-line2157+ for a POSIX shell. If the input is an array, the output2158+ will be a series of space-separated strings.2159+2160+ * `@base64`:2161+2162+ The input is converted to base64 as specified by RFC 4648.2163+2164+ * `@base64d`:2165+2166+ The inverse of `@base64`, input is decoded as specified by RFC 4648.2167+ Note\: If the decoded string is not UTF-8, the results are undefined.2168+2169+ This syntax can be combined with string interpolation in a2170+ useful way. You can follow a `@foo` token with a string2171+ literal. The contents of the string literal will *not* be2172+ escaped. However, all interpolations made inside that string2173+ literal will be escaped. For instance,2174+2175+ @uri "https://www.google.com/search?q=\(.search)"2176+2177+ will produce the following output for the input2178+ `{"search":"what is jq?"}`:2179+2180+ "https://www.google.com/search?q=what%20is%20jq%3F"2181+2182+ Note that the slashes, question mark, etc. in the URL are2183+ not escaped, as they were part of the string literal.2184+2185+ examples:2186+ - program: '@html'2187+ input: '"This works if x < y"'2188+ output: ['"This works if x < y"']2189+2190+ - program: '@sh "echo \(.)"'2191+ input: "\"O'Hara's Ale\""2192+ output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]2193+2194+ - program: '@base64'2195+ input: '"This is a message"'2196+ output: ['"VGhpcyBpcyBhIG1lc3NhZ2U="']2197+2198+ - program: '@base64d'2199+ input: '"VGhpcyBpcyBhIG1lc3NhZ2U="'2200+ output: ['"This is a message"']2201+2202+ - title: "Dates"2203+ body: |2204+2205+ jq provides some basic date handling functionality, with some2206+ high-level and low-level builtins. In all cases these2207+ builtins deal exclusively with time in UTC.2208+2209+ The `fromdateiso8601` builtin parses datetimes in the ISO 86012210+ format to a number of seconds since the Unix epoch2211+ (1970-01-01T00:00:00Z). The `todateiso8601` builtin does the2212+ inverse.2213+2214+ The `fromdate` builtin parses datetime strings. Currently2215+ `fromdate` only supports ISO 8601 datetime strings, but in the2216+ future it will attempt to parse datetime strings in more2217+ formats.2218+2219+ The `todate` builtin is an alias for `todateiso8601`.2220+2221+ The `now` builtin outputs the current time, in seconds since2222+ the Unix epoch.2223+2224+ Low-level jq interfaces to the C-library time functions are2225+ also provided: `strptime`, `strftime`, `strflocaltime`,2226+ `mktime`, `gmtime`, and `localtime`. Refer to your host2227+ operating system's documentation for the format strings used2228+ by `strptime` and `strftime`. Note: these are not necessarily2229+ stable interfaces in jq, particularly as to their localization2230+ functionality.2231+2232+ The `gmtime` builtin consumes a number of seconds since the2233+ Unix epoch and outputs a "broken down time" representation of2234+ Greenwich Mean Time as an array of numbers representing2235+ (in this order): the year, the month (zero-based), the day of2236+ the month (one-based), the hour of the day, the minute of the2237+ hour, the second of the minute, the day of the week, and the2238+ day of the year -- all one-based unless otherwise stated. The2239+ day of the week number may be wrong on some systems for dates2240+ before March 1st 1900, or after December 31 2099.2241+2242+ The `localtime` builtin works like the `gmtime` builtin, but2243+ using the local timezone setting.2244+2245+ The `mktime` builtin consumes "broken down time"2246+ representations of time output by `gmtime` and `strptime`.2247+2248+ The `strptime(fmt)` builtin parses input strings matching the2249+ `fmt` argument. The output is in the "broken down time"2250+ representation consumed by `gmtime` and output by `mktime`.2251+2252+ The `strftime(fmt)` builtin formats a time (GMT) with the2253+ given format. The `strflocaltime` does the same, but using2254+ the local timezone setting.2255+2256+ The format strings for `strptime` and `strftime` are described2257+ in typical C library documentation. The format string for ISO2258+ 8601 datetime is `"%Y-%m-%dT%H:%M:%SZ"`.2259+2260+ jq may not support some or all of this date functionality on2261+ some systems. In particular, the `%u` and `%j` specifiers for2262+ `strptime(fmt)` are not supported on macOS.2263+2264+ examples:2265+ - program: 'fromdate'2266+ input: '"2015-03-05T23:51:47Z"'2267+ output: ['1425599507']2268+2269+ - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")'2270+ input: '"2015-03-05T23:51:47Z"'2271+ output: ['[2015,2,5,23,51,47,4,63]']2272+2273+ - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'2274+ input: '"2015-03-05T23:51:47Z"'2275+ output: ['1425599507']2276+2277+ - title: "SQL-Style Operators"2278+ body: |2279+2280+ jq provides a few SQL-style operators.2281+2282+ * INDEX(stream; index_expression):2283+2284+ This builtin produces an object whose keys are computed by2285+ the given index expression applied to each value from the2286+ given stream.2287+2288+ * JOIN($idx; stream; idx_expr; join_expr):2289+2290+ This builtin joins the values from the given stream to the2291+ given index. The index's keys are computed by applying the2292+ given index expression to each value from the given stream.2293+ An array of the value in the stream and the corresponding2294+ value from the index is fed to the given join expression to2295+ produce each result.2296+2297+ * JOIN($idx; stream; idx_expr):2298+2299+ Same as `JOIN($idx; stream; idx_expr; .)`.2300+2301+ * JOIN($idx; idx_expr):2302+2303+ This builtin joins the input `.` to the given index, applying2304+ the given index expression to `.` to compute the index key.2305+ The join operation is as described above.2306+2307+ * IN(s):2308+2309+ This builtin outputs `true` if `.` appears in the given2310+ stream, otherwise it outputs `false`.2311+2312+ * IN(source; s):2313+2314+ This builtin outputs `true` if any value in the source stream2315+ appears in the second stream, otherwise it outputs `false`.2316+2317+ - title: "`builtins`"2318+ body: |2319+2320+ Returns a list of all builtin functions in the format `name/arity`.2321+ Since functions with the same name but different arities are considered2322+ separate functions, `all/0`, `all/1`, and `all/2` would all be present2323+ in the list.2324+2325+ - title: Conditionals and Comparisons2326+ entries:2327+ - title: "`==`, `!=`"2328+ body: |2329+2330+ The expression 'a == b' will produce 'true' if the results of evaluating2331+ a and b are equal (that is, if they represent equivalent JSON values) and2332+ 'false' otherwise. In particular, strings are never considered equal2333+ to numbers. In checking for the equality of JSON objects, the ordering of keys2334+ is irrelevant. If you're coming from JavaScript, please note that jq's `==` is like2335+ JavaScript's `===`, the "strict equality" operator.2336+2337+ != is "not equal", and 'a != b' returns the opposite value of 'a == b'2338+2339+ examples:2340+ - program: '. == false'2341+ input: 'null'2342+ output: ['false']2343+2344+ - program: '. == {"b": {"d": (4 + 1e-20), "c": 3}, "a":1}'2345+ input: '{"a":1, "b": {"c": 3, "d": 4}}'2346+ output: ['true']2347+2348+ - program: '.[] == 1'2349+ input: '[1, 1.0, "1", "banana"]'2350+ output: ['true', 'true', 'false', 'false']2351+2352+ - title: if-then-else-end2353+ body: |2354+2355+ `if A then B else C end` will act the same as `B` if `A`2356+ produces a value other than false or null, but act the same2357+ as `C` otherwise.2358+2359+ `if A then B end` is the same as `if A then B else . end`.2360+ That is, the `else` branch is optional, and if absent is the2361+ same as `.`. This also applies to `elif` with absent ending `else` branch.2362+2363+ Checking for false or null is a simpler notion of2364+ "truthiness" than is found in JavaScript or Python, but it2365+ means that you'll sometimes have to be more explicit about2366+ the condition you want. You can't test whether, e.g. a2367+ string is empty using `if .name then A else B end`; you'll2368+ need something like `if .name == "" then A else B end` instead.2369+2370+ If the condition `A` produces multiple results, then `B` is evaluated2371+ once for each result that is not false or null, and `C` is evaluated2372+ once for each false or null.2373+2374+ More cases can be added to an if using `elif A then B` syntax.2375+2376+ examples:2377+ - program: |-2378+ if . == 0 then2379+ "zero"2380+ elif . == 1 then2381+ "one"2382+ else2383+ "many"2384+ end2385+ input: '2'2386+ output: ['"many"']2387+2388+ - title: "`>`, `>=`, `<=`, `<`"2389+ body: |2390+2391+ The comparison operators `>`, `>=`, `<=`, `<` return whether2392+ their left argument is greater than, greater than or equal2393+ to, less than or equal to or less than their right argument2394+ (respectively).2395+2396+ The ordering is the same as that described for `sort`, above.2397+2398+ examples:2399+ - program: '. < 5'2400+ input: '2'2401+ output: ['true']2402+2403+ - title: "`and`, `or`, `not`"2404+ body: |2405+2406+ jq supports the normal Boolean operators `and`, `or`, `not`.2407+ They have the same standard of truth as if expressions -2408+ `false` and `null` are considered "false values", and2409+ anything else is a "true value".2410+2411+ If an operand of one of these operators produces multiple2412+ results, the operator itself will produce a result for each input.2413+2414+ `not` is in fact a builtin function rather than an operator,2415+ so it is called as a filter to which things can be piped2416+ rather than with special syntax, as in `.foo and .bar |2417+ not`.2418+2419+ These three only produce the values `true` and `false`, and2420+ so are only useful for genuine Boolean operations, rather2421+ than the common Perl/Python/Ruby idiom of2422+ "value_that_may_be_null or default". If you want to use this2423+ form of "or", picking between two values rather than2424+ evaluating a condition, see the `//` operator below.2425+2426+ examples:2427+ - program: '42 and "a string"'2428+ input: 'null'2429+ output: ['true']2430+ - program: '(true, false) or false'2431+ input: 'null'2432+ output: ['true', 'false']2433+ - program: '(true, true) and (true, false)'2434+ input: 'null'2435+ output: ['true', 'false', 'true', 'false']2436+ - program: '[true, false | not]'2437+ input: 'null'2438+ output: ['[false, true]']2439+2440+ - title: "Alternative operator: `//`"2441+ body: |2442+2443+ The `//` operator produces all the values of its left-hand2444+ side that are neither `false` nor `null`. If the2445+ left-hand side produces no values other than `false` or2446+ `null`, then `//` produces all the values of its right-hand2447+ side.2448+2449+ A filter of the form `a // b` produces all the results of2450+ `a` that are not `false` or `null`. If `a` produces no2451+ results, or no results other than `false` or `null`, then `a2452+ // b` produces the results of `b`.2453+2454+ This is useful for providing defaults: `.foo // 1` will2455+ evaluate to `1` if there's no `.foo` element in the2456+ input. It's similar to how `or` is sometimes used in Python2457+ (jq's `or` operator is reserved for strictly Boolean2458+ operations).2459+2460+ Note: `some_generator // defaults_here` is not the same2461+ as `some_generator | . // defaults_here`. The latter will2462+ produce default values for all non-`false`, non-`null`2463+ values of the left-hand side, while the former will not.2464+ Precedence rules can make this confusing. For example, in2465+ `false, 1 // 2` the left-hand side of `//` is `1`, not2466+ `false, 1` -- `false, 1 // 2` parses the same way as `false,2467+ (1 // 2)`. In `(false, null, 1) | . // 42` the left-hand2468+ side of `//` is `.`, which always produces just one value,2469+ while in `(false, null, 1) // 42` the left-hand side is a2470+ generator of three values, and since it produces a2471+ value other `false` and `null`, the default `42` is not2472+ produced.2473+2474+ examples:2475+ - program: 'empty // 42'2476+ input: 'null'2477+ output: ['42']2478+ - program: '.foo // 42'2479+ input: '{"foo": 19}'2480+ output: ['19']2481+ - program: '.foo // 42'2482+ input: '{}'2483+ output: ['42']2484+ - program: '(false, null, 1) // 42'2485+ input: 'null'2486+ output: ['1']2487+ - program: '(false, null, 1) | . // 42'2488+ input: 'null'2489+ output: ['42', '42', '1']2490+2491+ - title: try-catch2492+ body: |2493+2494+ Errors can be caught by using `try EXP catch EXP`. The first2495+ expression is executed, and if it fails then the second is2496+ executed with the error message. The output of the handler,2497+ if any, is output as if it had been the output of the2498+ expression to try.2499+2500+ The `try EXP` form uses `empty` as the exception handler.2501+2502+ examples:2503+ - program: 'try .a catch ". is not an object"'2504+ input: 'true'2505+ output: ['". is not an object"']2506+ - program: '[.[]|try .a]'2507+ input: '[{}, true, {"a":1}]'2508+ output: ['[null, 1]']2509+ - program: 'try error("some exception") catch .'2510+ input: 'true'2511+ output: ['"some exception"']2512+2513+ - title: Breaking out of control structures2514+ body: |2515+2516+ A convenient use of try/catch is to break out of control2517+ structures like `reduce`, `foreach`, `while`, and so on.2518+2519+ For example:2520+2521+ # Repeat an expression until it raises "break" as an2522+ # error, then stop repeating without re-raising the error.2523+ # But if the error caught is not "break" then re-raise it.2524+ try repeat(exp) catch if .=="break" then empty else error2525+2526+ jq has a syntax for named lexical labels to "break" or "go (back) to":2527+2528+ label $out | ... break $out ...2529+2530+ The `break $label_name` expression will cause the program to2531+ act as though the nearest (to the left) `label $label_name`2532+ produced `empty`.2533+2534+ The relationship between the `break` and corresponding `label`2535+ is lexical: the label has to be "visible" from the break.2536+2537+ To break out of a `reduce`, for example:2538+2539+ label $out | reduce .[] as $item (null; if .==false then break $out else ... end)2540+2541+ The following jq program produces a syntax error:2542+2543+ break $out2544+2545+ because no label `$out` is visible.2546+2547+ - title: "Error Suppression / Optional Operator: `?`"2548+ body: |2549+2550+ The `?` operator, used as `EXP?`, is shorthand for `try EXP`.2551+2552+ examples:2553+ - program: '[.[] | .a?]'2554+ input: '[{}, true, {"a":1}]'2555+ output: ['[null, 1]']2556+ - program: '[.[] | tonumber?]'2557+ input: '["1", "invalid", "3", 4]'2558+ output: ['[1, 3, 4]']2559+2560+ - title: Regular expressions2561+ body: |2562+2563+ jq uses the2564+ [Oniguruma regular expression library](https://github.com/kkos/oniguruma/blob/master/doc/RE),2565+ as do PHP, TextMate, Sublime Text, etc, so the2566+ description here will focus on jq specifics.2567+2568+ Oniguruma supports several flavors of regular expression, so it is important to know2569+ that jq uses the ["Perl NG" (Perl with named groups)](https://github.com/kkos/oniguruma/blob/master/doc/SYNTAX.md) flavor.2570+2571+ The jq regex filters are defined so that they can be used using2572+ one of these patterns:2573+2574+ STRING | FILTER(REGEX)2575+ STRING | FILTER(REGEX; FLAGS)2576+ STRING | FILTER([REGEX])2577+ STRING | FILTER([REGEX, FLAGS])2578+2579+ where:2580+2581+ * STRING, REGEX, and FLAGS are jq strings and subject to jq string interpolation;2582+ * REGEX, after string interpolation, should be a valid regular expression;2583+ * FILTER is one of `test`, `match`, or `capture`, as described below.2584+2585+ Since REGEX must evaluate to a JSON string, some characters that are needed2586+ to form a regular expression must be escaped. For example, the regular expression2587+ `\s` signifying a whitespace character would be written as `"\\s"`.2588+2589+ FLAGS is a string consisting of one of more of the supported flags:2590+2591+ * `g` - Global search (find all matches, not just the first)2592+ * `i` - Case insensitive search2593+ * `m` - Multi line mode (`.` will match newlines)2594+ * `n` - Ignore empty matches2595+ * `p` - Both s and m modes are enabled2596+ * `s` - Single line mode (`^` -> `\A`, `$` -> `\Z`)2597+ * `l` - Find longest possible matches2598+ * `x` - Extended regex format (ignore whitespace and comments)2599+2600+ To match a whitespace with the `x` flag, use `\s`, e.g.2601+2602+ jq -n '"a b" | test("a\\sb"; "x")'2603+2604+ Note that certain flags may also be specified within REGEX, e.g.2605+2606+ jq -n '("test", "TEst", "teST", "TEST") | test("(?i)te(?-i)st")'2607+2608+ evaluates to: `true`, `true`, `false`, `false`.2609+2610+ entries:2611+ - title: "`test(val)`, `test(regex; flags)`"2612+ body: |2613+2614+ Like `match`, but does not return match objects, only `true` or `false`2615+ for whether or not the regex matches the input.2616+2617+ examples:2618+ - program: 'test("foo")'2619+ input: '"foo"'2620+ output: ['true']2621+ - program: '.[] | test("a b c # spaces are ignored"; "ix")'2622+ input: '["xabcd", "ABC"]'2623+ output: ['true', 'true']2624+2625+ - title: "`match(val)`, `match(regex; flags)`"2626+ body: |2627+2628+ **match** outputs an object for each match it finds. Matches have2629+ the following fields:2630+2631+ * `offset` - offset in UTF-8 codepoints from the beginning of the input2632+ * `length` - length in UTF-8 codepoints of the match2633+ * `string` - the string that it matched2634+ * `captures` - an array of objects representing capturing groups.2635+2636+ Capturing group objects have the following fields:2637+2638+ * `offset` - offset in UTF-8 codepoints from the beginning of the input2639+ * `length` - length in UTF-8 codepoints of this capturing group2640+ * `string` - the string that was captured2641+ * `name` - the name of the capturing group (or `null` if it was unnamed)2642+2643+ Capturing groups that did not match anything return an offset of -12644+2645+ examples:2646+ - program: 'match("(abc)+"; "g")'2647+ input: '"abc abc"'2648+ output:2649+ - '{"offset": 0, "length": 3, "string": "abc", "captures": [{"offset": 0, "length": 3, "string": "abc", "name": null}]}'2650+ - '{"offset": 4, "length": 3, "string": "abc", "captures": [{"offset": 4, "length": 3, "string": "abc", "name": null}]}'2651+ - program: 'match("foo")'2652+ input: '"foo bar foo"'2653+ output: ['{"offset": 0, "length": 3, "string": "foo", "captures": []}']2654+ - program: 'match(["foo", "ig"])'2655+ input: '"foo bar FOO"'2656+ output:2657+ - '{"offset": 0, "length": 3, "string": "foo", "captures": []}'2658+ - '{"offset": 8, "length": 3, "string": "FOO", "captures": []}'2659+ - program: 'match("foo (?<bar123>bar)? foo"; "ig")'2660+ input: '"foo bar foo foo foo"'2661+ output:2662+ - '{"offset": 0, "length": 11, "string": "foo bar foo", "captures": [{"offset": 4, "length": 3, "string": "bar", "name": "bar123"}]}'2663+ - '{"offset": 12, "length": 8, "string": "foo foo", "captures": [{"offset": -1, "length": 0, "string": null, "name": "bar123"}]}'2664+2665+ - program: '[ match("."; "g")] | length'2666+ input: '"abc"'2667+ output: ['3']2668+2669+2670+ - title: "`capture(val)`, `capture(regex; flags)`"2671+ body: |2672+2673+ Collects the named captures in a JSON object, with the name2674+ of each capture as the key, and the matched string as the2675+ corresponding value.2676+2677+ examples:2678+ - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2679+ input: '"xyzzy-14"'2680+ output: ['{ "a": "xyzzy", "n": "14" }']2681+2682+ - title: "`scan(regex)`, `scan(regex; flags)`"2683+ body: |2684+2685+ Emit a stream of the non-overlapping substrings of the input2686+ that match the regex in accordance with the flags, if any2687+ have been specified. If there is no match, the stream is empty.2688+ To capture all the matches for each input string, use the idiom2689+ `[ expr ]`, e.g. `[ scan(regex) ]`.2690+2691+ examples:2692+ - program: 'scan("c")'2693+ input: '"abcdefabc"'2694+ output: ['"c"', '"c"']2695+2696+ - title: "`split(regex; flags)`"2697+ body: |2698+2699+ Splits an input string on each regex match.2700+2701+ For backwards compatibility, when called with a single argument,2702+ `split` splits on a string, not a regex.2703+2704+ examples:2705+ - program: 'split(", *"; null)'2706+ input: '"ab,cd, ef"'2707+ output: ['["ab","cd","ef"]']2708+2709+2710+ - title: "`splits(regex)`, `splits(regex; flags)`"2711+ body: |2712+2713+ These provide the same results as their `split` counterparts,2714+ but as a stream instead of an array.2715+2716+ examples:2717+ - program: 'splits(", *")'2718+ input: '"ab,cd, ef, gh"'2719+ output: ['"ab"','"cd"','"ef"','"gh"']2720+2721+ - title: "`sub(regex; tostring)`, `sub(regex; tostring; flags)`"2722+ body: |2723+2724+ Emit the string obtained by replacing the first match of2725+ regex in the input string with `tostring`, after2726+ interpolation. `tostring` should be a jq string or a stream2727+ of such strings, each of which may contain references to2728+ named captures. The named captures are, in effect, presented2729+ as a JSON object (as constructed by `capture`) to2730+ `tostring`, so a reference to a captured variable named "x"2731+ would take the form: `"\(.x)"`.2732+2733+ examples:2734+ - program: 'sub("[^a-z]*(?<x>[a-z]+)"; "Z\(.x)"; "g")'2735+ input: '"123abc456def"'2736+ output: ['"ZabcZdef"']2737+2738+ - program: '[sub("(?<a>.)"; "\(.a|ascii_upcase)", "\(.a|ascii_downcase)")]'2739+ input: '"aB"'2740+ output: ['["AB","aB"]']2741+2742+ - title: "`gsub(regex; tostring)`, `gsub(regex; tostring; flags)`"2743+ body: |2744+2745+ `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2746+ replaced by `tostring`, after interpolation. If the second argument is a stream2747+ of jq strings, then `gsub` will produce a corresponding stream of JSON strings.2748+2749+ examples:2750+ - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2751+ input: '"Abcabc"'2752+ output: ['"+A-+a-"']2753+2754+ - program: '[gsub("p"; "a", "b")]'2755+ input: '"p"'2756+ output: ['["a","b"]']2757+2758+2759+ - title: Advanced features2760+ body: |2761+ Variables are an absolute necessity in most programming languages, but2762+ they're relegated to an "advanced feature" in jq.2763+2764+ In most languages, variables are the only means of passing around2765+ data. If you calculate a value, and you want to use it more than once,2766+ you'll need to store it in a variable. To pass a value to another part2767+ of the program, you'll need that part of the program to define a2768+ variable (as a function parameter, object member, or whatever) in2769+ which to place the data.2770+2771+ It is also possible to define functions in jq, although this is2772+ is a feature whose biggest use is defining jq's standard library2773+ (many jq functions such as `map` and `select` are in fact written2774+ in jq).2775+2776+ jq has reduction operators, which are very powerful but a bit2777+ tricky. Again, these are mostly used internally, to define some2778+ useful bits of jq's standard library.2779+2780+ It may not be obvious at first, but jq is all about generators2781+ (yes, as often found in other languages). Some utilities are2782+ provided to help deal with generators.2783+2784+ Some minimal I/O support (besides reading JSON from standard2785+ input, and writing JSON to standard output) is available.2786+2787+ Finally, there is a module/library system.2788+2789+ entries:2790+ - title: "Variable / Symbolic Binding Operator: `... as $identifier | ...`"2791+ body: |2792+2793+ In jq, all filters have an input and an output, so manual2794+ plumbing is not necessary to pass a value from one part of a program2795+ to the next. Many expressions, for instance `a + b`, pass their input2796+ to two distinct subexpressions (here `a` and `b` are both passed the2797+ same input), so variables aren't usually necessary in order to use a2798+ value twice.2799+2800+ For instance, calculating the average value of an array of numbers2801+ requires a few variables in most languages - at least one to hold the2802+ array, perhaps one for each element or for a loop counter. In jq, it's2803+ simply `add / length` - the `add` expression is given the array and2804+ produces its sum, and the `length` expression is given the array and2805+ produces its length.2806+2807+ So, there's generally a cleaner way to solve most problems in jq than2808+ defining variables. Still, sometimes they do make things easier, so jq2809+ lets you define variables using `expression as $variable`. All2810+ variable names start with `$`. Here's a slightly uglier version of the2811+ array-averaging example:2812+2813+ length as $array_length | add / $array_length2814+2815+ We'll need a more complicated problem to find a situation where using2816+ variables actually makes our lives easier.2817+2818+2819+ Suppose we have an array of blog posts, with "author" and "title"2820+ fields, and another object which is used to map author usernames to2821+ real names. Our input looks like:2822+2823+ {"posts": [{"title": "First post", "author": "anon"},2824+ {"title": "A well-written article", "author": "person1"}],2825+ "realnames": {"anon": "Anonymous Coward",2826+ "person1": "Person McPherson"}}2827+2828+ We want to produce the posts with the author field containing a real2829+ name, as in:2830+2831+ {"title": "First post", "author": "Anonymous Coward"}2832+ {"title": "A well-written article", "author": "Person McPherson"}2833+2834+ We use a variable, $names, to store the realnames object, so that we2835+ can refer to it later when looking up author usernames:2836+2837+ .realnames as $names | .posts[] | {title, author: $names[.author]}2838+2839+ The expression `exp as $x | ...` means: for each value of expression2840+ `exp`, run the rest of the pipeline with the entire original input, and2841+ with `$x` set to that value. Thus `as` functions as something of a2842+ foreach loop.2843+2844+ Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2845+ `{$foo}` is a handy way of writing `{foo: $foo}`.2846+2847+ Multiple variables may be declared using a single `as` expression by2848+ providing a pattern that matches the structure of the input2849+ (this is known as "destructuring"):2850+2851+ . as {realnames: $names, posts: [$first, $second]} | ...2852+2853+ The variable declarations in array patterns (e.g., `. as2854+ [$first, $second]`) bind to the elements of the array in from2855+ the element at index zero on up, in order. When there is no2856+ value at the index for an array pattern element, `null` is2857+ bound to that variable.2858+2859+ Variables are scoped over the rest of the expression that defines2860+ them, so2861+2862+ .realnames as $names | (.posts[] | {title, author: $names[.author]})2863+2864+ will work, but2865+2866+ (.realnames as $names | .posts[]) | {title, author: $names[.author]}2867+2868+ won't.2869+2870+ For programming language theorists, it's more accurate to2871+ say that jq variables are lexically-scoped bindings. In2872+ particular there's no way to change the value of a binding;2873+ one can only setup a new binding with the same name, but which2874+ will not be visible where the old one was.2875+2876+ examples:2877+ - program: '.bar as $x | .foo | . + $x'2878+ input: '{"foo":10, "bar":200}'2879+ output: ['210']2880+ - program: '. as $i|[(.*2|. as $i| $i), $i]'2881+ input: '5'2882+ output: ['[10,5]']2883+ - program: '. as [$a, $b, {c: $c}] | $a + $b + $c'2884+ input: '[2, 3, {"c": 4, "d": 5}]'2885+ output: ['9']2886+ - program: '.[] as [$a, $b] | {a: $a, b: $b}'2887+ input: '[[0], [0, 1], [2, 1, 0]]'2888+ output: ['{"a":0,"b":null}', '{"a":0,"b":1}', '{"a":2,"b":1}']2889+2890+ - title: 'Destructuring Alternative Operator: `?//`'2891+ body: |2892+2893+ The destructuring alternative operator provides a concise mechanism2894+ for destructuring an input that can take one of several forms.2895+2896+ Suppose we have an API that returns a list of resources and events2897+ associated with them, and we want to get the user_id and timestamp of2898+ the first event for each resource. The API (having been clumsily2899+ converted from XML) will only wrap the events in an array if the resource2900+ has multiple events:2901+2902+ {"resources": [{"id": 1, "kind": "widget", "events": {"action": "create", "user_id": 1, "ts": 13}},2903+ {"id": 2, "kind": "widget", "events": [{"action": "create", "user_id": 1, "ts": 14}, {"action": "destroy", "user_id": 1, "ts": 15}]}]}2904+2905+ We can use the destructuring alternative operator to handle this structural change simply:2906+2907+ .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$user_id, $ts}]} | {$user_id, $kind, $id, $ts}2908+2909+ Or, if we aren't sure if the input is an array of values or an object:2910+2911+ .[] as [$id, $kind, $user_id, $ts] ?// {$id, $kind, $user_id, $ts} | ...2912+2913+ Each alternative need not define all of the same variables, but all named2914+ variables will be available to the subsequent expression. Variables not2915+ matched in the alternative that succeeded will be `null`:2916+2917+ .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}2918+2919+ Additionally, if the subsequent expression returns an error, the2920+ alternative operator will attempt to try the next binding. Errors2921+ that occur during the final alternative are passed through.2922+2923+ [[3]] | .[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end2924+2925+ examples:2926+ - program: '.[] as {$a, $b, c: {$d, $e}} ?// {$a, $b, c: [{$d, $e}]} | {$a, $b, $d, $e}'2927+ input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2928+ output: ['{"a":1,"b":2,"d":3,"e":4}', '{"a":1,"b":2,"d":3,"e":4}']2929+ - program: '.[] as {$a, $b, c: {$d}} ?// {$a, $b, c: [{$e}]} | {$a, $b, $d, $e}'2930+ input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2931+ output: ['{"a":1,"b":2,"d":3,"e":null}', '{"a":1,"b":2,"d":null,"e":4}']2932+ - program: '.[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end'2933+ input: '[[3]]'2934+ output: ['{"a":null,"b":3}']2935+2936+ - title: 'Defining Functions'2937+ body: |2938+2939+ You can give a filter a name using "def" syntax:2940+2941+ def increment: . + 1;2942+2943+ From then on, `increment` is usable as a filter just like a2944+ builtin function (in fact, this is how many of the builtins2945+ are defined). A function may take arguments:2946+2947+ def map(f): [.[] | f];2948+2949+ Arguments are passed as _filters_ (functions with no2950+ arguments), _not_ as values. The same argument may be2951+ referenced multiple times with different inputs (here `f` is2952+ run for each element of the input array). Arguments to a2953+ function work more like callbacks than like value arguments.2954+ This is important to understand. Consider:2955+2956+ def foo(f): f|f;2957+ 5|foo(.*2)2958+2959+ The result will be 20 because `f` is `.*2`, and during the2960+ first invocation of `f` `.` will be 5, and the second time it2961+ will be 10 (5 * 2), so the result will be 20. Function2962+ arguments are filters, and filters expect an input when2963+ invoked.2964+2965+ If you want the value-argument behaviour for defining simple2966+ functions, you can just use a variable:2967+2968+ def addvalue(f): f as $f | map(. + $f);2969+2970+ Or use the short-hand:2971+2972+ def addvalue($f): ...;2973+2974+ With either definition, `addvalue(.foo)` will add the current2975+ input's `.foo` field to each element of the array. Do note2976+ that calling `addvalue(.[])` will cause the `map(. + $f)` part2977+ to be evaluated once per value in the value of `.` at the call2978+ site.2979+2980+ Multiple definitions using the same function name are allowed.2981+ Each re-definition replaces the previous one for the same2982+ number of function arguments, but only for references from2983+ functions (or main program) subsequent to the re-definition.2984+ See also the section below on scoping.2985+2986+ examples:2987+ - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'2988+ input: '[[1,2],[10,20]]'2989+ output: ['[[1,2,1], [10,20,10]]']2990+ - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'2991+ input: '[[1,2],[10,20]]'2992+ output: ['[[1,2,1,2], [10,20,1,2]]']2993+2994+ - title: 'Scoping'2995+ body: |2996+2997+ There are two types of symbols in jq: value bindings (a.k.a.,2998+ "variables"), and functions. Both are scoped lexically,2999+ with expressions being able to refer only to symbols that3000+ have been defined "to the left" of them. The only exception3001+ to this rule is that functions can refer to themselves so as3002+ to be able to create recursive functions.3003+3004+ For example, in the following expression there is a binding3005+ which is visible "to the right" of it, `... | .*3 as3006+ $times_three | [. + $times_three] | ...`, but not "to the3007+ left". Consider this expression now, `... | (.*3 as3008+ $times_three | [. + $times_three]) | ...`: here the binding3009+ `$times_three` is _not_ visible past the closing parenthesis.3010+3011+ - title: "`isempty(exp)`"3012+ body: |3013+3014+ Returns true if `exp` produces no outputs, false otherwise.3015+3016+ examples:3017+ - program: 'isempty(empty)'3018+ input: 'null'3019+ output: ['true']3020+3021+ - program: 'isempty(.[])'3022+ input: '[]'3023+ output: ['true']3024+3025+ - program: 'isempty(.[])'3026+ input: '[1,2,3]'3027+ output: ['false']3028+3029+ - title: "`limit(n; exp)`"3030+ body: |3031+3032+ The `limit` function extracts up to `n` outputs from `exp`.3033+3034+ examples:3035+ - program: '[limit(3;.[])]'3036+ input: '[0,1,2,3,4,5,6,7,8,9]'3037+ output: ['[0,1,2]']3038+3039+ - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"3040+ body: |3041+3042+ The `first(expr)` and `last(expr)` functions extract the first3043+ and last values from `expr`, respectively.3044+3045+ The `nth(n; expr)` function extracts the nth value output by `expr`.3046+ Note that `nth(n; expr)` doesn't support negative values of `n`.3047+3048+ examples:3049+ - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'3050+ input: '10'3051+ output: ['[0,9,5]']3052+3053+ - title: "`first`, `last`, `nth(n)`"3054+ body: |3055+3056+ The `first` and `last` functions extract the first3057+ and last values from any array at `.`.3058+3059+ The `nth(n)` function extracts the nth value of any array at `.`.3060+3061+ examples:3062+ - program: '[range(.)]|[first, last, nth(5)]'3063+ input: '10'3064+ output: ['[0,9,5]']3065+3066+ - title: "`reduce`"3067+ body: |3068+3069+ The `reduce` syntax allows you to combine all of the results of3070+ an expression by accumulating them into a single answer.3071+ The form is `reduce EXP as $var (INIT; UPDATE)`.3072+ As an example, we'll pass `[1,2,3]` to this expression:3073+3074+ reduce .[] as $item (0; . + $item)3075+3076+ For each result that `.[]` produces, `. + $item` is run to3077+ accumulate a running total, starting from 0 as the input value.3078+ In this example, `.[]` produces the results `1`, `2`, and `3`,3079+ so the effect is similar to running something like this:3080+3081+ 0 | 1 as $item | . + $item |3082+ 2 as $item | . + $item |3083+ 3 as $item | . + $item3084+3085+ examples:3086+ - program: 'reduce .[] as $item (0; . + $item)'3087+ input: '[1,2,3,4,5]'3088+ output: ['15']3089+3090+ - program: 'reduce .[] as [$i,$j] (0; . + $i * $j)'3091+ input: '[[1,2],[3,4],[5,6]]'3092+ output: ['44']3093+3094+ - program: 'reduce .[] as {$x,$y} (null; .x += $x | .y += [$y])'3095+ input: '[{"x":"a","y":1},{"x":"b","y":2},{"x":"c","y":3}]'3096+ output: ['{"x":"abc","y":[1,2,3]}']3097+3098+ - title: "`foreach`"3099+ body: |3100+3101+ The `foreach` syntax is similar to `reduce`, but intended to3102+ allow the construction of `limit` and reducers that produce3103+ intermediate results.3104+3105+ The form is `foreach EXP as $var (INIT; UPDATE; EXTRACT)`.3106+ As an example, we'll pass `[1,2,3]` to this expression:3107+3108+ foreach .[] as $item (0; . + $item; [$item, . * 2])3109+3110+ Like the `reduce` syntax, `. + $item` is run for each result3111+ that `.[]` produces, but `[$item, . * 2]` is run for each3112+ intermediate values. In this example, since the intermediate3113+ values are `1`, `3`, and `6`, the `foreach` expression produces3114+ `[1,2]`, `[2,6]`, and `[3,12]`. So the effect is similar3115+ to running something like this:3116+3117+ 0 | 1 as $item | . + $item | [$item, . * 2],3118+ 2 as $item | . + $item | [$item, . * 2],3119+ 3 as $item | . + $item | [$item, . * 2]3120+3121+ When `EXTRACT` is omitted, the identity filter is used.3122+ That is, it outputs the intermediate values as they are.3123+3124+ examples:3125+ - program: 'foreach .[] as $item (0; . + $item)'3126+ input: '[1,2,3,4,5]'3127+ output: ['1','3','6','10','15']3128+3129+ - program: 'foreach .[] as $item (0; . + $item; [$item, . * 2])'3130+ input: '[1,2,3,4,5]'3131+ output: ['[1,2]','[2,6]','[3,12]','[4,20]','[5,30]']3132+3133+ - program: 'foreach .[] as $item (0; . + 1; {index: ., $item})'3134+ input: '["foo", "bar", "baz"]'3135+ output:3136+ - '{"index":1,"item":"foo"}'3137+ - '{"index":2,"item":"bar"}'3138+ - '{"index":3,"item":"baz"}'3139+3140+ - title: Recursion3141+ body: |3142+3143+ As described above, `recurse` uses recursion, and any jq3144+ function can be recursive. The `while` builtin is also3145+ implemented in terms of recursion.3146+3147+ Tail calls are optimized whenever the expression to the left of3148+ the recursive call outputs its last value. In practice this3149+ means that the expression to the left of the recursive call3150+ should not produce more than one output for each input.3151+3152+ For example:3153+3154+ def recurse(f): def r: ., (f | select(. != null) | r); r;3155+3156+ def while(cond; update):3157+ def _while:3158+ if cond then ., (update | _while) else empty end;3159+ _while;3160+3161+ def repeat(exp):3162+ def _repeat:3163+ exp, _repeat;3164+ _repeat;3165+3166+ - title: Generators and iterators3167+ body: |3168+3169+ Some jq operators and functions are actually generators in3170+ that they can produce zero, one, or more values for each3171+ input, just as one might expect in other programming3172+ languages that have generators. For example, `.[]`3173+ generates all the values in its input (which must be an3174+ array or an object), `range(0; 10)` generates the integers3175+ between 0 and 10, and so on.3176+3177+ Even the comma operator is a generator, generating first3178+ the values generated by the expression to the left of the3179+ comma, then the values generated by the expression on the3180+ right of the comma.3181+3182+ The `empty` builtin is the generator that produces zero3183+ outputs. The `empty` builtin backtracks to the preceding3184+ generator expression.3185+3186+ All jq functions can be generators just by using builtin3187+ generators. It is also possible to construct new generators3188+ using only recursion and the comma operator. If3189+ recursive calls are "in tail position" then the3190+ generator will be efficient. In the example below the3191+ recursive call by `_range` to itself is in tail position.3192+ The example shows off three advanced topics: tail recursion,3193+ generator construction, and sub-functions.3194+3195+ examples:3196+ - program: 'def range(init; upto; by):3197+ def _range:3198+ if (by > 0 and . < upto) or (by < 0 and . > upto)3199+ then ., ((.+by)|_range)3200+ else . end;3201+ if by == 0 then init else init|_range end |3202+ select((by > 0 and . < upto) or (by < 0 and . > upto));3203+ range(0; 10; 3)'3204+ input: 'null'3205+ output: ['0', '3', '6', '9']3206+ - program: 'def while(cond; update):3207+ def _while:3208+ if cond then ., (update | _while) else empty end;3209+ _while;3210+ [while(.<100; .*2)]'3211+ input: '1'3212+ output: ['[1,2,4,8,16,32,64]']3213+3214+ - title: 'Math'3215+ body: |3216+3217+ jq currently only has IEEE754 double-precision (64-bit) floating3218+ point number support.3219+3220+ Besides simple arithmetic operators such as `+`, jq also has most3221+ standard math functions from the C math library. C math functions3222+ that take a single input argument (e.g., `sin()`) are available as3223+ zero-argument jq functions. C math functions that take two input3224+ arguments (e.g., `pow()`) are available as two-argument jq3225+ functions that ignore `.`. C math functions that take three input3226+ arguments are available as three-argument jq functions that ignore3227+ `.`.3228+3229+ Availability of standard math functions depends on the3230+ availability of the corresponding math functions in your operating3231+ system and C math library. Unavailable math functions will be3232+ defined but will raise an error.3233+3234+ One-input C math functions: `acos` `acosh` `asin` `asinh` `atan`3235+ `atanh` `cbrt` `ceil` `cos` `cosh` `erf` `erfc` `exp` `exp10`3236+ `exp2` `expm1` `fabs` `floor` `gamma` `j0` `j1` `lgamma` `log`3237+ `log10` `log1p` `log2` `logb` `nearbyint` `rint` `round`3238+ `significand` `sin` `sinh` `sqrt` `tan` `tanh` `tgamma` `trunc`3239+ `y0` `y1`.3240+3241+ Two-input C math functions: `atan2` `copysign` `drem` `fdim`3242+ `fmax` `fmin` `fmod` `frexp` `hypot` `jn` `ldexp` `modf`3243+ `nextafter` `nexttoward` `pow` `remainder` `scalb` `scalbln` `yn`.3244+3245+ Three-input C math functions: `fma`.3246+3247+ See your system's manual for more information on each of these.3248+3249+ - title: 'I/O'3250+ body: |3251+3252+ At this time jq has minimal support for I/O, mostly in the3253+ form of control over when inputs are read. Two builtins functions3254+ are provided for this, `input` and `inputs`, that read from the3255+ same sources (e.g., `stdin`, files named on the command-line) as3256+ jq itself. These two builtins, and jq's own reading actions, can3257+ be interleaved with each other. They are commonly used in combination3258+ with the null input option `-n` to prevent one input from being read3259+ implicitly.3260+3261+ Two builtins provide minimal output capabilities, `debug`, and3262+ `stderr`. (Recall that a jq program's output values are always3263+ output as JSON texts on `stdout`.) The `debug` builtin can have3264+ application-specific behavior, such as for executables that use3265+ the libjq C API but aren't the jq executable itself. The `stderr`3266+ builtin outputs its input in raw mode to stder with no additional3267+ decoration, not even a newline.3268+3269+ Most jq builtins are referentially transparent, and yield constant3270+ and repeatable value streams when applied to constant inputs.3271+ This is not true of I/O builtins.3272+3273+ entries:3274+ - title: "`input`"3275+ body: |3276+3277+ Outputs one new input.3278+3279+ Note that when using `input` it is generally be necessary to3280+ invoke jq with the `-n` command-line option, otherwise3281+ the first entity will be lost.3282+3283+ echo 1 2 3 4 | jq '[., input]' # [1,2] [3,4]3284+3285+ - title: "`inputs`"3286+ body: |3287+3288+ Outputs all remaining inputs, one by one.3289+3290+ This is primarily useful for reductions over a program's3291+ inputs. Note that when using `inputs` it is generally necessary3292+ to invoke jq with the `-n` command-line option, otherwise3293+ the first entity will be lost.3294+3295+ echo 1 2 3 | jq -n 'reduce inputs as $i (0; . + $i)' # 63296+3297+ - title: "`debug`, `debug(msgs)`"3298+ body: |3299+3300+ These two filters are like `.` but have as a side-effect the3301+ production of one or more messages on stderr.3302+3303+ The message produced by the `debug` filter has the form3304+3305+ ["DEBUG:",<input-value>]3306+3307+ where `<input-value>` is a compact rendition of the input3308+ value. This format may change in the future.3309+3310+ The `debug(msgs)` filter is defined as `(msgs | debug | empty), .`3311+ thus allowing great flexibility in the content of the message,3312+ while also allowing multi-line debugging statements to be created.3313+3314+ For example, the expression:3315+3316+ 1 as $x | 2 | debug("Entering function foo with $x == \($x)", .) | (.+1)3317+3318+ would produce the value 3 but with the following two lines3319+ being written to stderr:3320+3321+ ["DEBUG:","Entering function foo with $x == 1"]3322+ ["DEBUG:",2]3323+3324+ - title: "`stderr`"3325+ body: |3326+3327+ Prints its input in raw and compact mode to stderr with no3328+ additional decoration, not even a newline.3329+3330+ - title: "`input_filename`"3331+ body: |3332+3333+ Returns the name of the file whose input is currently being3334+ filtered. Note that this will not work well unless jq is3335+ running in a UTF-8 locale.3336+3337+ - title: "`input_line_number`"3338+ body: |3339+3340+ Returns the line number of the input currently being filtered.3341+3342+ - title: 'Streaming'3343+ body: |3344+3345+ With the `--stream` option jq can parse input texts in a streaming3346+ fashion, allowing jq programs to start processing large JSON texts3347+ immediately rather than after the parse completes. If you have a3348+ single JSON text that is 1GB in size, streaming it will allow you3349+ to process it much more quickly.3350+3351+ However, streaming isn't easy to deal with as the jq program will3352+ have `[<path>, <leaf-value>]` (and a few other forms) as inputs.3353+3354+ Several builtins are provided to make handling streams easier.3355+3356+ The examples below use the streamed form of `[0,[1]]`, which is3357+ `[[0],0],[[1,0],1],[[1,0]],[[1]]`.3358+3359+ Streaming forms include `[<path>, <leaf-value>]` (to indicate any3360+ scalar value, empty array, or empty object), and `[<path>]` (to3361+ indicate the end of an array or object). Future versions of jq3362+ run with `--stream` and `--seq` may output additional forms such3363+ as `["error message"]` when an input text fails to parse.3364+3365+ entries:3366+ - title: "`truncate_stream(stream_expression)`"3367+ body: |3368+3369+ Consumes a number as input and truncates the corresponding3370+ number of path elements from the left of the outputs of the3371+ given streaming expression.3372+3373+ examples:3374+ - program: 'truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])'3375+ input: '1'3376+ output: ['[[0],2]', '[[0]]']3377+3378+ - title: "`fromstream(stream_expression)`"3379+ body: |3380+3381+ Outputs values corresponding to the stream expression's3382+ outputs.3383+3384+ examples:3385+ - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'3386+ input: 'null'3387+ output: ['[2]']3388+3389+ - title: "`tostream`"3390+ body: |3391+3392+ The `tostream` builtin outputs the streamed form of its input.3393+3394+ examples:3395+ - program: '. as $dot|fromstream($dot|tostream)|.==$dot'3396+ input: '[0,[1,{"a":1},{"b":2}]]'3397+ output: ['true']3398+3399+ - title: Assignment3400+ body: |3401+ Assignment works a little differently in jq than in most3402+ programming languages. jq doesn't distinguish between references3403+ to and copies of something - two objects or arrays are either3404+ equal or not equal, without any further notion of being "the3405+ same object" or "not the same object".3406+3407+ If an object has two fields which are arrays, `.foo` and `.bar`,3408+ and you append something to `.foo`, then `.bar` will not get3409+ bigger, even if you've previously set `.bar = .foo`. If you're3410+ used to programming in languages like Python, Java, Ruby,3411+ JavaScript, etc. then you can think of it as though jq does a full3412+ deep copy of every object before it does the assignment (for3413+ performance it doesn't actually do that, but that's the general3414+ idea).3415+3416+ This means that it's impossible to build circular values in jq3417+ (such as an array whose first element is itself). This is quite3418+ intentional, and ensures that anything a jq program can produce3419+ can be represented in JSON.3420+3421+ All the assignment operators in jq have path expressions on the3422+ left-hand side (LHS). The right-hand side (RHS) provides values3423+ to set to the paths named by the LHS path expressions.3424+3425+ Values in jq are always immutable. Internally, assignment works3426+ by using a reduction to compute new, replacement values for `.` that3427+ have had all the desired assignments applied to `.`, then3428+ outputting the modified value. This might be made clear by this3429+ example: `{a:{b:{c:1}}} | (.a.b|=3), .`. This will output3430+ `{"a":{"b":3}}` and `{"a":{"b":{"c":1}}}` because the last3431+ sub-expression, `.`, sees the original value, not the modified3432+ value.3433+3434+ Most users will want to use modification assignment operators,3435+ such as `|=` or `+=`, rather than `=`.3436+3437+ Note that the LHS of assignment operators refers to a value in3438+ `.`. Thus `$var.foo = 1` won't work as expected (`$var.foo` is3439+ not a valid or useful path expression in `.`); use `$var | .foo =3440+ 1` instead.3441+3442+ Note too that `.a,.b=0` does not set `.a` and `.b`, but3443+ `(.a,.b)=0` sets both.3444+3445+ entries:3446+ - title: "Update-assignment: `|=`"3447+ body: |3448+ This is the "update" operator `|=`. It takes a filter on the3449+ right-hand side and works out the new value for the property3450+ of `.` being assigned to by running the old value through this3451+ expression. For instance, `(.foo, .bar) |= .+1` will build an3452+ object with the `foo` field set to the input's `foo` plus 1,3453+ and the `bar` field set to the input's `bar` plus 1.3454+3455+ The left-hand side can be any general path expression; see `path()`.3456+3457+ Note that the left-hand side of `|=` refers to a value in `.`.3458+ Thus `$var.foo |= . + 1` won't work as expected (`$var.foo` is3459+ not a valid or useful path expression in `.`); use `$var |3460+ .foo |= . + 1` instead.3461+3462+ If the right-hand side outputs no values (i.e., `empty`), then3463+ the left-hand side path will be deleted, as with `del(path)`.3464+3465+ If the right-hand side outputs multiple values, only the first3466+ one will be used (COMPATIBILITY NOTE: in jq 1.5 and earlier3467+ releases, it used to be that only the last one was used).3468+3469+ examples:3470+ - program: '(..|select(type=="boolean")) |= if . then 1 else 0 end'3471+ input: '[true,false,[5,true,[true,[false]],false]]'3472+ output: ['[1,0,[5,1,[1,[0]],0]]']3473+3474+ - title: "Arithmetic update-assignment: `+=`, `-=`, `*=`, `/=`, `%=`, `//=`"3475+ body: |3476+3477+ jq has a few operators of the form `a op= b`, which are all3478+ equivalent to `a |= . op b`. So, `+= 1` can be used to3479+ increment values, being the same as `|= . + 1`.3480+3481+ examples:3482+ - program: .foo += 13483+ input: '{"foo": 42}'3484+ output: ['{"foo": 43}']3485+3486+ - title: "Plain assignment: `=`"3487+ body: |3488+3489+ This is the plain assignment operator. Unlike the others, the3490+ input to the right-hand side (RHS) is the same as the input to3491+ the left-hand side (LHS) rather than the value at the LHS3492+ path, and all values output by the RHS will be used (as shown3493+ below).3494+3495+ If the RHS of `=` produces multiple values, then for each such3496+ value jq will set the paths on the left-hand side to the value3497+ and then it will output the modified `.`. For example,3498+ `(.a,.b) = range(2)` outputs `{"a":0,"b":0}`, then3499+ `{"a":1,"b":1}`. The "update" assignment forms (see above) do3500+ not do this.3501+3502+ This example should show the difference between `=` and `|=`:3503+3504+ Provide input `{"a": {"b": 10}, "b": 20}` to the programs3505+3506+ .a = .b3507+3508+ and3509+3510+ .a |= .b3511+3512+ The former will set the `a` field of the input to the `b`3513+ field of the input, and produce the output `{"a": 20, "b": 20}`.3514+ The latter will set the `a` field of the input to the `a`3515+ field's `b` field, producing `{"a": 10, "b": 20}`.3516+3517+ examples:3518+ - program: .a = .b3519+ input: '{"a": {"b": 10}, "b": 20}'3520+ output: ['{"a":20,"b":20}']3521+3522+ - program: .a |= .b3523+ input: '{"a": {"b": 10}, "b": 20}'3524+ output: ['{"a":10,"b":20}']3525+3526+ - program: (.a, .b) = range(3)3527+ input: 'null'3528+ output:3529+ - '{"a":0,"b":0}'3530+ - '{"a":1,"b":1}'3531+ - '{"a":2,"b":2}'3532+3533+ - program: (.a, .b) |= range(3)3534+ input: 'null'3535+ output: ['{"a":0,"b":0}']3536+3537+ - title: Complex assignments3538+ body: |3539+ Lots more things are allowed on the left-hand side of a jq assignment3540+ than in most languages. We've already seen simple field accesses on3541+ the left hand side, and it's no surprise that array accesses work just3542+ as well:3543+3544+ .posts[0].title = "JQ Manual"3545+3546+ What may come as a surprise is that the expression on the left may3547+ produce multiple results, referring to different points in the input3548+ document:3549+3550+ .posts[].comments |= . + ["this is great"]3551+3552+ That example appends the string "this is great" to the "comments"3553+ array of each post in the input (where the input is an object with a3554+ field "posts" which is an array of posts).3555+3556+ When jq encounters an assignment like 'a = b', it records the "path"3557+ taken to select a part of the input document while executing a. This3558+ path is then used to find which part of the input to change while3559+ executing the assignment. Any filter may be used on the3560+ left-hand side of an equals - whichever paths it selects from the3561+ input will be where the assignment is performed.3562+3563+ This is a very powerful operation. Suppose we wanted to add a comment3564+ to blog posts, using the same "blog" input above. This time, we only3565+ want to comment on the posts written by "stedolan". We can find those3566+ posts using the "select" function described earlier:3567+3568+ .posts[] | select(.author == "stedolan")3569+3570+ The paths provided by this operation point to each of the posts that3571+ "stedolan" wrote, and we can comment on each of them in the same way3572+ that we did before:3573+3574+ (.posts[] | select(.author == "stedolan") | .comments) |=3575+ . + ["terrible."]3576+3577+ - title: Comments3578+3579+ body: |3580+3581+ You can write comments in your jq filters using `#`.3582+3583+ A `#` character (not part of a string) starts a comment.3584+ All characters from `#` to the end of the line are ignored.3585+3586+ If the end of the line is preceded by an odd number of backslash3587+ characters, the following line is also considered part of the3588+ comment and is ignored.3589+3590+ For example, the following code outputs `[1,3,4,7]`3591+3592+ [3593+ 1,3594+ # foo \3595+ 2,3596+ # bar \\3597+ 3,3598+ 4, # baz \\\3599+ 5, \3600+ 6,3601+ 73602+ # comment \3603+ comment \3604+ comment3605+ ]3606+3607+ Backslash continuing the comment on the next line can be useful3608+ when writing the "shebang" for a jq script:3609+3610+ #!/bin/sh --3611+ # total - Output the sum of the given arguments (or stdin)3612+ # usage: total [numbers...]3613+ # \3614+ exec jq --args -MRnf "$0" -- "$@"3615+3616+ $ARGS.positional |3617+ reduce (3618+ if . == []3619+ then inputs3620+ else .[]3621+ end |3622+ . as $dot |3623+ try tonumber catch false |3624+ if not or isnan then3625+ @json "total: Invalid number \($dot).\n" | halt_error(1)3626+ end3627+ ) as $n (0; . + $n)3628+3629+ The `exec` line is considered a comment by jq, so it is ignored.3630+ But it is not ignored by `sh`, since in `sh` a backslash at the3631+ end of the line does not continue the comment.3632+ With this trick, when the script is invoked as `total 1 2`,3633+ `/bin/sh -- /path/to/total 1 2` will be run, and `sh` will then3634+ run `exec jq --args -MRnf /path/to/total -- 1 2` replacing itself3635+ with a `jq` interpreter invoked with the specified options (`-M`,3636+ `-R`, `-n`, `--args`), that evaluates the current file (`$0`),3637+ with the arguments (`$@`) that were passed to `sh`.3638+3639+ - title: Modules3640+ body: |3641+3642+ jq has a library/module system. Modules are files whose names end3643+ in `.jq`.3644+3645+ Modules imported by a program are searched for in a default search3646+ path (see below). The `import` and `include` directives allow the3647+ importer to alter this path.3648+3649+ Paths in the search path are subject to various substitutions.3650+3651+ For paths starting with `~/`, the user's home directory is3652+ substituted for `~`.3653+3654+ For paths starting with `$ORIGIN/`, the directory where the jq3655+ executable is located is substituted for `$ORIGIN`.3656+3657+ For paths starting with `./` or paths that are `.`, the path of3658+ the including file is substituted for `.`. For top-level programs3659+ given on the command-line, the current directory is used.3660+3661+ Import directives can optionally specify a search path to which3662+ the default is appended.3663+3664+ The default search path is the search path given to the `-L`3665+ command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",3666+ "$ORIGIN/../lib"]`.3667+3668+ Null and empty string path elements terminate search path3669+ processing.3670+3671+ A dependency with relative path `foo/bar` would be searched for in3672+ `foo/bar.jq` and `foo/bar/bar.jq` in the given search path. This3673+ is intended to allow modules to be placed in a directory along3674+ with, for example, version control files, README files, and so on,3675+ but also to allow for single-file modules.3676+3677+ Consecutive components with the same name are not allowed to avoid3678+ ambiguities (e.g., `foo/foo`).3679+3680+ For example, with `-L$HOME/.jq` a module `foo` can be found in3681+ `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.3682+3683+ If `$HOME/.jq` is a file, it is sourced into the main program.3684+3685+ entries:3686+ - title: "`import RelativePathString as NAME [<metadata>];`"3687+ body: |3688+3689+ Imports a module found at the given path relative to a3690+ directory in a search path. A `.jq` suffix will be added to3691+ the relative path string. The module's symbols are prefixed3692+ with `NAME::`.3693+3694+ The optional metadata must be a constant jq expression. It3695+ should be an object with keys like `homepage` and so on. At3696+ this time jq only uses the `search` key/value of the metadata.3697+ The metadata is also made available to users via the3698+ `modulemeta` builtin.3699+3700+ The `search` key in the metadata, if present, should have a3701+ string or array value (array of strings); this is the search3702+ path to be prefixed to the top-level search path.3703+3704+ - title: "`include RelativePathString [<metadata>];`"3705+ body: |3706+3707+ Imports a module found at the given path relative to a3708+ directory in a search path as if it were included in place. A3709+ `.jq` suffix will be added to the relative path string. The3710+ module's symbols are imported into the caller's namespace as3711+ if the module's content had been included directly.3712+3713+ The optional metadata must be a constant jq expression. It3714+ should be an object with keys like `homepage` and so on. At3715+ this time jq only uses the `search` key/value of the metadata.3716+ The metadata is also made available to users via the3717+ `modulemeta` builtin.3718+3719+ - title: "`import RelativePathString as $NAME [<metadata>];`"3720+ body: |3721+3722+ Imports a JSON file found at the given path relative to a3723+ directory in a search path. A `.json` suffix will be added to3724+ the relative path string. The file's data will be available3725+ as `$NAME::NAME`.3726+3727+ The optional metadata must be a constant jq expression. It3728+ should be an object with keys like `homepage` and so on. At3729+ this time jq only uses the `search` key/value of the metadata.3730+ The metadata is also made available to users via the3731+ `modulemeta` builtin.3732+3733+ The `search` key in the metadata, if present, should have a3734+ string or array value (array of strings); this is the search3735+ path to be prefixed to the top-level search path.3736+3737+ - title: "`module <metadata>;`"3738+ body: |3739+3740+ This directive is entirely optional. It's not required for3741+ proper operation. It serves only the purpose of providing3742+ metadata that can be read with the `modulemeta` builtin.3743+3744+ The metadata must be a constant jq expression. It should be3745+ an object with keys like `homepage`. At this time jq doesn't3746+ use this metadata, but it is made available to users via the3747+ `modulemeta` builtin.3748+3749+ - title: "`modulemeta`"3750+ body: |3751+3752+ Takes a module name as input and outputs the module's metadata3753+ as an object, with the module's imports (including metadata)3754+ as an array value for the `deps` key and the module's defined3755+ functions as an array value for the `defs` key.3756+3757+ Programs can use this to query a module's metadata, which they3758+ could then use to, for example, search for, download, and3759+ install missing dependencies.3760+3761+ - title: Colors3762+ body: |3763+3764+ To configure alternative colors just set the `JQ_COLORS`3765+ environment variable to colon-delimited list of partial terminal3766+ escape sequences like `"1;31"`, in this order:3767+3768+ - color for `null`3769+ - color for `false`3770+ - color for `true`3771+ - color for numbers3772+ - color for strings3773+ - color for arrays3774+ - color for objects3775+ - color for object keys3776+3777+ The default color scheme is the same as setting3778+ `JQ_COLORS="0;90:0;39:0;39:0;39:0;32:1;39:1;39:1;34"`.3779+3780+ This is not a manual for VT100/ANSI escapes. However, each of3781+ these color specifications should consist of two numbers separated3782+ by a semi-colon, where the first number is one of these:3783+3784+ - 1 (bright)3785+ - 2 (dim)3786+ - 4 (underscore)3787+ - 5 (blink)3788+ - 7 (reverse)3789+ - 8 (hidden)3790+3791+ and the second is one of these:3792+3793+ - 30 (black)3794+ - 31 (red)3795+ - 32 (green)3796+ - 33 (yellow)3797+ - 34 (blue)3798+ - 35 (magenta)3799+ - 36 (cyan)3800+ - 37 (white)modified:docs/content/manual/v1.3/manual.yml-5 removed
1 ---2 headline: jq 1.3 Manual3 4-history: |5-6- *The manual for the development version of jq can be found7- [here](../).*8-4 body: |5 6 A jq program is a "filter": it takes an input, and produces an7 output. There are a lot of builtin filters for extracting a1252 unmodified linesmodified:docs/content/manual/v1.4/manual.yml-5 removed
1 ---2 headline: jq 1.4 Manual3 4-history: |5-6- *The manual for the development version of jq can be found7- [here](../).*8-4 body: |5 6 A jq program is a "filter": it takes an input, and produces an7 output. There are a lot of builtin filters for extracting a1658 unmodified linesmodified:docs/content/manual/v1.5/manual.yml-5 removed
1 ---2 headline: jq 1.5 Manual3 4-history: |5-6- *The manual for the development version of jq can be found7- [here](../).*8-4 body: |5 6 A jq program is a "filter": it takes an input, and produces an7 output. There are a lot of builtin filters for extracting a2922 unmodified linesmodified:docs/content/manual/v1.6/manual.yml-5 removed
1 ---2 headline: jq 1.6 Manual3 4-history: |5-6- *The manual for the development version of jq can be found7- [here](../).*8-4 body: |5 6 A jq program is a "filter": it takes an input, and produces an7 output. There are a lot of builtin filters for extracting a3356 unmodified linesmodified:docs/content/manual/v1.7/manual.yml-5 removed
1 ---2 headline: jq 1.7 Manual3 4-history: |5-6- *The manual for the development version of jq can be found7- [here](../).*8-4 body: |5 6 A jq program is a "filter": it takes an input, and produces an7 output. There are a lot of builtin filters for extracting a3690 unmodified linesmodified:docs/content/manual/manual.yml+1 added-3805 removed
1----2-headline: jq Manual (development version)3-4-history: |5-6- *For released versions, see [jq 1.7](./v1.7/), [jq 1.6](./v1.6/), [jq 1.5](./v1.5/),7- [jq 1.4](./v1.4/) or [jq 1.3](./v1.3/).*8-9-body: |10-11- 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.15-16- 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.19-20- 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.25-26- 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.33-34- But that's getting ahead of ourselves. :) Let's start with something35- simpler:36-37-manpage_intro: |38- jq(1) -- Command-line JSON processor39- ====================================40-41- ## SYNOPSIS42-43- `jq` [<options>...] <filter> [<files>...]44-45- `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.49-50- `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.55-56- 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.60-61- ## FILTERS62-63-manpage_epilogue: |64- ## BUGS65-66- Presumably. Report them or discuss them at:67-68- https://github.com/jqlang/jq/issues69-70- ## AUTHOR71-72- Stephen Dolan `<mu@netsoc.tcd.ie>`73-74-sections:75- - title: Invoking jq76- body: |77-78- jq filters run on a stream of JSON data. The input to jq is79- parsed as a sequence of whitespace-separated JSON values which80- are passed through the provided filter one at a time. The81- output(s) of the filter are written to standard output, as a82- sequence of newline-separated JSON data.83-84- The simplest and most common filter (or jq program) is `.`,85- which is the identity operator, copying the inputs of the jq86- processor to the output stream. Because the default behavior of87- the jq processor is to read JSON texts from the input stream,88- and to pretty-print outputs, the `.` program's main use is to89- validate and pretty-print the inputs. The jq programming90- language is quite rich and allows for much more than just91- validation and pretty-printing.92-93- Note: it is important to mind the shell's quoting rules. As a94- general rule it's best to always quote (with single-quote95- characters on Unix shells) the jq program, as too many characters with special96- meaning to jq are also shell meta-characters. For example, `jq97- "foo"` will fail on most Unix shells because that will be the same98- as `jq foo`, which will generally fail because `foo is not99- defined`. When using the Windows command shell (cmd.exe) it's100- best to use double quotes around your jq program when given on the101- command-line (instead of the `-f program-file` option), but then102- double-quotes in the jq program need backslash escaping. When using103- the Powershell (`powershell.exe`) or the Powershell Core104- (`pwsh`/`pwsh.exe`), use single-quote characters around the jq105- program and backslash-escaped double-quotes (`\"`) inside the jq106- program.107-108- * Unix shells: `jq '.["foo"]'`109- * Powershell: `jq '.[\"foo\"]'`110- * Windows command shell: `jq ".[\"foo\"]"`111-112- Note: jq allows user-defined functions, but every jq program113- must have a top-level expression.114-115- You can affect how jq reads and writes its input and output116- using some command-line options:117-118- * `--null-input` / `-n`:119-120- Don't read any input at all. Instead, the filter is run once121- using `null` as the input. This is useful when using jq as a122- simple calculator or to construct JSON data from scratch.123-124- * `--raw-input` / `-R`:125-126- Don't parse the input as JSON. Instead, each line of text is127- passed to the filter as a string. If combined with `--slurp`,128- then the entire input is passed to the filter as a single long129- string.130-131- * `--slurp` / `-s`:132-133- Instead of running the filter for each JSON object in the134- input, read the entire input stream into a large array and run135- the filter just once.136-137- * `--compact-output` / `-c`:138-139- By default, jq pretty-prints JSON output. Using this option140- will result in more compact output by instead putting each141- JSON object on a single line.142-143- * `--raw-output` / `-r`:144-145- With this option, if the filter's result is a string then it146- will be written directly to standard output rather than being147- formatted as a JSON string with quotes. This can be useful for148- making jq filters talk to non-JSON-based systems.149-150- * `--raw-output0`:151-152- Like `-r` but jq will print NUL instead of newline after each output.153- This can be useful when the values being output can contain newlines.154- When the output value contains NUL, jq exits with non-zero code.155-156- * `--join-output` / `-j`:157-158- Like `-r` but jq won't print a newline after each output.159-160- * `--ascii-output` / `-a`:161-162- jq usually outputs non-ASCII Unicode codepoints as UTF-8, even163- if the input specified them as escape sequences (like164- "\u03bc"). Using this option, you can force jq to produce pure165- ASCII output with every non-ASCII character replaced with the166- equivalent escape sequence.167-168- * `--sort-keys` / `-S`:169-170- Output the fields of each object with the keys in sorted order.171-172- * `--color-output` / `-C` and `--monochrome-output` / `-M`:173-174- By default, jq outputs colored JSON if writing to a175- terminal. You can force it to produce color even if writing to176- a pipe or a file using `-C`, and disable color with `-M`.177- When the `NO_COLOR` environment variable is not empty, jq disables178- colored output by default, but you can enable it by `-C`.179-180- Colors can be configured with the `JQ_COLORS` environment181- variable (see below).182-183- * `--tab`:184-185- Use a tab for each indentation level instead of two spaces.186-187- * `--indent n`:188-189- Use the given number of spaces (no more than 7) for indentation.190-191- * `--unbuffered`:192-193- Flush the output after each JSON object is printed (useful if194- you're piping a slow data source into jq and piping jq's195- output elsewhere).196-197- * `--stream`:198-199- Parse the input in streaming fashion, outputting arrays of path200- and leaf values (scalars and empty arrays or empty objects).201- For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]`202- becomes `[[0],[]]`, `[[1],"a"]`, and `[[2,0],"b"]`.203-204- This is useful for processing very large inputs. Use this in205- conjunction with filtering and the `reduce` and `foreach` syntax206- to reduce large inputs incrementally.207-208- * `--stream-errors`:209-210- Like `--stream`, but invalid JSON inputs yield array values211- where the first element is the error and the second is a path.212- For example, `["a",n]` produces `["Invalid literal at line 1,213- column 7",[1]]`.214-215- Implies `--stream`. Invalid JSON inputs produce no error values216- when `--stream` without `--stream-errors`.217-218- * `--seq`:219-220- Use the `application/json-seq` MIME type scheme for separating221- JSON texts in jq's input and output. This means that an ASCII222- RS (record separator) character is printed before each value on223- output and an ASCII LF (line feed) is printed after every224- output. Input JSON texts that fail to parse are ignored (but225- warned about), discarding all subsequent input until the next226- RS. This mode also parses the output of jq without the `--seq`227- option.228-229- * `-f filename` / `--from-file filename`:230-231- Read filter from the file rather than from a command line, like232- awk's -f option.233-234- * `-L directory`:235-236- Prepend `directory` to the search list for modules. If this237- option is used then no builtin search list is used. See the238- section on modules below.239-240- * `--arg name value`:241-242- This option passes a value to the jq program as a predefined243- variable. If you run jq with `--arg foo bar`, then `$foo` is244- available in the program and has the value `"bar"`. Note that245- `value` will be treated as a string, so `--arg foo 123` will246- bind `$foo` to `"123"`.247-248- Named arguments are also available to the jq program as249- `$ARGS.named`.250-251- * `--argjson name JSON-text`:252-253- This option passes a JSON-encoded value to the jq program as a254- predefined variable. If you run jq with `--argjson foo 123`, then255- `$foo` is available in the program and has the value `123`.256-257- * `--slurpfile variable-name filename`:258-259- This option reads all the JSON texts in the named file and binds260- an array of the parsed JSON values to the given global variable.261- If you run jq with `--slurpfile foo bar`, then `$foo` is available262- in the program and has an array whose elements correspond to the263- texts in the file named `bar`.264-265- * `--rawfile variable-name filename`:266-267- This option reads in the named file and binds its contents to the given268- global variable. If you run jq with `--rawfile foo bar`, then `$foo` is269- available in the program and has a string whose contents are to the texts270- in the file named `bar`.271-272- * `--args`:273-274- Remaining arguments are positional string arguments. These are275- available to the jq program as `$ARGS.positional[]`.276-277- * `--jsonargs`:278-279- Remaining arguments are positional JSON text arguments. These280- are available to the jq program as `$ARGS.positional[]`.281-282- * `--exit-status` / `-e`:283-284- Sets the exit status of jq to 0 if the last output value was285- neither `false` nor `null`, 1 if the last output value was286- either `false` or `null`, or 4 if no valid result was ever287- produced. Normally jq exits with 2 if there was any usage288- problem or system error, 3 if there was a jq program compile289- error, or 0 if the jq program ran.290-291- Another way to set the exit status is with the `halt_error`292- builtin function.293-294- * `--binary` / `-b`:295-296- Windows users using WSL, MSYS2, or Cygwin, should use this option297- when using a native jq.exe, otherwise jq will turn newlines (LFs)298- into carriage-return-then-newline (CRLF).299-300- * `--version` / `-V`:301-302- Output the jq version and exit with zero.303-304- * `--build-configuration`:305-306- Output the build configuration of jq and exit with zero.307- This output has no supported format or structure and may change308- without notice in future releases.309-310- * `--help` / `-h`:311-312- Output the jq help and exit with zero.313-314- * `--`:315-316- Terminates argument processing. Remaining arguments are not317- interpreted as options.318-319- * `--run-tests [filename]`:320-321- Runs the tests in the given file or standard input. This must322- be the last option given and does not honor all preceding323- options. The input consists of comment lines, empty lines, and324- program lines followed by one input line, as many lines of325- output as are expected (one per output), and a terminating empty326- line. Compilation failure tests start with a line containing327- only `%%FAIL`, then a line containing the program to compile,328- then a line containing an error message to compare to the329- actual.330-331- Be warned that this option can change backwards-incompatibly.332-333- - title: Basic filters334- entries:335- - title: "Identity: `.`"336- body: |337-338- The absolute simplest filter is `.` . This filter takes its339- input and produces the same value as output. That is, this340- is the identity operator.341-342- Since jq by default pretty-prints all output, a trivial343- program consisting of nothing but `.` can be used to format344- JSON output from, say, `curl`.345-346- Although the identity filter never modifies the value of its347- input, jq processing can sometimes make it appear as though348- it does. For example, using the current implementation of349- jq, we would see that the expression:350-351- 1E1234567890 | .352-353- produces `1.7976931348623157e+308` on at least one platform.354- This is because, in the process of parsing the number, this355- particular version of jq has converted it to an IEEE754356- double-precision representation, losing precision.357-358- The way in which jq handles numbers has changed over time359- and further changes are likely within the parameters set by360- the relevant JSON standards. Moreover, build configuration361- options can alter how jq processes numbers.362-363- The following remarks are therefore offered with the364- understanding that they are intended to be descriptive of the365- current version of jq and should not be interpreted as being366- prescriptive:367-368- (1) Any arithmetic operation on a number that has not369- already been converted to an IEEE754 double precision370- representation will trigger a conversion to the IEEE754371- representation.372-373- (2) jq will attempt to maintain the original decimal374- precision of number literals (if the `--disable-decnum`375- build configuration option was not used), but in expressions376- such `1E1234567890`, precision will be lost if the exponent377- is too large.378-379- (3) In jq programs, a leading minus sign will trigger the380- conversion of the number to an IEEE754 representation.381-382- (4) Comparisons are carried out using the untruncated383- big decimal representation of numbers if available, as384- illustrated in one of the following examples.385-386- The examples below use the builtin function `have_decnum` in387- order to demonstrate the expected effects of using / not388- using the `--disable-decnum` build configuration option, and389- also to allow automated tests derived from these examples to390- pass regardless of whether that option is used.391-392- examples:393- - program: '.'394- input: '"Hello, world!"'395- output: ['"Hello, world!"']396-397- - program: '.'398- input: '0.12345678901234567890123456789'399- output: ['0.12345678901234567890123456789']400-401- - program: '[., tojson] | . == if have_decnum then [12345678909876543212345,"12345678909876543212345"] else [12345678909876543000000,"12345678909876543000000"] end'402- input: '12345678909876543212345'403- output: ['true']404-405- - program: '. < 0.12345678901234567890123456788'406- input: '0.12345678901234567890123456789'407- output: ['false']408-409- - program: 'map([., . == 1]) | tojson | . == if have_decnum then "[[1,true],[1.000,true],[1.0,true],[1.00,true]]" else "[[1,true],[1,true],[1,true],[1,true]]" end'410- input: '[1, 1.000, 1.0, 100e-2]'411- output: ['true']412-413- - program: '. as $big | [$big, $big + 1] | map(. > 10000000000000000000000000000000) | . == if have_decnum then [true, false] else [false, false] end'414- input: '10000000000000000000000000000001'415- output: ['true']416-417- - title: "Object Identifier-Index: `.foo`, `.foo.bar`"418- body: |419-420- The simplest *useful* filter has the form `.foo`. When given a421- JSON object (aka dictionary or hash) as input, `.foo` produces422- the value at the key "foo" if the key is present, or null otherwise.423-424- A filter of the form `.foo.bar` is equivalent to `.foo | .bar`.425-426- The `.foo` syntax only works for simple, identifier-like keys, that427- is, keys that are all made of alphanumeric characters and428- underscore, and which do not start with a digit.429-430- If the key contains special characters or starts with a digit,431- you need to surround it with double quotes like this:432- `."foo$"`, or else `.["foo$"]`.433-434- For example `.["foo::bar"]` and `.["foo.bar"]` work while435- `.foo::bar` does not.436-437- examples:438- - program: '.foo'439- input: '{"foo": 42, "bar": "less interesting data"}'440- output: ['42']441-442- - program: '.foo'443- input: '{"notfoo": true, "alsonotfoo": false}'444- output: ['null']445-446- - program: '.["foo"]'447- input: '{"foo": 42}'448- output: ['42']449-450- - title: "Optional Object Identifier-Index: `.foo?`"451- body: |452-453- Just like `.foo`, but does not output an error when `.` is not an454- object.455-456- examples:457- - program: '.foo?'458- input: '{"foo": 42, "bar": "less interesting data"}'459- output: ['42']460- - program: '.foo?'461- input: '{"notfoo": true, "alsonotfoo": false}'462- output: ['null']463- - program: '.["foo"]?'464- input: '{"foo": 42}'465- output: ['42']466- - program: '[.foo?]'467- input: '[1,2]'468- output: ['[]']469-470- - title: "Object Index: `.[<string>]`"471- body: |472-473- You can also look up fields of an object using syntax like474- `.["foo"]` (`.foo` above is a shorthand version of this, but475- only for identifier-like strings).476-477- - title: "Array Index: `.[<number>]`"478- body: |479-480- When the index value is an integer, `.[<number>]` can index481- arrays. Arrays are zero-based, so `.[2]` returns the third482- element.483-484- Negative indices are allowed, with -1 referring to the last485- element, -2 referring to the next to last element, and so on.486-487- examples:488- - program: '.[0]'489- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'490- output: ['{"name":"JSON", "good":true}']491-492- - program: '.[2]'493- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'494- output: ['null']495-496- - program: '.[-2]'497- input: '[1,2,3]'498- output: ['2']499-500- - title: "Array/String Slice: `.[<number>:<number>]`"501- body: |502-503- The `.[<number>:<number>]` syntax can be used to return a504- subarray of an array or substring of a string. The array505- returned by `.[10:15]` will be of length 5, containing the506- elements from index 10 (inclusive) to index 15 (exclusive).507- Either index may be negative (in which case it counts508- backwards from the end of the array), or omitted (in which509- case it refers to the start or end of the array).510- Indices are zero-based.511-512- examples:513- - program: '.[2:4]'514- input: '["a","b","c","d","e"]'515- output: ['["c", "d"]']516-517- - program: '.[2:4]'518- input: '"abcdefghi"'519- output: ['"cd"']520-521- - program: '.[:3]'522- input: '["a","b","c","d","e"]'523- output: ['["a", "b", "c"]']524-525- - program: '.[-2:]'526- input: '["a","b","c","d","e"]'527- output: ['["d", "e"]']528-529- - title: "Array/Object Value Iterator: `.[]`"530- body: |531-532- If you use the `.[index]` syntax, but omit the index533- entirely, it will return *all* of the elements of an534- array. Running `.[]` with the input `[1,2,3]` will produce the535- numbers as three separate results, rather than as a single536- array. A filter of the form `.foo[]` is equivalent to537- `.foo | .[]`.538-539- You can also use this on an object, and it will return all540- the values of the object.541-542- Note that the iterator operator is a generator of values.543-544- examples:545- - program: '.[]'546- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'547- output:548- - '{"name":"JSON", "good":true}'549- - '{"name":"XML", "good":false}'550-551- - program: '.[]'552- input: '[]'553- output: []554-555- - program: '.foo[]'556- input: '{"foo":[1,2,3]}'557- output: ['1','2','3']558-559- - program: '.[]'560- input: '{"a": 1, "b": 1}'561- output: ['1', '1']562-563- - title: "`.[]?`"564- body: |565-566- Like `.[]`, but no errors will be output if . is not an array567- or object. A filter of the form `.foo[]?` is equivalent to568- `.foo | .[]?`.569-570- - title: "Comma: `,`"571- body: |572-573- If two filters are separated by a comma, then the574- same input will be fed into both and the two filters' output575- value streams will be concatenated in order: first, all of the576- outputs produced by the left expression, and then all of the577- outputs produced by the right. For instance, filter `.foo,578- .bar`, produces both the "foo" fields and "bar" fields as579- separate outputs.580-581- The `,` operator is one way to construct generators.582-583- examples:584- - program: '.foo, .bar'585- input: '{"foo": 42, "bar": "something else", "baz": true}'586- output: ['42', '"something else"']587-588- - program: ".user, .projects[]"589- input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'590- output: ['"stedolan"', '"jq"', '"wikiflow"']591-592- - program: '.[4,2]'593- input: '["a","b","c","d","e"]'594- output: ['"e"', '"c"']595-596- - title: "Pipe: `|`"597- body: |598-599- The | operator combines two filters by feeding the output(s) of600- the one on the left into the input of the one on the right. It's601- similar to the Unix shell's pipe, if you're used to that.602-603- If the one on the left produces multiple results, the one on604- the right will be run for each of those results. So, the605- expression `.[] | .foo` retrieves the "foo" field of each606- element of the input array. This is a cartesian product,607- which can be surprising.608-609- Note that `.a.b.c` is the same as `.a | .b | .c`.610-611- Note too that `.` is the input value at the particular stage612- in a "pipeline", specifically: where the `.` expression appears.613- Thus `.a | . | .b` is the same as `.a.b`, as the `.` in the614- middle refers to whatever value `.a` produced.615-616- examples:617- - program: '.[] | .name'618- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'619- output: ['"JSON"', '"XML"']620-621- - title: "Parenthesis"622- body: |623-624- Parenthesis work as a grouping operator just as in any typical625- programming language.626-627- examples:628- - program: '(. + 2) * 5'629- input: '1'630- output: ['15']631-632- - title: Types and Values633- body: |634-635- jq supports the same set of datatypes as JSON - numbers,636- strings, booleans, arrays, objects (which in JSON-speak are637- hashes with only string keys), and "null".638-639- Booleans, null, strings and numbers are written the same way as640- in JSON. Just like everything else in jq, these simple641- values take an input and produce an output - `42` is a valid jq642- expression that takes an input, ignores it, and returns 42643- instead.644-645- Numbers in jq are internally represented by their IEEE754 double646- precision approximation. Any arithmetic operation with numbers,647- whether they are literals or results of previous filters, will648- produce a double precision floating point result.649-650- However, when parsing a literal jq will store the original literal651- string. If no mutation is applied to this value then it will make652- to the output in its original form, even if conversion to double653- would result in a loss.654-655- entries:656- - title: "Array construction: `[]`"657- body: |658-659- As in JSON, `[]` is used to construct arrays, as in660- `[1,2,3]`. The elements of the arrays can be any jq661- expression, including a pipeline. All of the results produced662- by all of the expressions are collected into one big array.663- You can use it to construct an array out of a known quantity664- of values (as in `[.foo, .bar, .baz]`) or to "collect" all the665- results of a filter into an array (as in `[.items[].name]`)666-667- Once you understand the "," operator, you can look at jq's array668- syntax in a different light: the expression `[1,2,3]` is not using a669- built-in syntax for comma-separated arrays, but is instead applying670- the `[]` operator (collect results) to the expression 1,2,3 (which671- produces three different results).672-673- If you have a filter `X` that produces four results,674- then the expression `[X]` will produce a single result, an675- array of four elements.676-677- examples:678- - program: "[.user, .projects[]]"679- input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'680- output: ['["stedolan", "jq", "wikiflow"]']681- - program: "[ .[] | . * 2]"682- input: '[1, 2, 3]'683- output: ['[2, 4, 6]']684-685- - title: "Object Construction: `{}`"686- body: |687-688- Like JSON, `{}` is for constructing objects (aka689- dictionaries or hashes), as in: `{"a": 42, "b": 17}`.690-691- If the keys are "identifier-like", then the quotes can be left692- off, as in `{a:42, b:17}`. Variable references as key693- expressions use the value of the variable as the key. Key694- expressions other than constant literals, identifiers, or695- variable references, need to be parenthesized, e.g.,696- `{("a"+"b"):59}`.697-698- The value can be any expression (although you may need to wrap699- it in parentheses if, for example, it contains colons), which700- gets applied to the {} expression's input (remember, all701- filters have an input and an output).702-703- {foo: .bar}704-705- will produce the JSON object `{"foo": 42}` if given the JSON706- object `{"bar":42, "baz":43}` as its input. You can use this707- to select particular fields of an object: if the input is an708- object with "user", "title", "id", and "content" fields and709- you just want "user" and "title", you can write710-711- {user: .user, title: .title}712-713- Because that is so common, there's a shortcut syntax for it:714- `{user, title}`.715-716- If one of the expressions produces multiple results,717- multiple dictionaries will be produced. If the input's718-719- {"user":"stedolan","titles":["JQ Primer", "More JQ"]}720-721- then the expression722-723- {user, title: .titles[]}724-725- will produce two outputs:726-727- {"user":"stedolan", "title": "JQ Primer"}728- {"user":"stedolan", "title": "More JQ"}729-730- Putting parentheses around the key means it will be evaluated as an731- expression. With the same input as above,732-733- {(.user): .titles}734-735- produces736-737- {"stedolan": ["JQ Primer", "More JQ"]}738-739- Variable references as keys use the value of the variable as740- the key. Without a value then the variable's name becomes the741- key and its value becomes the value,742-743- "f o o" as $foo | "b a r" as $bar | {$foo, $bar:$foo}744-745- produces746-747- {"foo":"f o o","b a r":"f o o"}748-749- examples:750- - program: '{user, title: .titles[]}'751- input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'752- output:753- - '{"user":"stedolan", "title": "JQ Primer"}'754- - '{"user":"stedolan", "title": "More JQ"}'755- - program: '{(.user): .titles}'756- input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'757- output: ['{"stedolan": ["JQ Primer", "More JQ"]}']758-759- - title: "Recursive Descent: `..`"760- body: |761-762- Recursively descends `.`, producing every value. This is the763- same as the zero-argument `recurse` builtin (see below). This764- is intended to resemble the XPath `//` operator. Note that765- `..a` does not work; use `.. | .a` instead. In the example766- below we use `.. | .a?` to find all the values of object keys767- "a" in any object found "below" `.`.768-769- This is particularly useful in conjunction with `path(EXP)`770- (also see below) and the `?` operator.771-772- examples:773- - program: '.. | .a?'774- input: '[[{"a":1}]]'775- output: ['1']776-777- - title: Builtin operators and functions778- body: |779-780- Some jq operators (for instance, `+`) do different things781- depending on the type of their arguments (arrays, numbers,782- etc.). However, jq never does implicit type conversions. If you783- try to add a string to an object you'll get an error message and784- no result.785-786- Please note that all numbers are converted to IEEE754 double precision787- floating point representation. Arithmetic and logical operators are working788- with these converted doubles. Results of all such operations are also limited789- to the double precision.790-791- The only exception to this behaviour of number is a snapshot of original number792- literal. When a number which originally was provided as a literal is never793- mutated until the end of the program then it is printed to the output in its794- original literal form. This also includes cases when the original literal795- would be truncated when converted to the IEEE754 double precision floating point796- number.797-798- entries:799- - title: "Addition: `+`"800- body: |801-802- The operator `+` takes two filters, applies them both803- to the same input, and adds the results together. What804- "adding" means depends on the types involved:805-806- - **Numbers** are added by normal arithmetic.807-808- - **Arrays** are added by being concatenated into a larger array.809-810- - **Strings** are added by being joined into a larger string.811-812- - **Objects** are added by merging, that is, inserting all813- the key-value pairs from both objects into a single814- combined object. If both objects contain a value for the815- same key, the object on the right of the `+` wins. (For816- recursive merge use the `*` operator.)817-818- `null` can be added to any value, and returns the other819- value unchanged.820-821- examples:822- - program: '.a + 1'823- input: '{"a": 7}'824- output: ['8']825- - program: '.a + .b'826- input: '{"a": [1,2], "b": [3,4]}'827- output: ['[1,2,3,4]']828- - program: '.a + null'829- input: '{"a": 1}'830- output: ['1']831- - program: '.a + 1'832- input: '{}'833- output: ['1']834- - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'835- input: 'null'836- output: ['{"a": 42, "b": 2, "c": 3}']837-838- - title: "Subtraction: `-`"839- body: |840-841- As well as normal arithmetic subtraction on numbers, the `-`842- operator can be used on arrays to remove all occurrences of843- the second array's elements from the first array.844-845- examples:846- - program: '4 - .a'847- input: '{"a":3}'848- output: ['1']849- - program: . - ["xml", "yaml"]850- input: '["xml", "yaml", "json"]'851- output: ['["json"]']852-853- - title: "Multiplication, division, modulo: `*`, `/`, `%`"854- body: |855-856- These infix operators behave as expected when given two numbers.857- Division by zero raises an error. `x % y` computes x modulo y.858-859- Multiplying a string by a number produces the concatenation of860- that string that many times. `"x" * 0` produces `""`.861-862- Dividing a string by another splits the first using the second863- as separators.864-865- Multiplying two objects will merge them recursively: this works866- like addition but if both objects contain a value for the867- same key, and the values are objects, the two are merged with868- the same strategy.869-870- examples:871- - program: '10 / . * 3'872- input: '5'873- output: ['6']874- - program: '. / ", "'875- input: '"a, b,c,d, e"'876- output: ['["a","b,c,d","e"]']877- - program: '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'878- input: 'null'879- output: ['{"k": {"a": 0, "b": 2, "c": 3}}']880- - program: '.[] | (1 / .)?'881- input: '[1,0,-1]'882- output: ['1', '-1']883-884- - title: "`abs`"885- body: |886-887- The builtin function `abs` is defined naively as: `if . < 0 then - . else . end`.888-889- For numeric input, this is the absolute value. See the890- section on the identity filter for the implications of this891- definition for numeric input.892-893- To compute the absolute value of a number as a floating point number, you may wish use `fabs`.894-895- examples:896- - program: 'map(abs)'897- input: '[-10, -1.1, -1e-1]'898- output: ['[10,1.1,1e-1]']899-900- - title: "`length`"901- body: |902-903- The builtin function `length` gets the length of various904- different types of value:905-906- - The length of a **string** is the number of Unicode907- codepoints it contains (which will be the same as its908- JSON-encoded length in bytes if it's pure ASCII).909-910- - The length of a **number** is its absolute value.911-912- - The length of an **array** is the number of elements.913-914- - The length of an **object** is the number of key-value pairs.915-916- - The length of **null** is zero.917-918- - It is an error to use `length` on a **boolean**.919-920- examples:921- - program: '.[] | length'922- input: '[[1,2], "string", {"a":2}, null, -5]'923- output: ['2', '6', '1', '0', '5']924-925-926- - title: "`utf8bytelength`"927- body: |928-929- The builtin function `utf8bytelength` outputs the number of930- bytes used to encode a string in UTF-8.931-932- examples:933- - program: 'utf8bytelength'934- input: '"\u03bc"'935- output: ['2']936-937- - title: "`keys`, `keys_unsorted`"938- body: |939-940- The builtin function `keys`, when given an object, returns941- its keys in an array.942-943- The keys are sorted "alphabetically", by unicode codepoint944- order. This is not an order that makes particular sense in945- any particular language, but you can count on it being the946- same for any two objects with the same set of keys,947- regardless of locale settings.948-949- When `keys` is given an array, it returns the valid indices950- for that array: the integers from 0 to length-1.951-952- The `keys_unsorted` function is just like `keys`, but if953- the input is an object then the keys will not be sorted,954- instead the keys will roughly be in insertion order.955-956- examples:957- - program: 'keys'958- input: '{"abc": 1, "abcd": 2, "Foo": 3}'959- output: ['["Foo", "abc", "abcd"]']960- - program: 'keys'961- input: '[42,3,35]'962- output: ['[0,1,2]']963-964- - title: "`has(key)`"965- body: |966-967- The builtin function `has` returns whether the input object968- has the given key, or the input array has an element at the969- given index.970-971- `has($key)` has the same effect as checking whether `$key`972- is a member of the array returned by `keys`, although `has`973- will be faster.974-975- examples:976- - program: 'map(has("foo"))'977- input: '[{"foo": 42}, {}]'978- output: ['[true, false]']979- - program: 'map(has(2))'980- input: '[[0,1], ["a","b","c"]]'981- output: ['[false, true]']982-983- - title: "`in`"984- body: |985-986- The builtin function `in` returns whether or not the input key is in the987- given object, or the input index corresponds to an element988- in the given array. It is, essentially, an inversed version989- of `has`.990-991- examples:992- - program: '.[] | in({"foo": 42})'993- input: '["foo", "bar"]'994- output: ['true', 'false']995- - program: 'map(in([0,1]))'996- input: '[2, 0]'997- output: ['[false, true]']998-999- - title: "`map(f)`, `map_values(f)`"1000- body: |1001-1002- For any filter `f`, `map(f)` and `map_values(f)` apply `f`1003- to each of the values in the input array or object, that is,1004- to the values of `.[]`.1005-1006- In the absence of errors, `map(f)` always outputs an array1007- whereas `map_values(f)` outputs an array if given an array,1008- or an object if given an object.1009-1010- When the input to `map_values(f)` is an object, the output1011- object has the same keys as the input object except for1012- those keys whose values when piped to `f` produce no values1013- at all.1014-1015- The key difference between `map(f)` and `map_values(f)` is1016- that the former simply forms an array from all the values of1017- `($x|f)` for each value, $x, in the input array or object,1018- but `map_values(f)` only uses `first($x|f)`.1019-1020- Specifically, for object inputs, `map_values(f)` constructs1021- the output object by examining in turn the value of1022- `first(.[$k]|f)` for each key, $k, of the input. If this1023- expression produces no values, then the corresponding key1024- will be dropped; otherwise, the output object will have that1025- value at the key, $k.1026-1027- Here are some examples to clarify the behavior of `map` and1028- `map_values` when applied to arrays. These examples assume the1029- input is `[1]` in all cases:1030-1031- map(.+1) #=> [2]1032- map(., .) #=> [1,1]1033- map(empty) #=> []1034-1035- map_values(.+1) #=> [2]1036- map_values(., .) #=> [1]1037- map_values(empty) #=> []1038-1039- `map(f)` is equivalent to `[.[] | f]` and1040- `map_values(f)` is equivalent to `.[] |= f`.1041-1042- In fact, these are their implementations.1043-1044-1045- examples:1046- - program: 'map(.+1)'1047- input: '[1,2,3]'1048- output: ['[2,3,4]']1049-1050- - program: 'map_values(.+1)'1051- input: '{"a": 1, "b": 2, "c": 3}'1052- output: ['{"a": 2, "b": 3, "c": 4}']1053-1054- - program: 'map(., .)'1055- input: '[1,2]'1056- output: ['[1,1,2,2]']1057-1058- - program: 'map_values(. // empty)'1059- input: '{"a": null, "b": true, "c": false}'1060- output: ['{"b":true}']1061-1062-1063- - title: "`pick(pathexps)`"1064- body: |1065-1066- Emit the projection of the input object or array defined by the1067- specified sequence of path expressions, such that if `p` is any1068- one of these specifications, then `(. | p)` will evaluate to the1069- same value as `(. | pick(pathexps) | p)`. For arrays, negative1070- indices and `.[m:n]` specifications should not be used.1071-1072- examples:1073- - program: 'pick(.a, .b.c, .x)'1074- input: '{"a": 1, "b": {"c": 2, "d": 3}, "e": 4}'1075- output: ['{"a":1,"b":{"c":2},"x":null}']1076-1077- - program: 'pick(.[2], .[0], .[0])'1078- input: '[1,2,3,4]'1079- output: ['[1,null,3]']1080-1081-1082- - title: "`path(path_expression)`"1083- body: |1084-1085- Outputs array representations of the given path expression1086- in `.`. The outputs are arrays of strings (object keys)1087- and/or numbers (array indices).1088-1089- Path expressions are jq expressions like `.a`, but also `.[]`.1090- There are two types of path expressions: ones that can match1091- exactly, and ones that cannot. For example, `.a.b.c` is an1092- exact match path expression, while `.a[].b` is not.1093-1094- `path(exact_path_expression)` will produce the array1095- representation of the path expression even if it does not1096- exist in `.`, if `.` is `null` or an array or an object.1097-1098- `path(pattern)` will produce array representations of the1099- paths matching `pattern` if the paths exist in `.`.1100-1101- Note that the path expressions are not different from normal1102- expressions. The expression1103- `path(..|select(type=="boolean"))` outputs all the paths to1104- boolean values in `.`, and only those paths.1105-1106- examples:1107- - program: 'path(.a[0].b)'1108- input: 'null'1109- output: ['["a",0,"b"]']1110- - program: '[path(..)]'1111- input: '{"a":[{"b":1}]}'1112- output: ['[[],["a"],["a",0],["a",0,"b"]]']1113-1114- - title: "`del(path_expression)`"1115- body: |1116-1117- The builtin function `del` removes a key and its corresponding1118- value from an object.1119-1120- examples:1121- - program: 'del(.foo)'1122- input: '{"foo": 42, "bar": 9001, "baz": 42}'1123- output: ['{"bar": 9001, "baz": 42}']1124- - program: 'del(.[1, 2])'1125- input: '["foo", "bar", "baz"]'1126- output: ['["foo"]']1127-1128- - title: "`getpath(PATHS)`"1129- body: |1130-1131- The builtin function `getpath` outputs the values in `.` found1132- at each path in `PATHS`.1133-1134- examples:1135- - program: 'getpath(["a","b"])'1136- input: 'null'1137- output: ['null']1138- - program: '[getpath(["a","b"], ["a","c"])]'1139- input: '{"a":{"b":0, "c":1}}'1140- output: ['[0, 1]']1141-1142- - title: "`setpath(PATHS; VALUE)`"1143- body: |1144-1145- The builtin function `setpath` sets the `PATHS` in `.` to `VALUE`.1146-1147- examples:1148- - program: 'setpath(["a","b"]; 1)'1149- input: 'null'1150- output: ['{"a": {"b": 1}}']1151- - program: 'setpath(["a","b"]; 1)'1152- input: '{"a":{"b":0}}'1153- output: ['{"a": {"b": 1}}']1154- - program: 'setpath([0,"a"]; 1)'1155- input: 'null'1156- output: ['[{"a":1}]']1157-1158- - title: "`delpaths(PATHS)`"1159- body: |1160-1161- The builtin function `delpaths` deletes the `PATHS` in `.`.1162- `PATHS` must be an array of paths, where each path is an array1163- of strings and numbers.1164-1165- examples:1166- - program: 'delpaths([["a","b"]])'1167- input: '{"a":{"b":1},"x":{"y":2}}'1168- output: ['{"a":{},"x":{"y":2}}']1169-1170- - title: "`to_entries`, `from_entries`, `with_entries(f)`"1171- body: |1172-1173- These functions convert between an object and an array of1174- key-value pairs. If `to_entries` is passed an object, then1175- for each `k: v` entry in the input, the output array1176- includes `{"key": k, "value": v}`.1177-1178- `from_entries` does the opposite conversion, and `with_entries(f)`1179- is a shorthand for `to_entries | map(f) | from_entries`, useful for1180- doing some operation to all keys and values of an object.1181- `from_entries` accepts `"key"`, `"Key"`, `"name"`, `"Name"`,1182- `"value"`, and `"Value"` as keys.1183-1184- examples:1185- - program: 'to_entries'1186- input: '{"a": 1, "b": 2}'1187- output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']1188- - program: 'from_entries'1189- input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'1190- output: ['{"a": 1, "b": 2}']1191- - program: 'with_entries(.key |= "KEY_" + .)'1192- input: '{"a": 1, "b": 2}'1193- output: ['{"KEY_a": 1, "KEY_b": 2}']1194-1195-1196- - title: "`select(boolean_expression)`"1197- body: |1198-1199- The function `select(f)` produces its input unchanged if1200- `f` returns true for that input, and produces no output1201- otherwise.1202-1203- It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`1204- will give you `[2,3]`.1205-1206- examples:1207- - program: 'map(select(. >= 2))'1208- input: '[1,5,3,0,7]'1209- output: ['[5,3,7]']1210- - program: '.[] | select(.id == "second")'1211- input: '[{"id": "first", "val": 1}, {"id": "second", "val": 2}]'1212- output: ['{"id": "second", "val": 2}']1213-1214-1215- - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"1216- body: |1217-1218- These built-ins select only inputs that are arrays, objects,1219- iterables (arrays or objects), booleans, numbers, normal1220- numbers, finite numbers, strings, null, non-null values, and1221- non-iterables, respectively.1222-1223- examples:1224- - program: '.[]|numbers'1225- input: '[[],{},1,"foo",null,true,false]'1226- output: ['1']1227-1228- - title: "`empty`"1229- body: |1230-1231- `empty` returns no results. None at all. Not even `null`.1232-1233- It's useful on occasion. You'll know if you need it :)1234-1235- examples:1236- - program: '1, empty, 2'1237- input: 'null'1238- output: ['1', '2']1239- - program: '[1,2,empty,3]'1240- input: 'null'1241- output: ['[1,2,3]']1242-1243- - title: "`error`, `error(message)`"1244- body: |1245-1246- Produces an error with the input value, or with the message1247- given as the argument. Errors can be caught with try/catch;1248- see below.1249-1250- examples:1251- - program: 'try error catch .'1252- input: '"error message"'1253- output: ['"error message"']1254-1255- - program: 'try error("invalid value: \(.)") catch .'1256- input: '42'1257- output: ['"invalid value: 42"']1258-1259- - title: "`halt`"1260- body: |1261-1262- Stops the jq program with no further outputs. jq will exit1263- with exit status `0`.1264-1265- - title: "`halt_error`, `halt_error(exit_code)`"1266- body: |1267-1268- Stops the jq program with no further outputs. The input will1269- be printed on `stderr` as raw output (i.e., strings will not1270- have double quotes) with no decoration, not even a newline.1271-1272- The given `exit_code` (defaulting to `5`) will be jq's exit1273- status.1274-1275- For example, `"Error: something went wrong\n"|halt_error(1)`.1276-1277- - title: "`$__loc__`"1278- body: |1279-1280- Produces an object with a "file" key and a "line" key, with1281- the filename and line number where `$__loc__` occurs, as1282- values.1283-1284- examples:1285- - program: 'try error("\($__loc__)") catch .'1286- input: 'null'1287- output: ['"{\"file\":\"<top-level>\",\"line\":1}"']1288-1289- - title: "`paths`, `paths(node_filter)`"1290- body: |1291-1292- `paths` outputs the paths to all the elements in its input1293- (except it does not output the empty list, representing .1294- itself).1295-1296- `paths(f)` outputs the paths to any values for which `f` is `true`.1297- That is, `paths(type == "number")` outputs the paths to all numeric1298- values.1299-1300- examples:1301- - program: '[paths]'1302- input: '[1,[[],{"a":2}]]'1303- output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']1304- - program: '[paths(type == "number")]'1305- input: '[1,[[],{"a":2}]]'1306- output: ['[[0],[1,1,"a"]]']1307-1308- - title: "`add`"1309- body: |1310-1311- The filter `add` takes as input an array, and produces as1312- output the elements of the array added together. This might1313- mean summed, concatenated or merged depending on the types1314- of the elements of the input array - the rules are the same1315- as those for the `+` operator (described above).1316-1317- If the input is an empty array, `add` returns `null`.1318-1319- examples:1320- - program: add1321- input: '["a","b","c"]'1322- output: ['"abc"']1323- - program: add1324- input: '[1, 2, 3]'1325- output: ['6']1326- - program: add1327- input: '[]'1328- output: ["null"]1329-1330- - title: "`any`, `any(condition)`, `any(generator; condition)`"1331- body: |1332-1333- The filter `any` takes as input an array of boolean values,1334- and produces `true` as output if any of the elements of1335- the array are `true`.1336-1337- If the input is an empty array, `any` returns `false`.1338-1339- The `any(condition)` form applies the given condition to the1340- elements of the input array.1341-1342- The `any(generator; condition)` form applies the given1343- condition to all the outputs of the given generator.1344-1345- examples:1346- - program: any1347- input: '[true, false]'1348- output: ["true"]1349- - program: any1350- input: '[false, false]'1351- output: ["false"]1352- - program: any1353- input: '[]'1354- output: ["false"]1355-1356- - title: "`all`, `all(condition)`, `all(generator; condition)`"1357- body: |1358-1359- The filter `all` takes as input an array of boolean values,1360- and produces `true` as output if all of the elements of1361- the array are `true`.1362-1363- The `all(condition)` form applies the given condition to the1364- elements of the input array.1365-1366- The `all(generator; condition)` form applies the given1367- condition to all the outputs of the given generator.1368-1369- If the input is an empty array, `all` returns `true`.1370-1371- examples:1372- - program: all1373- input: '[true, false]'1374- output: ["false"]1375- - program: all1376- input: '[true, true]'1377- output: ["true"]1378- - program: all1379- input: '[]'1380- output: ["true"]1381-1382- - title: "`flatten`, `flatten(depth)`"1383- body: |1384-1385- The filter `flatten` takes as input an array of nested arrays,1386- and produces a flat array in which all arrays inside the original1387- array have been recursively replaced by their values. You can pass1388- an argument to it to specify how many levels of nesting to flatten.1389-1390- `flatten(2)` is like `flatten`, but going only up to two1391- levels deep.1392-1393- examples:1394- - program: flatten1395- input: '[1, [2], [[3]]]'1396- output: ["[1, 2, 3]"]1397- - program: flatten(1)1398- input: '[1, [2], [[3]]]'1399- output: ["[1, 2, [3]]"]1400- - program: flatten1401- input: '[[]]'1402- output: ["[]"]1403- - program: flatten1404- input: '[{"foo": "bar"}, [{"foo": "baz"}]]'1405- output: ['[{"foo": "bar"}, {"foo": "baz"}]']1406-1407- - title: "`range(upto)`, `range(from; upto)`, `range(from; upto; by)`"1408- body: |1409-1410- The `range` function produces a range of numbers. `range(4; 10)`1411- produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers1412- are produced as separate outputs. Use `[range(4; 10)]` to get a range as1413- an array.1414-1415- The one argument form generates numbers from 0 to the given1416- number, with an increment of 1.1417-1418- The two argument form generates numbers from `from` to `upto`1419- with an increment of 1.1420-1421- The three argument form generates numbers `from` to `upto`1422- with an increment of `by`.1423-1424- examples:1425- - program: 'range(2; 4)'1426- input: 'null'1427- output: ['2', '3']1428- - program: '[range(2; 4)]'1429- input: 'null'1430- output: ['[2,3]']1431- - program: '[range(4)]'1432- input: 'null'1433- output: ['[0,1,2,3]']1434- - program: '[range(0; 10; 3)]'1435- input: 'null'1436- output: ['[0,3,6,9]']1437- - program: '[range(0; 10; -1)]'1438- input: 'null'1439- output: ['[]']1440- - program: '[range(0; -5; -1)]'1441- input: 'null'1442- output: ['[0,-1,-2,-3,-4]']1443-1444- - title: "`floor`"1445- body: |1446-1447- The `floor` function returns the floor of its numeric input.1448-1449- examples:1450- - program: 'floor'1451- input: '3.14159'1452- output: ['3']1453-1454- - title: "`sqrt`"1455- body: |1456-1457- The `sqrt` function returns the square root of its numeric input.1458-1459- examples:1460- - program: 'sqrt'1461- input: '9'1462- output: ['3']1463-1464- - title: "`tonumber`"1465- body: |1466-1467- The `tonumber` function parses its input as a number. It1468- will convert correctly-formatted strings to their numeric1469- equivalent, leave numbers alone, and give an error on all other input.1470-1471- examples:1472- - program: '.[] | tonumber'1473- input: '[1, "1"]'1474- output: ['1', '1']1475-1476- - title: "`tostring`"1477- body: |1478-1479- The `tostring` function prints its input as a1480- string. Strings are left unchanged, and all other values are1481- JSON-encoded.1482-1483- examples:1484- - program: '.[] | tostring'1485- input: '[1, "1", [1]]'1486- output: ['"1"', '"1"', '"[1]"']1487-1488- - title: "`type`"1489- body: |1490-1491- The `type` function returns the type of its argument as a1492- string, which is one of null, boolean, number, string, array1493- or object.1494-1495- examples:1496- - program: 'map(type)'1497- input: '[0, false, [], {}, null, "hello"]'1498- output: ['["number", "boolean", "array", "object", "null", "string"]']1499-1500- - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1501- body: |1502-1503- Some arithmetic operations can yield infinities and "not a1504- number" (NaN) values. The `isinfinite` builtin returns `true`1505- if its input is infinite. The `isnan` builtin returns `true`1506- if its input is a NaN. The `infinite` builtin returns a1507- positive infinite value. The `nan` builtin returns a NaN.1508- The `isnormal` builtin returns true if its input is a normal1509- number.1510-1511- Note that division by zero raises an error.1512-1513- Currently most arithmetic operations operating on infinities,1514- NaNs, and sub-normals do not raise errors.1515-1516- examples:1517- - program: '.[] | (infinite * .) < 0'1518- input: '[-1, 1]'1519- output: ['true', 'false']1520- - program: 'infinite, nan | type'1521- input: 'null'1522- output: ['"number"', '"number"']1523-1524- - title: "`sort`, `sort_by(path_expression)`"1525- body: |1526-1527- The `sort` functions sorts its input, which must be an1528- array. Values are sorted in the following order:1529-1530- * `null`1531- * `false`1532- * `true`1533- * numbers1534- * strings, in alphabetical order (by unicode codepoint value)1535- * arrays, in lexical order1536- * objects1537-1538- The ordering for objects is a little complex: first they're1539- compared by comparing their sets of keys (as arrays in1540- sorted order), and if their keys are equal then the values1541- are compared key by key.1542-1543- `sort_by` may be used to sort by a particular field of an1544- object, or by applying any jq filter. `sort_by(f)` compares1545- two elements by comparing the result of `f` on each element.1546- When `f` produces multiple values, it firstly compares the1547- first values, and the second values if the first values are1548- equal, and so on.1549-1550- examples:1551- - program: 'sort'1552- input: '[8,3,null,6]'1553- output: ['[null,3,6,8]']1554-1555- - program: 'sort_by(.foo)'1556- input: '[{"foo":4, "bar":10}, {"foo":3, "bar":10}, {"foo":2, "bar":1}]'1557- output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":10}, {"foo":4, "bar":10}]']1558-1559- - program: 'sort_by(.foo, .bar)'1560- input: '[{"foo":4, "bar":10}, {"foo":3, "bar":20}, {"foo":2, "bar":1}, {"foo":3, "bar":10}]'1561- output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":10}, {"foo":3, "bar":20}, {"foo":4, "bar":10}]']1562-1563- - title: "`group_by(path_expression)`"1564- body: |1565-1566- `group_by(.foo)` takes as input an array, groups the1567- elements having the same `.foo` field into separate arrays,1568- and produces all of these arrays as elements of a larger1569- array, sorted by the value of the `.foo` field.1570-1571- Any jq expression, not just a field access, may be used in1572- place of `.foo`. The sorting order is the same as described1573- in the `sort` function above.1574-1575- examples:1576- - program: 'group_by(.foo)'1577- input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'1578- output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']1579-1580- - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1581- body: |1582-1583- Find the minimum or maximum element of the input array.1584-1585- The `min_by(path_exp)` and `max_by(path_exp)` functions allow1586- you to specify a particular field or property to examine, e.g.1587- `min_by(.foo)` finds the object with the smallest `foo` field.1588-1589- examples:1590- - program: 'min'1591- input: '[5,4,2,7]'1592- output: ['2']1593- - program: 'max_by(.foo)'1594- input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'1595- output: ['{"foo":2, "bar":3}']1596-1597- - title: "`unique`, `unique_by(path_exp)`"1598- body: |1599-1600- The `unique` function takes as input an array and produces1601- an array of the same elements, in sorted order, with1602- duplicates removed.1603-1604- The `unique_by(path_exp)` function will keep only one element1605- for each value obtained by applying the argument. Think of it1606- as making an array by taking one element out of every group1607- produced by `group`.1608-1609- examples:1610- - program: 'unique'1611- input: '[1,2,5,3,5,3,1,3]'1612- output: ['[1,2,3,5]']1613- - program: 'unique_by(.foo)'1614- input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'1615- output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']1616- - program: 'unique_by(length)'1617- input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'1618- output: ['["bacon", "chunky", "asparagus"]']1619-1620- - title: "`reverse`"1621- body: |1622-1623- This function reverses an array.1624-1625- examples:1626- - program: 'reverse'1627- input: '[1,2,3,4]'1628- output: ['[4,3,2,1]']1629-1630- - title: "`contains(element)`"1631- body: |1632-1633- The filter `contains(b)` will produce true if b is1634- completely contained within the input. A string B is1635- contained in a string A if B is a substring of A. An array B1636- is contained in an array A if all elements in B are1637- contained in any element in A. An object B is contained in1638- object A if all of the values in B are contained in the1639- value in A with the same key. All other types are assumed to1640- be contained in each other if they are equal.1641-1642- examples:1643- - program: 'contains("bar")'1644- input: '"foobar"'1645- output: ['true']1646- - program: 'contains(["baz", "bar"])'1647- input: '["foobar", "foobaz", "blarp"]'1648- output: ['true']1649- - program: 'contains(["bazzzzz", "bar"])'1650- input: '["foobar", "foobaz", "blarp"]'1651- output: ['false']1652- - program: 'contains({foo: 12, bar: [{barp: 12}]})'1653- input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1654- output: ['true']1655- - program: 'contains({foo: 12, bar: [{barp: 15}]})'1656- input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1657- output: ['false']1658-1659- - title: "`indices(s)`"1660- body: |1661-1662- Outputs an array containing the indices in `.` where `s`1663- occurs. The input may be an array, in which case if `s` is an1664- array then the indices output will be those where all elements1665- in `.` match those of `s`.1666-1667- examples:1668- - program: 'indices(", ")'1669- input: '"a,b, cd, efg, hijk"'1670- output: ['[3,7,12]']1671- - program: 'indices(1)'1672- input: '[0,1,2,1,3,1,4]'1673- output: ['[1,3,5]']1674- - program: 'indices([1,2])'1675- input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1676- output: ['[1,8]']1677-1678- - title: "`index(s)`, `rindex(s)`"1679- body: |1680-1681- Outputs the index of the first (`index`) or last (`rindex`)1682- occurrence of `s` in the input.1683-1684- examples:1685- - program: 'index(", ")'1686- input: '"a,b, cd, efg, hijk"'1687- output: ['3']1688- - program: 'index(1)'1689- input: '[0,1,2,1,3,1,4]'1690- output: ['1']1691- - program: 'index([1,2])'1692- input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1693- output: ['1']1694- - program: 'rindex(", ")'1695- input: '"a,b, cd, efg, hijk"'1696- output: ['12']1697- - program: 'rindex(1)'1698- input: '[0,1,2,1,3,1,4]'1699- output: ['5']1700- - program: 'rindex([1,2])'1701- input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1702- output: ['8']1703-1704- - title: "`inside`"1705- body: |1706-1707- The filter `inside(b)` will produce true if the input is1708- completely contained within b. It is, essentially, an1709- inversed version of `contains`.1710-1711- examples:1712- - program: 'inside("foobar")'1713- input: '"bar"'1714- output: ['true']1715- - program: 'inside(["foobar", "foobaz", "blarp"])'1716- input: '["baz", "bar"]'1717- output: ['true']1718- - program: 'inside(["foobar", "foobaz", "blarp"])'1719- input: '["bazzzzz", "bar"]'1720- output: ['false']1721- - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1722- input: '{"foo": 12, "bar": [{"barp": 12}]}'1723- output: ['true']1724- - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1725- input: '{"foo": 12, "bar": [{"barp": 15}]}'1726- output: ['false']1727-1728- - title: "`startswith(str)`"1729- body: |1730-1731- Outputs `true` if . starts with the given string argument.1732-1733- examples:1734- - program: '[.[]|startswith("foo")]'1735- input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1736- output: ['[false, true, false, true, false]']1737-1738- - title: "`endswith(str)`"1739- body: |1740-1741- Outputs `true` if . ends with the given string argument.1742-1743- examples:1744- - program: '[.[]|endswith("foo")]'1745- input: '["foobar", "barfoo"]'1746- output: ['[false, true]']1747-1748- - title: "`combinations`, `combinations(n)`"1749- body: |1750-1751- Outputs all combinations of the elements of the arrays in the1752- input array. If given an argument `n`, it outputs all combinations1753- of `n` repetitions of the input array.1754-1755- examples:1756- - program: 'combinations'1757- input: '[[1,2], [3, 4]]'1758- output: ['[1, 3]', '[1, 4]', '[2, 3]', '[2, 4]']1759- - program: 'combinations(2)'1760- input: '[0, 1]'1761- output: ['[0, 0]', '[0, 1]', '[1, 0]', '[1, 1]']1762-1763- - title: "`ltrimstr(str)`"1764- body: |1765-1766- Outputs its input with the given prefix string removed, if it1767- starts with it.1768-1769- examples:1770- - program: '[.[]|ltrimstr("foo")]'1771- input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1772- output: ['["fo","","barfoo","bar","afoo"]']1773-1774- - title: "`rtrimstr(str)`"1775- body: |1776-1777- Outputs its input with the given suffix string removed, if it1778- ends with it.1779-1780- examples:1781- - program: '[.[]|rtrimstr("foo")]'1782- input: '["fo", "foo", "barfoo", "foobar", "foob"]'1783- output: ['["fo","","bar","foobar","foob"]']1784-1785- - title: "`trim`, `ltrim`, `rtrim`"1786- body: |1787-1788- `trim` trims both leading and trailing whitespace.1789-1790- `ltrim` trims only leading (left side) whitespace.1791-1792- `rtrim` trims only trailing (right side) whitespace.1793-1794- Whitespace characters are the usual `" "`, `"\n"` `"\t"`, `"\r"`1795- and also all characters in the Unicode character database with the1796- whitespace property. Note that what considers whitespace might1797- change in the future.1798-1799- examples:1800- - program: 'trim, ltrim, rtrim'1801- input: '" abc "'1802- output: ['"abc"', '"abc "', '" abc"']1803-1804- - title: "`explode`"1805- body: |1806-1807- Converts an input string into an array of the string's1808- codepoint numbers.1809-1810- examples:1811- - program: 'explode'1812- input: '"foobar"'1813- output: ['[102,111,111,98,97,114]']1814-1815- - title: "`implode`"1816- body: |1817-1818- The inverse of explode.1819-1820- examples:1821- - program: 'implode'1822- input: '[65, 66, 67]'1823- output: ['"ABC"']1824-1825- - title: "`split(str)`"1826- body: |1827-1828- Splits an input string on the separator argument.1829-1830- `split` can also split on regex matches when called with1831- two arguments (see the regular expressions section below).1832-1833- examples:1834- - program: 'split(", ")'1835- input: '"a, b,c,d, e, "'1836- output: ['["a","b,c,d","e",""]']1837-1838- - title: "`join(str)`"1839- body: |1840-1841- Joins the array of elements given as input, using the1842- argument as separator. It is the inverse of `split`: that is,1843- running `split("foo") | join("foo")` over any input string1844- returns said input string.1845-1846- Numbers and booleans in the input are converted to strings.1847- Null values are treated as empty strings. Arrays and objects1848- in the input are not supported.1849-1850- examples:1851- - program: 'join(", ")'1852- input: '["a","b,c,d","e"]'1853- output: ['"a, b,c,d, e"']1854- - program: 'join(" ")'1855- input: '["a",1,2.3,true,null,false]'1856- output: ['"a 1 2.3 true false"']1857-1858- - title: "`ascii_downcase`, `ascii_upcase`"1859- body: |1860-1861- Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1862- converted to the specified case.1863-1864- examples:1865- - program: 'ascii_upcase'1866- input: '"useful but not for é"'1867- output: ['"USEFUL BUT NOT FOR é"']1868-1869- - title: "`while(cond; update)`"1870- body: |1871-1872- The `while(cond; update)` function allows you to repeatedly1873- apply an update to `.` until `cond` is false.1874-1875- Note that `while(cond; update)` is internally defined as a1876- recursive jq function. Recursive calls within `while` will1877- not consume additional memory if `update` produces at most one1878- output for each input. See advanced topics below.1879-1880- examples:1881- - program: '[while(.<100; .*2)]'1882- input: '1'1883- output: ['[1,2,4,8,16,32,64]']1884-1885- - title: "`repeat(exp)`"1886- body: |1887-1888- The `repeat(exp)` function allows you to repeatedly1889- apply expression `exp` to `.` until an error is raised.1890-1891- Note that `repeat(exp)` is internally defined as a1892- recursive jq function. Recursive calls within `repeat` will1893- not consume additional memory if `exp` produces at most one1894- output for each input. See advanced topics below.1895-1896- examples:1897- - program: '[repeat(.*2, error)?]'1898- input: '1'1899- output: ['[2]']1900-1901- - title: "`until(cond; next)`"1902- body: |1903-1904- The `until(cond; next)` function allows you to repeatedly1905- apply the expression `next`, initially to `.` then to its own1906- output, until `cond` is true. For example, this can be used1907- to implement a factorial function (see below).1908-1909- Note that `until(cond; next)` is internally defined as a1910- recursive jq function. Recursive calls within `until()` will1911- not consume additional memory if `next` produces at most one1912- output for each input. See advanced topics below.1913-1914- examples:1915- - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1916- input: '4'1917- output: ['24']1918-1919-1920- - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`"1921- body: |1922-1923- The `recurse(f)` function allows you to search through a1924- recursive structure, and extract interesting data from all1925- levels. Suppose your input represents a filesystem:1926-1927- {"name": "/", "children": [1928- {"name": "/bin", "children": [1929- {"name": "/bin/ls", "children": []},1930- {"name": "/bin/sh", "children": []}]},1931- {"name": "/home", "children": [1932- {"name": "/home/stephen", "children": [1933- {"name": "/home/stephen/jq", "children": []}]}]}]}1934-1935- Now suppose you want to extract all of the filenames1936- present. You need to retrieve `.name`, `.children[].name`,1937- `.children[].children[].name`, and so on. You can do this1938- with:1939-1940- recurse(.children[]) | .name1941-1942- When called without an argument, `recurse` is equivalent to1943- `recurse(.[]?)`.1944-1945- `recurse(f)` is identical to `recurse(f; true)` and can be1946- used without concerns about recursion depth.1947-1948- `recurse(f; condition)` is a generator which begins by1949- emitting . and then emits in turn .|f, .|f|f, .|f|f|f, ... so long1950- as the computed value satisfies the condition. For example,1951- to generate all the integers, at least in principle, one1952- could write `recurse(.+1; true)`.1953-1954- The recursive calls in `recurse` will not consume additional1955- memory whenever `f` produces at most a single output for each1956- input.1957-1958- examples:1959- - program: 'recurse(.foo[])'1960- input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'1961- output:1962- - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'1963- - '{"foo":[]}'1964- - '{"foo":[{"foo":[]}]}'1965- - '{"foo":[]}'1966-1967- - program: 'recurse'1968- input: '{"a":0,"b":[1]}'1969- output:1970- - '{"a":0,"b":[1]}'1971- - '0'1972- - '[1]'1973- - '1'1974-1975- - program: 'recurse(. * .; . < 20)'1976- input: '2'1977- output: ['2', '4', '16']1978-1979- - title: "`walk(f)`"1980- body: |1981-1982- The `walk(f)` function applies f recursively to every1983- component of the input entity. When an array is1984- encountered, f is first applied to its elements and then to1985- the array itself; when an object is encountered, f is first1986- applied to all the values and then to the object. In1987- practice, f will usually test the type of its input, as1988- illustrated in the following examples. The first example1989- highlights the usefulness of processing the elements of an1990- array of arrays before processing the array itself. The second1991- example shows how all the keys of all the objects within the1992- input can be considered for alteration.1993-1994- examples:1995- - program: 'walk(if type == "array" then sort else . end)'1996- input: '[[4, 1, 7], [8, 5, 2], [3, 6, 9]]'1997- output:1998- - '[[1,4,7],[2,5,8],[3,6,9]]'1999-2000- - program: 'walk( if type == "object" then with_entries( .key |= sub( "^_+"; "") ) else . end )'2001- input: '[ { "_a": { "__b": 2 } } ]'2002- output:2003- - '[{"a":{"b":2}}]'2004-2005- - title: "`have_literal_numbers`"2006- body: |2007-2008- This builtin returns true if jq's build configuration2009- includes support for preservation of input number literals.2010-2011- - title: "`have_decnum`"2012- body: |2013-2014- This builtin returns true if jq was built with "decnum",2015- which is the current literal number preserving numeric2016- backend implementation for jq.2017-2018- - title: "`$JQ_BUILD_CONFIGURATION`"2019- body: |2020-2021- This builtin binding shows the jq executable's build2022- configuration. Its value has no particular format, but2023- it can be expected to be at least the `./configure`2024- command-line arguments, and may be enriched in the2025- future to include the version strings for the build2026- tooling used.2027-2028- Note that this can be overriden in the command-line2029- with `--arg` and related options.2030-2031- - title: "`$ENV`, `env`"2032- body: |2033-2034- `$ENV` is an object representing the environment variables as2035- set when the jq program started.2036-2037- `env` outputs an object representing jq's current environment.2038-2039- At the moment there is no builtin for setting environment2040- variables.2041-2042- examples:2043- - program: '$ENV.PAGER'2044- input: 'null'2045- output: ['"less"']2046-2047- - program: 'env.PAGER'2048- input: 'null'2049- output: ['"less"']2050-2051- - title: "`transpose`"2052- body: |2053-2054- Transpose a possibly jagged matrix (an array of arrays).2055- Rows are padded with nulls so the result is always rectangular.2056-2057- examples:2058- - program: 'transpose'2059- input: '[[1], [2,3]]'2060- output: ['[[1,2],[null,3]]']2061-2062- - title: "`bsearch(x)`"2063- body: |2064-2065- `bsearch(x)` conducts a binary search for x in the input2066- array. If the input is sorted and contains x, then2067- `bsearch(x)` will return its index in the array; otherwise, if2068- the array is sorted, it will return (-1 - ix) where ix is an2069- insertion point such that the array would still be sorted2070- after the insertion of x at ix. If the array is not sorted,2071- `bsearch(x)` will return an integer that is probably of no2072- interest.2073-2074- examples:2075- - program: 'bsearch(0)'2076- input: '[0,1]'2077- output: ['0']2078- - program: 'bsearch(0)'2079- input: '[1,2,3]'2080- output: ['-1']2081- - program: 'bsearch(4) as $ix | if $ix < 0 then .[-(1+$ix)] = 4 else . end'2082- input: '[1,2,3]'2083- output: ['[1,2,3,4]']2084-2085- - title: "String interpolation: `\\(exp)`"2086- body: |2087-2088- Inside a string, you can put an expression inside parens2089- after a backslash. Whatever the expression returns will be2090- interpolated into the string.2091-2092- examples:2093- - program: '"The input was \(.), which is one less than \(.+1)"'2094- input: '42'2095- output: ['"The input was 42, which is one less than 43"']2096-2097- - title: "Convert to/from JSON"2098- body: |2099-2100- The `tojson` and `fromjson` builtins dump values as JSON texts2101- or parse JSON texts into values, respectively. The `tojson`2102- builtin differs from `tostring` in that `tostring` returns strings2103- unmodified, while `tojson` encodes strings as JSON strings.2104-2105- examples:2106- - program: '[.[]|tostring]'2107- input: '[1, "foo", ["foo"]]'2108- output: ['["1","foo","[\"foo\"]"]']2109- - program: '[.[]|tojson]'2110- input: '[1, "foo", ["foo"]]'2111- output: ['["1","\"foo\"","[\"foo\"]"]']2112- - program: '[.[]|tojson|fromjson]'2113- input: '[1, "foo", ["foo"]]'2114- output: ['[1,"foo",["foo"]]']2115-2116- - title: "Format strings and escaping"2117- body: |2118-2119- The `@foo` syntax is used to format and escape strings,2120- which is useful for building URLs, documents in a language2121- like HTML or XML, and so forth. `@foo` can be used as a2122- filter on its own, the possible escapings are:2123-2124- * `@text`:2125-2126- Calls `tostring`, see that function for details.2127-2128- * `@json`:2129-2130- Serializes the input as JSON.2131-2132- * `@html`:2133-2134- Applies HTML/XML escaping, by mapping the characters2135- `<>&'"` to their entity equivalents `<`, `>`,2136- `&`, `'`, `"`.2137-2138- * `@uri`:2139-2140- Applies percent-encoding, by mapping all reserved URI2141- characters to a `%XX` sequence.2142-2143- * `@csv`:2144-2145- The input must be an array, and it is rendered as CSV2146- with double quotes for strings, and quotes escaped by2147- repetition.2148-2149- * `@tsv`:2150-2151- The input must be an array, and it is rendered as TSV2152- (tab-separated values). Each input array will be printed as2153- a single line. Fields are separated by a single2154- tab (ascii `0x09`). Input characters line-feed (ascii `0x0a`),2155- carriage-return (ascii `0x0d`), tab (ascii `0x09`) and2156- backslash (ascii `0x5c`) will be output as escape sequences2157- `\n`, `\r`, `\t`, `\\` respectively.2158-2159- * `@sh`:2160-2161- The input is escaped suitable for use in a command-line2162- for a POSIX shell. If the input is an array, the output2163- will be a series of space-separated strings.2164-2165- * `@base64`:2166-2167- The input is converted to base64 as specified by RFC 4648.2168-2169- * `@base64d`:2170-2171- The inverse of `@base64`, input is decoded as specified by RFC 4648.2172- Note\: If the decoded string is not UTF-8, the results are undefined.2173-2174- This syntax can be combined with string interpolation in a2175- useful way. You can follow a `@foo` token with a string2176- literal. The contents of the string literal will *not* be2177- escaped. However, all interpolations made inside that string2178- literal will be escaped. For instance,2179-2180- @uri "https://www.google.com/search?q=\(.search)"2181-2182- will produce the following output for the input2183- `{"search":"what is jq?"}`:2184-2185- "https://www.google.com/search?q=what%20is%20jq%3F"2186-2187- Note that the slashes, question mark, etc. in the URL are2188- not escaped, as they were part of the string literal.2189-2190- examples:2191- - program: '@html'2192- input: '"This works if x < y"'2193- output: ['"This works if x < y"']2194-2195- - program: '@sh "echo \(.)"'2196- input: "\"O'Hara's Ale\""2197- output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]2198-2199- - program: '@base64'2200- input: '"This is a message"'2201- output: ['"VGhpcyBpcyBhIG1lc3NhZ2U="']2202-2203- - program: '@base64d'2204- input: '"VGhpcyBpcyBhIG1lc3NhZ2U="'2205- output: ['"This is a message"']2206-2207- - title: "Dates"2208- body: |2209-2210- jq provides some basic date handling functionality, with some2211- high-level and low-level builtins. In all cases these2212- builtins deal exclusively with time in UTC.2213-2214- The `fromdateiso8601` builtin parses datetimes in the ISO 86012215- format to a number of seconds since the Unix epoch2216- (1970-01-01T00:00:00Z). The `todateiso8601` builtin does the2217- inverse.2218-2219- The `fromdate` builtin parses datetime strings. Currently2220- `fromdate` only supports ISO 8601 datetime strings, but in the2221- future it will attempt to parse datetime strings in more2222- formats.2223-2224- The `todate` builtin is an alias for `todateiso8601`.2225-2226- The `now` builtin outputs the current time, in seconds since2227- the Unix epoch.2228-2229- Low-level jq interfaces to the C-library time functions are2230- also provided: `strptime`, `strftime`, `strflocaltime`,2231- `mktime`, `gmtime`, and `localtime`. Refer to your host2232- operating system's documentation for the format strings used2233- by `strptime` and `strftime`. Note: these are not necessarily2234- stable interfaces in jq, particularly as to their localization2235- functionality.2236-2237- The `gmtime` builtin consumes a number of seconds since the2238- Unix epoch and outputs a "broken down time" representation of2239- Greenwich Mean Time as an array of numbers representing2240- (in this order): the year, the month (zero-based), the day of2241- the month (one-based), the hour of the day, the minute of the2242- hour, the second of the minute, the day of the week, and the2243- day of the year -- all one-based unless otherwise stated. The2244- day of the week number may be wrong on some systems for dates2245- before March 1st 1900, or after December 31 2099.2246-2247- The `localtime` builtin works like the `gmtime` builtin, but2248- using the local timezone setting.2249-2250- The `mktime` builtin consumes "broken down time"2251- representations of time output by `gmtime` and `strptime`.2252-2253- The `strptime(fmt)` builtin parses input strings matching the2254- `fmt` argument. The output is in the "broken down time"2255- representation consumed by `gmtime` and output by `mktime`.2256-2257- The `strftime(fmt)` builtin formats a time (GMT) with the2258- given format. The `strflocaltime` does the same, but using2259- the local timezone setting.2260-2261- The format strings for `strptime` and `strftime` are described2262- in typical C library documentation. The format string for ISO2263- 8601 datetime is `"%Y-%m-%dT%H:%M:%SZ"`.2264-2265- jq may not support some or all of this date functionality on2266- some systems. In particular, the `%u` and `%j` specifiers for2267- `strptime(fmt)` are not supported on macOS.2268-2269- examples:2270- - program: 'fromdate'2271- input: '"2015-03-05T23:51:47Z"'2272- output: ['1425599507']2273-2274- - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")'2275- input: '"2015-03-05T23:51:47Z"'2276- output: ['[2015,2,5,23,51,47,4,63]']2277-2278- - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'2279- input: '"2015-03-05T23:51:47Z"'2280- output: ['1425599507']2281-2282- - title: "SQL-Style Operators"2283- body: |2284-2285- jq provides a few SQL-style operators.2286-2287- * INDEX(stream; index_expression):2288-2289- This builtin produces an object whose keys are computed by2290- the given index expression applied to each value from the2291- given stream.2292-2293- * JOIN($idx; stream; idx_expr; join_expr):2294-2295- This builtin joins the values from the given stream to the2296- given index. The index's keys are computed by applying the2297- given index expression to each value from the given stream.2298- An array of the value in the stream and the corresponding2299- value from the index is fed to the given join expression to2300- produce each result.2301-2302- * JOIN($idx; stream; idx_expr):2303-2304- Same as `JOIN($idx; stream; idx_expr; .)`.2305-2306- * JOIN($idx; idx_expr):2307-2308- This builtin joins the input `.` to the given index, applying2309- the given index expression to `.` to compute the index key.2310- The join operation is as described above.2311-2312- * IN(s):2313-2314- This builtin outputs `true` if `.` appears in the given2315- stream, otherwise it outputs `false`.2316-2317- * IN(source; s):2318-2319- This builtin outputs `true` if any value in the source stream2320- appears in the second stream, otherwise it outputs `false`.2321-2322- - title: "`builtins`"2323- body: |2324-2325- Returns a list of all builtin functions in the format `name/arity`.2326- Since functions with the same name but different arities are considered2327- separate functions, `all/0`, `all/1`, and `all/2` would all be present2328- in the list.2329-2330- - title: Conditionals and Comparisons2331- entries:2332- - title: "`==`, `!=`"2333- body: |2334-2335- The expression 'a == b' will produce 'true' if the results of evaluating2336- a and b are equal (that is, if they represent equivalent JSON values) and2337- 'false' otherwise. In particular, strings are never considered equal2338- to numbers. In checking for the equality of JSON objects, the ordering of keys2339- is irrelevant. If you're coming from JavaScript, please note that jq's `==` is like2340- JavaScript's `===`, the "strict equality" operator.2341-2342- != is "not equal", and 'a != b' returns the opposite value of 'a == b'2343-2344- examples:2345- - program: '. == false'2346- input: 'null'2347- output: ['false']2348-2349- - program: '. == {"b": {"d": (4 + 1e-20), "c": 3}, "a":1}'2350- input: '{"a":1, "b": {"c": 3, "d": 4}}'2351- output: ['true']2352-2353- - program: '.[] == 1'2354- input: '[1, 1.0, "1", "banana"]'2355- output: ['true', 'true', 'false', 'false']2356-2357- - title: if-then-else-end2358- body: |2359-2360- `if A then B else C end` will act the same as `B` if `A`2361- produces a value other than false or null, but act the same2362- as `C` otherwise.2363-2364- `if A then B end` is the same as `if A then B else . end`.2365- That is, the `else` branch is optional, and if absent is the2366- same as `.`. This also applies to `elif` with absent ending `else` branch.2367-2368- Checking for false or null is a simpler notion of2369- "truthiness" than is found in JavaScript or Python, but it2370- means that you'll sometimes have to be more explicit about2371- the condition you want. You can't test whether, e.g. a2372- string is empty using `if .name then A else B end`; you'll2373- need something like `if .name == "" then A else B end` instead.2374-2375- If the condition `A` produces multiple results, then `B` is evaluated2376- once for each result that is not false or null, and `C` is evaluated2377- once for each false or null.2378-2379- More cases can be added to an if using `elif A then B` syntax.2380-2381- examples:2382- - program: |-2383- if . == 0 then2384- "zero"2385- elif . == 1 then2386- "one"2387- else2388- "many"2389- end2390- input: '2'2391- output: ['"many"']2392-2393- - title: "`>`, `>=`, `<=`, `<`"2394- body: |2395-2396- The comparison operators `>`, `>=`, `<=`, `<` return whether2397- their left argument is greater than, greater than or equal2398- to, less than or equal to or less than their right argument2399- (respectively).2400-2401- The ordering is the same as that described for `sort`, above.2402-2403- examples:2404- - program: '. < 5'2405- input: '2'2406- output: ['true']2407-2408- - title: "`and`, `or`, `not`"2409- body: |2410-2411- jq supports the normal Boolean operators `and`, `or`, `not`.2412- They have the same standard of truth as if expressions -2413- `false` and `null` are considered "false values", and2414- anything else is a "true value".2415-2416- If an operand of one of these operators produces multiple2417- results, the operator itself will produce a result for each input.2418-2419- `not` is in fact a builtin function rather than an operator,2420- so it is called as a filter to which things can be piped2421- rather than with special syntax, as in `.foo and .bar |2422- not`.2423-2424- These three only produce the values `true` and `false`, and2425- so are only useful for genuine Boolean operations, rather2426- than the common Perl/Python/Ruby idiom of2427- "value_that_may_be_null or default". If you want to use this2428- form of "or", picking between two values rather than2429- evaluating a condition, see the `//` operator below.2430-2431- examples:2432- - program: '42 and "a string"'2433- input: 'null'2434- output: ['true']2435- - program: '(true, false) or false'2436- input: 'null'2437- output: ['true', 'false']2438- - program: '(true, true) and (true, false)'2439- input: 'null'2440- output: ['true', 'false', 'true', 'false']2441- - program: '[true, false | not]'2442- input: 'null'2443- output: ['[false, true]']2444-2445- - title: "Alternative operator: `//`"2446- body: |2447-2448- The `//` operator produces all the values of its left-hand2449- side that are neither `false` nor `null`. If the2450- left-hand side produces no values other than `false` or2451- `null`, then `//` produces all the values of its right-hand2452- side.2453-2454- A filter of the form `a // b` produces all the results of2455- `a` that are not `false` or `null`. If `a` produces no2456- results, or no results other than `false` or `null`, then `a2457- // b` produces the results of `b`.2458-2459- This is useful for providing defaults: `.foo // 1` will2460- evaluate to `1` if there's no `.foo` element in the2461- input. It's similar to how `or` is sometimes used in Python2462- (jq's `or` operator is reserved for strictly Boolean2463- operations).2464-2465- Note: `some_generator // defaults_here` is not the same2466- as `some_generator | . // defaults_here`. The latter will2467- produce default values for all non-`false`, non-`null`2468- values of the left-hand side, while the former will not.2469- Precedence rules can make this confusing. For example, in2470- `false, 1 // 2` the left-hand side of `//` is `1`, not2471- `false, 1` -- `false, 1 // 2` parses the same way as `false,2472- (1 // 2)`. In `(false, null, 1) | . // 42` the left-hand2473- side of `//` is `.`, which always produces just one value,2474- while in `(false, null, 1) // 42` the left-hand side is a2475- generator of three values, and since it produces a2476- value other `false` and `null`, the default `42` is not2477- produced.2478-2479- examples:2480- - program: 'empty // 42'2481- input: 'null'2482- output: ['42']2483- - program: '.foo // 42'2484- input: '{"foo": 19}'2485- output: ['19']2486- - program: '.foo // 42'2487- input: '{}'2488- output: ['42']2489- - program: '(false, null, 1) // 42'2490- input: 'null'2491- output: ['1']2492- - program: '(false, null, 1) | . // 42'2493- input: 'null'2494- output: ['42', '42', '1']2495-2496- - title: try-catch2497- body: |2498-2499- Errors can be caught by using `try EXP catch EXP`. The first2500- expression is executed, and if it fails then the second is2501- executed with the error message. The output of the handler,2502- if any, is output as if it had been the output of the2503- expression to try.2504-2505- The `try EXP` form uses `empty` as the exception handler.2506-2507- examples:2508- - program: 'try .a catch ". is not an object"'2509- input: 'true'2510- output: ['". is not an object"']2511- - program: '[.[]|try .a]'2512- input: '[{}, true, {"a":1}]'2513- output: ['[null, 1]']2514- - program: 'try error("some exception") catch .'2515- input: 'true'2516- output: ['"some exception"']2517-2518- - title: Breaking out of control structures2519- body: |2520-2521- A convenient use of try/catch is to break out of control2522- structures like `reduce`, `foreach`, `while`, and so on.2523-2524- For example:2525-2526- # Repeat an expression until it raises "break" as an2527- # error, then stop repeating without re-raising the error.2528- # But if the error caught is not "break" then re-raise it.2529- try repeat(exp) catch if .=="break" then empty else error2530-2531- jq has a syntax for named lexical labels to "break" or "go (back) to":2532-2533- label $out | ... break $out ...2534-2535- The `break $label_name` expression will cause the program to2536- act as though the nearest (to the left) `label $label_name`2537- produced `empty`.2538-2539- The relationship between the `break` and corresponding `label`2540- is lexical: the label has to be "visible" from the break.2541-2542- To break out of a `reduce`, for example:2543-2544- label $out | reduce .[] as $item (null; if .==false then break $out else ... end)2545-2546- The following jq program produces a syntax error:2547-2548- break $out2549-2550- because no label `$out` is visible.2551-2552- - title: "Error Suppression / Optional Operator: `?`"2553- body: |2554-2555- The `?` operator, used as `EXP?`, is shorthand for `try EXP`.2556-2557- examples:2558- - program: '[.[] | .a?]'2559- input: '[{}, true, {"a":1}]'2560- output: ['[null, 1]']2561- - program: '[.[] | tonumber?]'2562- input: '["1", "invalid", "3", 4]'2563- output: ['[1, 3, 4]']2564-2565- - title: Regular expressions2566- body: |2567-2568- jq uses the2569- [Oniguruma regular expression library](https://github.com/kkos/oniguruma/blob/master/doc/RE),2570- as do PHP, TextMate, Sublime Text, etc, so the2571- description here will focus on jq specifics.2572-2573- Oniguruma supports several flavors of regular expression, so it is important to know2574- that jq uses the ["Perl NG" (Perl with named groups)](https://github.com/kkos/oniguruma/blob/master/doc/SYNTAX.md) flavor.2575-2576- The jq regex filters are defined so that they can be used using2577- one of these patterns:2578-2579- STRING | FILTER(REGEX)2580- STRING | FILTER(REGEX; FLAGS)2581- STRING | FILTER([REGEX])2582- STRING | FILTER([REGEX, FLAGS])2583-2584- where:2585-2586- * STRING, REGEX, and FLAGS are jq strings and subject to jq string interpolation;2587- * REGEX, after string interpolation, should be a valid regular expression;2588- * FILTER is one of `test`, `match`, or `capture`, as described below.2589-2590- Since REGEX must evaluate to a JSON string, some characters that are needed2591- to form a regular expression must be escaped. For example, the regular expression2592- `\s` signifying a whitespace character would be written as `"\\s"`.2593-2594- FLAGS is a string consisting of one of more of the supported flags:2595-2596- * `g` - Global search (find all matches, not just the first)2597- * `i` - Case insensitive search2598- * `m` - Multi line mode (`.` will match newlines)2599- * `n` - Ignore empty matches2600- * `p` - Both s and m modes are enabled2601- * `s` - Single line mode (`^` -> `\A`, `$` -> `\Z`)2602- * `l` - Find longest possible matches2603- * `x` - Extended regex format (ignore whitespace and comments)2604-2605- To match a whitespace with the `x` flag, use `\s`, e.g.2606-2607- jq -n '"a b" | test("a\\sb"; "x")'2608-2609- Note that certain flags may also be specified within REGEX, e.g.2610-2611- jq -n '("test", "TEst", "teST", "TEST") | test("(?i)te(?-i)st")'2612-2613- evaluates to: `true`, `true`, `false`, `false`.2614-2615- entries:2616- - title: "`test(val)`, `test(regex; flags)`"2617- body: |2618-2619- Like `match`, but does not return match objects, only `true` or `false`2620- for whether or not the regex matches the input.2621-2622- examples:2623- - program: 'test("foo")'2624- input: '"foo"'2625- output: ['true']2626- - program: '.[] | test("a b c # spaces are ignored"; "ix")'2627- input: '["xabcd", "ABC"]'2628- output: ['true', 'true']2629-2630- - title: "`match(val)`, `match(regex; flags)`"2631- body: |2632-2633- **match** outputs an object for each match it finds. Matches have2634- the following fields:2635-2636- * `offset` - offset in UTF-8 codepoints from the beginning of the input2637- * `length` - length in UTF-8 codepoints of the match2638- * `string` - the string that it matched2639- * `captures` - an array of objects representing capturing groups.2640-2641- Capturing group objects have the following fields:2642-2643- * `offset` - offset in UTF-8 codepoints from the beginning of the input2644- * `length` - length in UTF-8 codepoints of this capturing group2645- * `string` - the string that was captured2646- * `name` - the name of the capturing group (or `null` if it was unnamed)2647-2648- Capturing groups that did not match anything return an offset of -12649-2650- examples:2651- - program: 'match("(abc)+"; "g")'2652- input: '"abc abc"'2653- output:2654- - '{"offset": 0, "length": 3, "string": "abc", "captures": [{"offset": 0, "length": 3, "string": "abc", "name": null}]}'2655- - '{"offset": 4, "length": 3, "string": "abc", "captures": [{"offset": 4, "length": 3, "string": "abc", "name": null}]}'2656- - program: 'match("foo")'2657- input: '"foo bar foo"'2658- output: ['{"offset": 0, "length": 3, "string": "foo", "captures": []}']2659- - program: 'match(["foo", "ig"])'2660- input: '"foo bar FOO"'2661- output:2662- - '{"offset": 0, "length": 3, "string": "foo", "captures": []}'2663- - '{"offset": 8, "length": 3, "string": "FOO", "captures": []}'2664- - program: 'match("foo (?<bar123>bar)? foo"; "ig")'2665- input: '"foo bar foo foo foo"'2666- output:2667- - '{"offset": 0, "length": 11, "string": "foo bar foo", "captures": [{"offset": 4, "length": 3, "string": "bar", "name": "bar123"}]}'2668- - '{"offset": 12, "length": 8, "string": "foo foo", "captures": [{"offset": -1, "length": 0, "string": null, "name": "bar123"}]}'2669-2670- - program: '[ match("."; "g")] | length'2671- input: '"abc"'2672- output: ['3']2673-2674-2675- - title: "`capture(val)`, `capture(regex; flags)`"2676- body: |2677-2678- Collects the named captures in a JSON object, with the name2679- of each capture as the key, and the matched string as the2680- corresponding value.2681-2682- examples:2683- - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2684- input: '"xyzzy-14"'2685- output: ['{ "a": "xyzzy", "n": "14" }']2686-2687- - title: "`scan(regex)`, `scan(regex; flags)`"2688- body: |2689-2690- Emit a stream of the non-overlapping substrings of the input2691- that match the regex in accordance with the flags, if any2692- have been specified. If there is no match, the stream is empty.2693- To capture all the matches for each input string, use the idiom2694- `[ expr ]`, e.g. `[ scan(regex) ]`.2695-2696- examples:2697- - program: 'scan("c")'2698- input: '"abcdefabc"'2699- output: ['"c"', '"c"']2700-2701- - title: "`split(regex; flags)`"2702- body: |2703-2704- Splits an input string on each regex match.2705-2706- For backwards compatibility, when called with a single argument,2707- `split` splits on a string, not a regex.2708-2709- examples:2710- - program: 'split(", *"; null)'2711- input: '"ab,cd, ef"'2712- output: ['["ab","cd","ef"]']2713-2714-2715- - title: "`splits(regex)`, `splits(regex; flags)`"2716- body: |2717-2718- These provide the same results as their `split` counterparts,2719- but as a stream instead of an array.2720-2721- examples:2722- - program: 'splits(", *")'2723- input: '"ab,cd, ef, gh"'2724- output: ['"ab"','"cd"','"ef"','"gh"']2725-2726- - title: "`sub(regex; tostring)`, `sub(regex; tostring; flags)`"2727- body: |2728-2729- Emit the string obtained by replacing the first match of2730- regex in the input string with `tostring`, after2731- interpolation. `tostring` should be a jq string or a stream2732- of such strings, each of which may contain references to2733- named captures. The named captures are, in effect, presented2734- as a JSON object (as constructed by `capture`) to2735- `tostring`, so a reference to a captured variable named "x"2736- would take the form: `"\(.x)"`.2737-2738- examples:2739- - program: 'sub("[^a-z]*(?<x>[a-z]+)"; "Z\(.x)"; "g")'2740- input: '"123abc456def"'2741- output: ['"ZabcZdef"']2742-2743- - program: '[sub("(?<a>.)"; "\(.a|ascii_upcase)", "\(.a|ascii_downcase)")]'2744- input: '"aB"'2745- output: ['["AB","aB"]']2746-2747- - title: "`gsub(regex; tostring)`, `gsub(regex; tostring; flags)`"2748- body: |2749-2750- `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2751- replaced by `tostring`, after interpolation. If the second argument is a stream2752- of jq strings, then `gsub` will produce a corresponding stream of JSON strings.2753-2754- examples:2755- - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2756- input: '"Abcabc"'2757- output: ['"+A-+a-"']2758-2759- - program: '[gsub("p"; "a", "b")]'2760- input: '"p"'2761- output: ['["a","b"]']2762-2763-2764- - title: Advanced features2765- body: |2766- Variables are an absolute necessity in most programming languages, but2767- they're relegated to an "advanced feature" in jq.2768-2769- In most languages, variables are the only means of passing around2770- data. If you calculate a value, and you want to use it more than once,2771- you'll need to store it in a variable. To pass a value to another part2772- of the program, you'll need that part of the program to define a2773- variable (as a function parameter, object member, or whatever) in2774- which to place the data.2775-2776- It is also possible to define functions in jq, although this is2777- is a feature whose biggest use is defining jq's standard library2778- (many jq functions such as `map` and `select` are in fact written2779- in jq).2780-2781- jq has reduction operators, which are very powerful but a bit2782- tricky. Again, these are mostly used internally, to define some2783- useful bits of jq's standard library.2784-2785- It may not be obvious at first, but jq is all about generators2786- (yes, as often found in other languages). Some utilities are2787- provided to help deal with generators.2788-2789- Some minimal I/O support (besides reading JSON from standard2790- input, and writing JSON to standard output) is available.2791-2792- Finally, there is a module/library system.2793-2794- entries:2795- - title: "Variable / Symbolic Binding Operator: `... as $identifier | ...`"2796- body: |2797-2798- In jq, all filters have an input and an output, so manual2799- plumbing is not necessary to pass a value from one part of a program2800- to the next. Many expressions, for instance `a + b`, pass their input2801- to two distinct subexpressions (here `a` and `b` are both passed the2802- same input), so variables aren't usually necessary in order to use a2803- value twice.2804-2805- For instance, calculating the average value of an array of numbers2806- requires a few variables in most languages - at least one to hold the2807- array, perhaps one for each element or for a loop counter. In jq, it's2808- simply `add / length` - the `add` expression is given the array and2809- produces its sum, and the `length` expression is given the array and2810- produces its length.2811-2812- So, there's generally a cleaner way to solve most problems in jq than2813- defining variables. Still, sometimes they do make things easier, so jq2814- lets you define variables using `expression as $variable`. All2815- variable names start with `$`. Here's a slightly uglier version of the2816- array-averaging example:2817-2818- length as $array_length | add / $array_length2819-2820- We'll need a more complicated problem to find a situation where using2821- variables actually makes our lives easier.2822-2823-2824- Suppose we have an array of blog posts, with "author" and "title"2825- fields, and another object which is used to map author usernames to2826- real names. Our input looks like:2827-2828- {"posts": [{"title": "First post", "author": "anon"},2829- {"title": "A well-written article", "author": "person1"}],2830- "realnames": {"anon": "Anonymous Coward",2831- "person1": "Person McPherson"}}2832-2833- We want to produce the posts with the author field containing a real2834- name, as in:2835-2836- {"title": "First post", "author": "Anonymous Coward"}2837- {"title": "A well-written article", "author": "Person McPherson"}2838-2839- We use a variable, $names, to store the realnames object, so that we2840- can refer to it later when looking up author usernames:2841-2842- .realnames as $names | .posts[] | {title, author: $names[.author]}2843-2844- The expression `exp as $x | ...` means: for each value of expression2845- `exp`, run the rest of the pipeline with the entire original input, and2846- with `$x` set to that value. Thus `as` functions as something of a2847- foreach loop.2848-2849- Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2850- `{$foo}` is a handy way of writing `{foo: $foo}`.2851-2852- Multiple variables may be declared using a single `as` expression by2853- providing a pattern that matches the structure of the input2854- (this is known as "destructuring"):2855-2856- . as {realnames: $names, posts: [$first, $second]} | ...2857-2858- The variable declarations in array patterns (e.g., `. as2859- [$first, $second]`) bind to the elements of the array in from2860- the element at index zero on up, in order. When there is no2861- value at the index for an array pattern element, `null` is2862- bound to that variable.2863-2864- Variables are scoped over the rest of the expression that defines2865- them, so2866-2867- .realnames as $names | (.posts[] | {title, author: $names[.author]})2868-2869- will work, but2870-2871- (.realnames as $names | .posts[]) | {title, author: $names[.author]}2872-2873- won't.2874-2875- For programming language theorists, it's more accurate to2876- say that jq variables are lexically-scoped bindings. In2877- particular there's no way to change the value of a binding;2878- one can only setup a new binding with the same name, but which2879- will not be visible where the old one was.2880-2881- examples:2882- - program: '.bar as $x | .foo | . + $x'2883- input: '{"foo":10, "bar":200}'2884- output: ['210']2885- - program: '. as $i|[(.*2|. as $i| $i), $i]'2886- input: '5'2887- output: ['[10,5]']2888- - program: '. as [$a, $b, {c: $c}] | $a + $b + $c'2889- input: '[2, 3, {"c": 4, "d": 5}]'2890- output: ['9']2891- - program: '.[] as [$a, $b] | {a: $a, b: $b}'2892- input: '[[0], [0, 1], [2, 1, 0]]'2893- output: ['{"a":0,"b":null}', '{"a":0,"b":1}', '{"a":2,"b":1}']2894-2895- - title: 'Destructuring Alternative Operator: `?//`'2896- body: |2897-2898- The destructuring alternative operator provides a concise mechanism2899- for destructuring an input that can take one of several forms.2900-2901- Suppose we have an API that returns a list of resources and events2902- associated with them, and we want to get the user_id and timestamp of2903- the first event for each resource. The API (having been clumsily2904- converted from XML) will only wrap the events in an array if the resource2905- has multiple events:2906-2907- {"resources": [{"id": 1, "kind": "widget", "events": {"action": "create", "user_id": 1, "ts": 13}},2908- {"id": 2, "kind": "widget", "events": [{"action": "create", "user_id": 1, "ts": 14}, {"action": "destroy", "user_id": 1, "ts": 15}]}]}2909-2910- We can use the destructuring alternative operator to handle this structural change simply:2911-2912- .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$user_id, $ts}]} | {$user_id, $kind, $id, $ts}2913-2914- Or, if we aren't sure if the input is an array of values or an object:2915-2916- .[] as [$id, $kind, $user_id, $ts] ?// {$id, $kind, $user_id, $ts} | ...2917-2918- Each alternative need not define all of the same variables, but all named2919- variables will be available to the subsequent expression. Variables not2920- matched in the alternative that succeeded will be `null`:2921-2922- .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}2923-2924- Additionally, if the subsequent expression returns an error, the2925- alternative operator will attempt to try the next binding. Errors2926- that occur during the final alternative are passed through.2927-2928- [[3]] | .[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end2929-2930- examples:2931- - program: '.[] as {$a, $b, c: {$d, $e}} ?// {$a, $b, c: [{$d, $e}]} | {$a, $b, $d, $e}'2932- input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2933- output: ['{"a":1,"b":2,"d":3,"e":4}', '{"a":1,"b":2,"d":3,"e":4}']2934- - program: '.[] as {$a, $b, c: {$d}} ?// {$a, $b, c: [{$e}]} | {$a, $b, $d, $e}'2935- input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2936- output: ['{"a":1,"b":2,"d":3,"e":null}', '{"a":1,"b":2,"d":null,"e":4}']2937- - program: '.[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end'2938- input: '[[3]]'2939- output: ['{"a":null,"b":3}']2940-2941- - title: 'Defining Functions'2942- body: |2943-2944- You can give a filter a name using "def" syntax:2945-2946- def increment: . + 1;2947-2948- From then on, `increment` is usable as a filter just like a2949- builtin function (in fact, this is how many of the builtins2950- are defined). A function may take arguments:2951-2952- def map(f): [.[] | f];2953-2954- Arguments are passed as _filters_ (functions with no2955- arguments), _not_ as values. The same argument may be2956- referenced multiple times with different inputs (here `f` is2957- run for each element of the input array). Arguments to a2958- function work more like callbacks than like value arguments.2959- This is important to understand. Consider:2960-2961- def foo(f): f|f;2962- 5|foo(.*2)2963-2964- The result will be 20 because `f` is `.*2`, and during the2965- first invocation of `f` `.` will be 5, and the second time it2966- will be 10 (5 * 2), so the result will be 20. Function2967- arguments are filters, and filters expect an input when2968- invoked.2969-2970- If you want the value-argument behaviour for defining simple2971- functions, you can just use a variable:2972-2973- def addvalue(f): f as $f | map(. + $f);2974-2975- Or use the short-hand:2976-2977- def addvalue($f): ...;2978-2979- With either definition, `addvalue(.foo)` will add the current2980- input's `.foo` field to each element of the array. Do note2981- that calling `addvalue(.[])` will cause the `map(. + $f)` part2982- to be evaluated once per value in the value of `.` at the call2983- site.2984-2985- Multiple definitions using the same function name are allowed.2986- Each re-definition replaces the previous one for the same2987- number of function arguments, but only for references from2988- functions (or main program) subsequent to the re-definition.2989- See also the section below on scoping.2990-2991- examples:2992- - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'2993- input: '[[1,2],[10,20]]'2994- output: ['[[1,2,1], [10,20,10]]']2995- - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'2996- input: '[[1,2],[10,20]]'2997- output: ['[[1,2,1,2], [10,20,1,2]]']2998-2999- - title: 'Scoping'3000- body: |3001-3002- There are two types of symbols in jq: value bindings (a.k.a.,3003- "variables"), and functions. Both are scoped lexically,3004- with expressions being able to refer only to symbols that3005- have been defined "to the left" of them. The only exception3006- to this rule is that functions can refer to themselves so as3007- to be able to create recursive functions.3008-3009- For example, in the following expression there is a binding3010- which is visible "to the right" of it, `... | .*3 as3011- $times_three | [. + $times_three] | ...`, but not "to the3012- left". Consider this expression now, `... | (.*3 as3013- $times_three | [. + $times_three]) | ...`: here the binding3014- `$times_three` is _not_ visible past the closing parenthesis.3015-3016- - title: "`isempty(exp)`"3017- body: |3018-3019- Returns true if `exp` produces no outputs, false otherwise.3020-3021- examples:3022- - program: 'isempty(empty)'3023- input: 'null'3024- output: ['true']3025-3026- - program: 'isempty(.[])'3027- input: '[]'3028- output: ['true']3029-3030- - program: 'isempty(.[])'3031- input: '[1,2,3]'3032- output: ['false']3033-3034- - title: "`limit(n; exp)`"3035- body: |3036-3037- The `limit` function extracts up to `n` outputs from `exp`.3038-3039- examples:3040- - program: '[limit(3;.[])]'3041- input: '[0,1,2,3,4,5,6,7,8,9]'3042- output: ['[0,1,2]']3043-3044- - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"3045- body: |3046-3047- The `first(expr)` and `last(expr)` functions extract the first3048- and last values from `expr`, respectively.3049-3050- The `nth(n; expr)` function extracts the nth value output by `expr`.3051- Note that `nth(n; expr)` doesn't support negative values of `n`.3052-3053- examples:3054- - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'3055- input: '10'3056- output: ['[0,9,5]']3057-3058- - title: "`first`, `last`, `nth(n)`"3059- body: |3060-3061- The `first` and `last` functions extract the first3062- and last values from any array at `.`.3063-3064- The `nth(n)` function extracts the nth value of any array at `.`.3065-3066- examples:3067- - program: '[range(.)]|[first, last, nth(5)]'3068- input: '10'3069- output: ['[0,9,5]']3070-3071- - title: "`reduce`"3072- body: |3073-3074- The `reduce` syntax allows you to combine all of the results of3075- an expression by accumulating them into a single answer.3076- The form is `reduce EXP as $var (INIT; UPDATE)`.3077- As an example, we'll pass `[1,2,3]` to this expression:3078-3079- reduce .[] as $item (0; . + $item)3080-3081- For each result that `.[]` produces, `. + $item` is run to3082- accumulate a running total, starting from 0 as the input value.3083- In this example, `.[]` produces the results `1`, `2`, and `3`,3084- so the effect is similar to running something like this:3085-3086- 0 | 1 as $item | . + $item |3087- 2 as $item | . + $item |3088- 3 as $item | . + $item3089-3090- examples:3091- - program: 'reduce .[] as $item (0; . + $item)'3092- input: '[1,2,3,4,5]'3093- output: ['15']3094-3095- - program: 'reduce .[] as [$i,$j] (0; . + $i * $j)'3096- input: '[[1,2],[3,4],[5,6]]'3097- output: ['44']3098-3099- - program: 'reduce .[] as {$x,$y} (null; .x += $x | .y += [$y])'3100- input: '[{"x":"a","y":1},{"x":"b","y":2},{"x":"c","y":3}]'3101- output: ['{"x":"abc","y":[1,2,3]}']3102-3103- - title: "`foreach`"3104- body: |3105-3106- The `foreach` syntax is similar to `reduce`, but intended to3107- allow the construction of `limit` and reducers that produce3108- intermediate results.3109-3110- The form is `foreach EXP as $var (INIT; UPDATE; EXTRACT)`.3111- As an example, we'll pass `[1,2,3]` to this expression:3112-3113- foreach .[] as $item (0; . + $item; [$item, . * 2])3114-3115- Like the `reduce` syntax, `. + $item` is run for each result3116- that `.[]` produces, but `[$item, . * 2]` is run for each3117- intermediate values. In this example, since the intermediate3118- values are `1`, `3`, and `6`, the `foreach` expression produces3119- `[1,2]`, `[2,6]`, and `[3,12]`. So the effect is similar3120- to running something like this:3121-3122- 0 | 1 as $item | . + $item | [$item, . * 2],3123- 2 as $item | . + $item | [$item, . * 2],3124- 3 as $item | . + $item | [$item, . * 2]3125-3126- When `EXTRACT` is omitted, the identity filter is used.3127- That is, it outputs the intermediate values as they are.3128-3129- examples:3130- - program: 'foreach .[] as $item (0; . + $item)'3131- input: '[1,2,3,4,5]'3132- output: ['1','3','6','10','15']3133-3134- - program: 'foreach .[] as $item (0; . + $item; [$item, . * 2])'3135- input: '[1,2,3,4,5]'3136- output: ['[1,2]','[2,6]','[3,12]','[4,20]','[5,30]']3137-3138- - program: 'foreach .[] as $item (0; . + 1; {index: ., $item})'3139- input: '["foo", "bar", "baz"]'3140- output:3141- - '{"index":1,"item":"foo"}'3142- - '{"index":2,"item":"bar"}'3143- - '{"index":3,"item":"baz"}'3144-3145- - title: Recursion3146- body: |3147-3148- As described above, `recurse` uses recursion, and any jq3149- function can be recursive. The `while` builtin is also3150- implemented in terms of recursion.3151-3152- Tail calls are optimized whenever the expression to the left of3153- the recursive call outputs its last value. In practice this3154- means that the expression to the left of the recursive call3155- should not produce more than one output for each input.3156-3157- For example:3158-3159- def recurse(f): def r: ., (f | select(. != null) | r); r;3160-3161- def while(cond; update):3162- def _while:3163- if cond then ., (update | _while) else empty end;3164- _while;3165-3166- def repeat(exp):3167- def _repeat:3168- exp, _repeat;3169- _repeat;3170-3171- - title: Generators and iterators3172- body: |3173-3174- Some jq operators and functions are actually generators in3175- that they can produce zero, one, or more values for each3176- input, just as one might expect in other programming3177- languages that have generators. For example, `.[]`3178- generates all the values in its input (which must be an3179- array or an object), `range(0; 10)` generates the integers3180- between 0 and 10, and so on.3181-3182- Even the comma operator is a generator, generating first3183- the values generated by the expression to the left of the3184- comma, then the values generated by the expression on the3185- right of the comma.3186-3187- The `empty` builtin is the generator that produces zero3188- outputs. The `empty` builtin backtracks to the preceding3189- generator expression.3190-3191- All jq functions can be generators just by using builtin3192- generators. It is also possible to construct new generators3193- using only recursion and the comma operator. If3194- recursive calls are "in tail position" then the3195- generator will be efficient. In the example below the3196- recursive call by `_range` to itself is in tail position.3197- The example shows off three advanced topics: tail recursion,3198- generator construction, and sub-functions.3199-3200- examples:3201- - program: 'def range(init; upto; by):3202- def _range:3203- if (by > 0 and . < upto) or (by < 0 and . > upto)3204- then ., ((.+by)|_range)3205- else . end;3206- if by == 0 then init else init|_range end |3207- select((by > 0 and . < upto) or (by < 0 and . > upto));3208- range(0; 10; 3)'3209- input: 'null'3210- output: ['0', '3', '6', '9']3211- - program: 'def while(cond; update):3212- def _while:3213- if cond then ., (update | _while) else empty end;3214- _while;3215- [while(.<100; .*2)]'3216- input: '1'3217- output: ['[1,2,4,8,16,32,64]']3218-3219- - title: 'Math'3220- body: |3221-3222- jq currently only has IEEE754 double-precision (64-bit) floating3223- point number support.3224-3225- Besides simple arithmetic operators such as `+`, jq also has most3226- standard math functions from the C math library. C math functions3227- that take a single input argument (e.g., `sin()`) are available as3228- zero-argument jq functions. C math functions that take two input3229- arguments (e.g., `pow()`) are available as two-argument jq3230- functions that ignore `.`. C math functions that take three input3231- arguments are available as three-argument jq functions that ignore3232- `.`.3233-3234- Availability of standard math functions depends on the3235- availability of the corresponding math functions in your operating3236- system and C math library. Unavailable math functions will be3237- defined but will raise an error.3238-3239- One-input C math functions: `acos` `acosh` `asin` `asinh` `atan`3240- `atanh` `cbrt` `ceil` `cos` `cosh` `erf` `erfc` `exp` `exp10`3241- `exp2` `expm1` `fabs` `floor` `gamma` `j0` `j1` `lgamma` `log`3242- `log10` `log1p` `log2` `logb` `nearbyint` `rint` `round`3243- `significand` `sin` `sinh` `sqrt` `tan` `tanh` `tgamma` `trunc`3244- `y0` `y1`.3245-3246- Two-input C math functions: `atan2` `copysign` `drem` `fdim`3247- `fmax` `fmin` `fmod` `frexp` `hypot` `jn` `ldexp` `modf`3248- `nextafter` `nexttoward` `pow` `remainder` `scalb` `scalbln` `yn`.3249-3250- Three-input C math functions: `fma`.3251-3252- See your system's manual for more information on each of these.3253-3254- - title: 'I/O'3255- body: |3256-3257- At this time jq has minimal support for I/O, mostly in the3258- form of control over when inputs are read. Two builtins functions3259- are provided for this, `input` and `inputs`, that read from the3260- same sources (e.g., `stdin`, files named on the command-line) as3261- jq itself. These two builtins, and jq's own reading actions, can3262- be interleaved with each other. They are commonly used in combination3263- with the null input option `-n` to prevent one input from being read3264- implicitly.3265-3266- Two builtins provide minimal output capabilities, `debug`, and3267- `stderr`. (Recall that a jq program's output values are always3268- output as JSON texts on `stdout`.) The `debug` builtin can have3269- application-specific behavior, such as for executables that use3270- the libjq C API but aren't the jq executable itself. The `stderr`3271- builtin outputs its input in raw mode to stder with no additional3272- decoration, not even a newline.3273-3274- Most jq builtins are referentially transparent, and yield constant3275- and repeatable value streams when applied to constant inputs.3276- This is not true of I/O builtins.3277-3278- entries:3279- - title: "`input`"3280- body: |3281-3282- Outputs one new input.3283-3284- Note that when using `input` it is generally be necessary to3285- invoke jq with the `-n` command-line option, otherwise3286- the first entity will be lost.3287-3288- echo 1 2 3 4 | jq '[., input]' # [1,2] [3,4]3289-3290- - title: "`inputs`"3291- body: |3292-3293- Outputs all remaining inputs, one by one.3294-3295- This is primarily useful for reductions over a program's3296- inputs. Note that when using `inputs` it is generally necessary3297- to invoke jq with the `-n` command-line option, otherwise3298- the first entity will be lost.3299-3300- echo 1 2 3 | jq -n 'reduce inputs as $i (0; . + $i)' # 63301-3302- - title: "`debug`, `debug(msgs)`"3303- body: |3304-3305- These two filters are like `.` but have as a side-effect the3306- production of one or more messages on stderr.3307-3308- The message produced by the `debug` filter has the form3309-3310- ["DEBUG:",<input-value>]3311-3312- where `<input-value>` is a compact rendition of the input3313- value. This format may change in the future.3314-3315- The `debug(msgs)` filter is defined as `(msgs | debug | empty), .`3316- thus allowing great flexibility in the content of the message,3317- while also allowing multi-line debugging statements to be created.3318-3319- For example, the expression:3320-3321- 1 as $x | 2 | debug("Entering function foo with $x == \($x)", .) | (.+1)3322-3323- would produce the value 3 but with the following two lines3324- being written to stderr:3325-3326- ["DEBUG:","Entering function foo with $x == 1"]3327- ["DEBUG:",2]3328-3329- - title: "`stderr`"3330- body: |3331-3332- Prints its input in raw and compact mode to stderr with no3333- additional decoration, not even a newline.3334-3335- - title: "`input_filename`"3336- body: |3337-3338- Returns the name of the file whose input is currently being3339- filtered. Note that this will not work well unless jq is3340- running in a UTF-8 locale.3341-3342- - title: "`input_line_number`"3343- body: |3344-3345- Returns the line number of the input currently being filtered.3346-3347- - title: 'Streaming'3348- body: |3349-3350- With the `--stream` option jq can parse input texts in a streaming3351- fashion, allowing jq programs to start processing large JSON texts3352- immediately rather than after the parse completes. If you have a3353- single JSON text that is 1GB in size, streaming it will allow you3354- to process it much more quickly.3355-3356- However, streaming isn't easy to deal with as the jq program will3357- have `[<path>, <leaf-value>]` (and a few other forms) as inputs.3358-3359- Several builtins are provided to make handling streams easier.3360-3361- The examples below use the streamed form of `[0,[1]]`, which is3362- `[[0],0],[[1,0],1],[[1,0]],[[1]]`.3363-3364- Streaming forms include `[<path>, <leaf-value>]` (to indicate any3365- scalar value, empty array, or empty object), and `[<path>]` (to3366- indicate the end of an array or object). Future versions of jq3367- run with `--stream` and `--seq` may output additional forms such3368- as `["error message"]` when an input text fails to parse.3369-3370- entries:3371- - title: "`truncate_stream(stream_expression)`"3372- body: |3373-3374- Consumes a number as input and truncates the corresponding3375- number of path elements from the left of the outputs of the3376- given streaming expression.3377-3378- examples:3379- - program: 'truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])'3380- input: '1'3381- output: ['[[0],2]', '[[0]]']3382-3383- - title: "`fromstream(stream_expression)`"3384- body: |3385-3386- Outputs values corresponding to the stream expression's3387- outputs.3388-3389- examples:3390- - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'3391- input: 'null'3392- output: ['[2]']3393-3394- - title: "`tostream`"3395- body: |3396-3397- The `tostream` builtin outputs the streamed form of its input.3398-3399- examples:3400- - program: '. as $dot|fromstream($dot|tostream)|.==$dot'3401- input: '[0,[1,{"a":1},{"b":2}]]'3402- output: ['true']3403-3404- - title: Assignment3405- body: |3406- Assignment works a little differently in jq than in most3407- programming languages. jq doesn't distinguish between references3408- to and copies of something - two objects or arrays are either3409- equal or not equal, without any further notion of being "the3410- same object" or "not the same object".3411-3412- If an object has two fields which are arrays, `.foo` and `.bar`,3413- and you append something to `.foo`, then `.bar` will not get3414- bigger, even if you've previously set `.bar = .foo`. If you're3415- used to programming in languages like Python, Java, Ruby,3416- JavaScript, etc. then you can think of it as though jq does a full3417- deep copy of every object before it does the assignment (for3418- performance it doesn't actually do that, but that's the general3419- idea).3420-3421- This means that it's impossible to build circular values in jq3422- (such as an array whose first element is itself). This is quite3423- intentional, and ensures that anything a jq program can produce3424- can be represented in JSON.3425-3426- All the assignment operators in jq have path expressions on the3427- left-hand side (LHS). The right-hand side (RHS) provides values3428- to set to the paths named by the LHS path expressions.3429-3430- Values in jq are always immutable. Internally, assignment works3431- by using a reduction to compute new, replacement values for `.` that3432- have had all the desired assignments applied to `.`, then3433- outputting the modified value. This might be made clear by this3434- example: `{a:{b:{c:1}}} | (.a.b|=3), .`. This will output3435- `{"a":{"b":3}}` and `{"a":{"b":{"c":1}}}` because the last3436- sub-expression, `.`, sees the original value, not the modified3437- value.3438-3439- Most users will want to use modification assignment operators,3440- such as `|=` or `+=`, rather than `=`.3441-3442- Note that the LHS of assignment operators refers to a value in3443- `.`. Thus `$var.foo = 1` won't work as expected (`$var.foo` is3444- not a valid or useful path expression in `.`); use `$var | .foo =3445- 1` instead.3446-3447- Note too that `.a,.b=0` does not set `.a` and `.b`, but3448- `(.a,.b)=0` sets both.3449-3450- entries:3451- - title: "Update-assignment: `|=`"3452- body: |3453- This is the "update" operator `|=`. It takes a filter on the3454- right-hand side and works out the new value for the property3455- of `.` being assigned to by running the old value through this3456- expression. For instance, `(.foo, .bar) |= .+1` will build an3457- object with the `foo` field set to the input's `foo` plus 1,3458- and the `bar` field set to the input's `bar` plus 1.3459-3460- The left-hand side can be any general path expression; see `path()`.3461-3462- Note that the left-hand side of `|=` refers to a value in `.`.3463- Thus `$var.foo |= . + 1` won't work as expected (`$var.foo` is3464- not a valid or useful path expression in `.`); use `$var |3465- .foo |= . + 1` instead.3466-3467- If the right-hand side outputs no values (i.e., `empty`), then3468- the left-hand side path will be deleted, as with `del(path)`.3469-3470- If the right-hand side outputs multiple values, only the first3471- one will be used (COMPATIBILITY NOTE: in jq 1.5 and earlier3472- releases, it used to be that only the last one was used).3473-3474- examples:3475- - program: '(..|select(type=="boolean")) |= if . then 1 else 0 end'3476- input: '[true,false,[5,true,[true,[false]],false]]'3477- output: ['[1,0,[5,1,[1,[0]],0]]']3478-3479- - title: "Arithmetic update-assignment: `+=`, `-=`, `*=`, `/=`, `%=`, `//=`"3480- body: |3481-3482- jq has a few operators of the form `a op= b`, which are all3483- equivalent to `a |= . op b`. So, `+= 1` can be used to3484- increment values, being the same as `|= . + 1`.3485-3486- examples:3487- - program: .foo += 13488- input: '{"foo": 42}'3489- output: ['{"foo": 43}']3490-3491- - title: "Plain assignment: `=`"3492- body: |3493-3494- This is the plain assignment operator. Unlike the others, the3495- input to the right-hand side (RHS) is the same as the input to3496- the left-hand side (LHS) rather than the value at the LHS3497- path, and all values output by the RHS will be used (as shown3498- below).3499-3500- If the RHS of `=` produces multiple values, then for each such3501- value jq will set the paths on the left-hand side to the value3502- and then it will output the modified `.`. For example,3503- `(.a,.b) = range(2)` outputs `{"a":0,"b":0}`, then3504- `{"a":1,"b":1}`. The "update" assignment forms (see above) do3505- not do this.3506-3507- This example should show the difference between `=` and `|=`:3508-3509- Provide input `{"a": {"b": 10}, "b": 20}` to the programs3510-3511- .a = .b3512-3513- and3514-3515- .a |= .b3516-3517- The former will set the `a` field of the input to the `b`3518- field of the input, and produce the output `{"a": 20, "b": 20}`.3519- The latter will set the `a` field of the input to the `a`3520- field's `b` field, producing `{"a": 10, "b": 20}`.3521-3522- examples:3523- - program: .a = .b3524- input: '{"a": {"b": 10}, "b": 20}'3525- output: ['{"a":20,"b":20}']3526-3527- - program: .a |= .b3528- input: '{"a": {"b": 10}, "b": 20}'3529- output: ['{"a":10,"b":20}']3530-3531- - program: (.a, .b) = range(3)3532- input: 'null'3533- output:3534- - '{"a":0,"b":0}'3535- - '{"a":1,"b":1}'3536- - '{"a":2,"b":2}'3537-3538- - program: (.a, .b) |= range(3)3539- input: 'null'3540- output: ['{"a":0,"b":0}']3541-3542- - title: Complex assignments3543- body: |3544- Lots more things are allowed on the left-hand side of a jq assignment3545- than in most languages. We've already seen simple field accesses on3546- the left hand side, and it's no surprise that array accesses work just3547- as well:3548-3549- .posts[0].title = "JQ Manual"3550-3551- What may come as a surprise is that the expression on the left may3552- produce multiple results, referring to different points in the input3553- document:3554-3555- .posts[].comments |= . + ["this is great"]3556-3557- That example appends the string "this is great" to the "comments"3558- array of each post in the input (where the input is an object with a3559- field "posts" which is an array of posts).3560-3561- When jq encounters an assignment like 'a = b', it records the "path"3562- taken to select a part of the input document while executing a. This3563- path is then used to find which part of the input to change while3564- executing the assignment. Any filter may be used on the3565- left-hand side of an equals - whichever paths it selects from the3566- input will be where the assignment is performed.3567-3568- This is a very powerful operation. Suppose we wanted to add a comment3569- to blog posts, using the same "blog" input above. This time, we only3570- want to comment on the posts written by "stedolan". We can find those3571- posts using the "select" function described earlier:3572-3573- .posts[] | select(.author == "stedolan")3574-3575- The paths provided by this operation point to each of the posts that3576- "stedolan" wrote, and we can comment on each of them in the same way3577- that we did before:3578-3579- (.posts[] | select(.author == "stedolan") | .comments) |=3580- . + ["terrible."]3581-3582- - title: Comments3583-3584- body: |3585-3586- You can write comments in your jq filters using `#`.3587-3588- A `#` character (not part of a string) starts a comment.3589- All characters from `#` to the end of the line are ignored.3590-3591- If the end of the line is preceded by an odd number of backslash3592- characters, the following line is also considered part of the3593- comment and is ignored.3594-3595- For example, the following code outputs `[1,3,4,7]`3596-3597- [3598- 1,3599- # foo \3600- 2,3601- # bar \\3602- 3,3603- 4, # baz \\\3604- 5, \3605- 6,3606- 73607- # comment \3608- comment \3609- comment3610- ]3611-3612- Backslash continuing the comment on the next line can be useful3613- when writing the "shebang" for a jq script:3614-3615- #!/bin/sh --3616- # total - Output the sum of the given arguments (or stdin)3617- # usage: total [numbers...]3618- # \3619- exec jq --args -MRnf "$0" -- "$@"3620-3621- $ARGS.positional |3622- reduce (3623- if . == []3624- then inputs3625- else .[]3626- end |3627- . as $dot |3628- try tonumber catch false |3629- if not or isnan then3630- @json "total: Invalid number \($dot).\n" | halt_error(1)3631- end3632- ) as $n (0; . + $n)3633-3634- The `exec` line is considered a comment by jq, so it is ignored.3635- But it is not ignored by `sh`, since in `sh` a backslash at the3636- end of the line does not continue the comment.3637- With this trick, when the script is invoked as `total 1 2`,3638- `/bin/sh -- /path/to/total 1 2` will be run, and `sh` will then3639- run `exec jq --args -MRnf /path/to/total -- 1 2` replacing itself3640- with a `jq` interpreter invoked with the specified options (`-M`,3641- `-R`, `-n`, `--args`), that evaluates the current file (`$0`),3642- with the arguments (`$@`) that were passed to `sh`.3643-3644- - title: Modules3645- body: |3646-3647- jq has a library/module system. Modules are files whose names end3648- in `.jq`.3649-3650- Modules imported by a program are searched for in a default search3651- path (see below). The `import` and `include` directives allow the3652- importer to alter this path.3653-3654- Paths in the search path are subject to various substitutions.3655-3656- For paths starting with `~/`, the user's home directory is3657- substituted for `~`.3658-3659- For paths starting with `$ORIGIN/`, the directory where the jq3660- executable is located is substituted for `$ORIGIN`.3661-3662- For paths starting with `./` or paths that are `.`, the path of3663- the including file is substituted for `.`. For top-level programs3664- given on the command-line, the current directory is used.3665-3666- Import directives can optionally specify a search path to which3667- the default is appended.3668-3669- The default search path is the search path given to the `-L`3670- command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",3671- "$ORIGIN/../lib"]`.3672-3673- Null and empty string path elements terminate search path3674- processing.3675-3676- A dependency with relative path `foo/bar` would be searched for in3677- `foo/bar.jq` and `foo/bar/bar.jq` in the given search path. This3678- is intended to allow modules to be placed in a directory along3679- with, for example, version control files, README files, and so on,3680- but also to allow for single-file modules.3681-3682- Consecutive components with the same name are not allowed to avoid3683- ambiguities (e.g., `foo/foo`).3684-3685- For example, with `-L$HOME/.jq` a module `foo` can be found in3686- `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.3687-3688- If `$HOME/.jq` is a file, it is sourced into the main program.3689-3690- entries:3691- - title: "`import RelativePathString as NAME [<metadata>];`"3692- body: |3693-3694- Imports a module found at the given path relative to a3695- directory in a search path. A `.jq` suffix will be added to3696- the relative path string. The module's symbols are prefixed3697- with `NAME::`.3698-3699- The optional metadata must be a constant jq expression. It3700- should be an object with keys like `homepage` and so on. At3701- this time jq only uses the `search` key/value of the metadata.3702- The metadata is also made available to users via the3703- `modulemeta` builtin.3704-3705- The `search` key in the metadata, if present, should have a3706- string or array value (array of strings); this is the search3707- path to be prefixed to the top-level search path.3708-3709- - title: "`include RelativePathString [<metadata>];`"3710- body: |3711-3712- Imports a module found at the given path relative to a3713- directory in a search path as if it were included in place. A3714- `.jq` suffix will be added to the relative path string. The3715- module's symbols are imported into the caller's namespace as3716- if the module's content had been included directly.3717-3718- The optional metadata must be a constant jq expression. It3719- should be an object with keys like `homepage` and so on. At3720- this time jq only uses the `search` key/value of the metadata.3721- The metadata is also made available to users via the3722- `modulemeta` builtin.3723-3724- - title: "`import RelativePathString as $NAME [<metadata>];`"3725- body: |3726-3727- Imports a JSON file found at the given path relative to a3728- directory in a search path. A `.json` suffix will be added to3729- the relative path string. The file's data will be available3730- as `$NAME::NAME`.3731-3732- The optional metadata must be a constant jq expression. It3733- should be an object with keys like `homepage` and so on. At3734- this time jq only uses the `search` key/value of the metadata.3735- The metadata is also made available to users via the3736- `modulemeta` builtin.3737-3738- The `search` key in the metadata, if present, should have a3739- string or array value (array of strings); this is the search3740- path to be prefixed to the top-level search path.3741-3742- - title: "`module <metadata>;`"3743- body: |3744-3745- This directive is entirely optional. It's not required for3746- proper operation. It serves only the purpose of providing3747- metadata that can be read with the `modulemeta` builtin.3748-3749- The metadata must be a constant jq expression. It should be3750- an object with keys like `homepage`. At this time jq doesn't3751- use this metadata, but it is made available to users via the3752- `modulemeta` builtin.3753-3754- - title: "`modulemeta`"3755- body: |3756-3757- Takes a module name as input and outputs the module's metadata3758- as an object, with the module's imports (including metadata)3759- as an array value for the `deps` key and the module's defined3760- functions as an array value for the `defs` key.3761-3762- Programs can use this to query a module's metadata, which they3763- could then use to, for example, search for, download, and3764- install missing dependencies.3765-3766- - title: Colors3767- body: |3768-3769- To configure alternative colors just set the `JQ_COLORS`3770- environment variable to colon-delimited list of partial terminal3771- escape sequences like `"1;31"`, in this order:3772-3773- - color for `null`3774- - color for `false`3775- - color for `true`3776- - color for numbers3777- - color for strings3778- - color for arrays3779- - color for objects3780- - color for object keys3781-3782- The default color scheme is the same as setting3783- `JQ_COLORS="0;90:0;39:0;39:0;39:0;32:1;39:1;39:1;34"`.3784-3785- This is not a manual for VT100/ANSI escapes. However, each of3786- these color specifications should consist of two numbers separated3787- by a semi-colon, where the first number is one of these:3788-3789- - 1 (bright)3790- - 2 (dim)3791- - 4 (underscore)3792- - 5 (blink)3793- - 7 (reverse)3794- - 8 (hidden)3795-3796- and the second is one of these:3797-3798- - 30 (black)3799- - 31 (red)3800- - 32 (green)3801- - 33 (yellow)3802- - 34 (blue)3803- - 35 (magenta)3804- - 36 (cyan)3805- - 37 (white)1+v1.7/manual.ymlmodified:docs/templates/manual.html.j2+11 added-1 removed
31 unmodified lines32 {%- set _ = section_ids.__setitem__(id, true) %}33 {%- endmacro %}34 <main id="main" class="col-md-9" data-bs-spy="scroll" data-bs-target="#contents" data-bs-threshold="0,1" data-bs-root-margin="-30% 0% -70%">35 <h1>{{ headline }}</h1>36- {{ history | markdownify }}36+ <p>37+ <em>38+ For other versions, see39+ <a href="{{ root }}/manual/v1.7/">1.7</a>,40+ <a href="{{ root }}/manual/v1.6/">1.6</a>,41+ <a href="{{ root }}/manual/v1.5/">1.5</a>,42+ <a href="{{ root }}/manual/v1.4/">1.4</a>,43+ <a href="{{ root }}/manual/v1.3/">1.3</a> or44+ <a href="{{ root }}/manual/dev/">development version</a>.45+ </em>46+ </p>47 {{ body | markdownify }}48 {%- for section in sections %}49 <section id="{{ section.title | section_id }}">{{ check_section_id(section.title | section_id) }}50 <h2>{{ section.title }} <a href="#{{ section.title | section_id }}" class="icon-link" aria-label="Link to this section: {{ section.title }}"><span class="bi bi-link-45deg" aria-hidden="true"></span></a></h2>70 unmodified linesmodified:docs/build_manpage.py+1 added-1 removed
207 unmodified lines208 209 210 def convert_manual_to_markdown():211 f = StringIO()212- manual = load_yml_file("content/manual/manual.yml")212+ manual = load_yml_file("content/manual/dev/manual.yml")213 f.write(manual.get('manpage_intro', '\n'))214 f.write(dedent_body(manual.get('body', '\n')))215 for section in manual.get('sections', []):216 f.write('## {}\n'.format(section.get('title', '').upper()))35 unmodified linesmodified:docs/build_mantests.py+1 added-1 removed
3 unmodified lines4 5 regex_program_pattern = re.compile(6 r'\b(?:test|match|capture|scan|split|splits|sub|gsub)\s*\(')7 8-with open('content/manual/manual.yml') as source, \8+with open('content/manual/dev/manual.yml') as source, \9 open('../tests/man.test', 'w') as man, \10 open('../tests/manonig.test', 'w') as manonig:11 manual = yaml.safe_load(source)12 for section in manual.get('sections', []):9 unmodified linesmodified:docs/manual_schema.yml-3 removed
1 type: object2 required:3 - headline4- - history4 - body5 - manpage_intro6 - manpage_epilogue7 - sections8 additionalProperties: false9 properties:10 headline:11 type: string13- history:14- type: string12 body:13 type: string14 manpage_intro:15 type: string45 unmodified linesmodified:Makefile.am+4 added-4 removed
158 unmodified lines159 # As a result, we need to rebuild the tests if the manual has been updated.160 # Making changes to the manpage without having the python deps means your161 # tests won't run. If you aren't making changes to the examples, you probably162 # don't care. But if you are, then you need to run the tests anyway.163-tests/man.test tests/manonig.test: $(srcdir)/docs/content/manual/manual.yml163+tests/man.test tests/manonig.test: $(srcdir)/docs/content/manual/dev/manual.yml164 if ENABLE_DOCS165 $(AM_V_GEN) ( cd ${abs_srcdir}/docs && \166- $(PIPENV) run python validate_manual_schema.py content/manual/manual.yml && \166+ $(PIPENV) run python validate_manual_schema.py content/manual/dev/manual.yml && \167 $(PIPENV) run python build_mantests.py )168 else169 @echo Changes to the manual.yml require docs to be enabled to update the manual test.170 @echo As a result, the manual test is out of date.4 unmodified lines175 # We build the docs from the manpage yml. If no changes have been made to the176 # manpage, then we'll end up using the cached version. Otherwise, we need to177 # rebuild it.178 man_MANS = jq.1179-jq.1.prebuilt: $(srcdir)/docs/content/manual/manual.yml179+jq.1.prebuilt: $(srcdir)/docs/content/manual/dev/manual.yml180 if ENABLE_DOCS181 $(AM_V_GEN) ( cd ${abs_srcdir}/docs && \182- $(PIPENV) run python validate_manual_schema.py content/manual/manual.yml && \182+ $(PIPENV) run python validate_manual_schema.py content/manual/dev/manual.yml && \183 $(PIPENV) run python build_manpage.py ) > $@184 else185 @echo Changes to the manual.yml require docs to be enabled to update the manpage.186 @echo As a result, the manpage is out of date.69 unmodified lines