Update website with details for jq-1.6
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by William Langford · committed by William Langford · parent cd4f61a · Browse files · 4 files·+3314 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+3314 added−2 removed
- other:+3314 added−2 removed
Provenance
- Commit
3daecb2- Tree
cfb3fe1- Author
William Langford <wlangfor@gmail.com>- Committer
William Langford <wlangfor@gmail.com>- Parent
cd4f61a
4 files changed+3314 added−2 removed
modified:docs/content/2.download/default.yml+18 added
29 unmodified lines3031323334353637383940414212 unmodified lines555657585960616263646530 unmodified lines9697989910010110210310410510610710812 unmodified lines12112212312412512612712812913013113213313413513613713813914014114214314414514614746 unmodified lines29 unmodified lines * jq 1.5 is in the official [Arch](https://www.archlinux.org/packages/?sort=&q=jq&maintainer=&flagged=) repository. Install using `sudo pacman -Sy jq`.
* jq 1.6 binaries for [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64) or [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux32).
* jq 1.5 binaries for [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64) or [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux32).12 unmodified lines
* Use [Homebrew](http://brew.sh/) to install jq 1.5 with `brew install jq`.
* jq 1.6 binary for [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-osx-amd64).
* jq 1.5 binary for [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-osx-amd64).
* jq 1.4 binaries for30 unmodified lines
* Use [Chocolatey NuGet](https://chocolatey.org/) to install jq 1.5 with `chocolatey install jq`.
* jq 1.6 executables for [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-win64.exe) or [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-win32.exe).
* jq 1.5 executables for [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-win64.exe) or [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-win32.exe).12 unmodified lines
SHA-256 checksums are provided for all release and pre-release binaries. They can be found under [sig/v1.x/sha256sum.txt](https://github.com/stedolan/jq/tree/master/sig). The checksums for jq 1.6 are in [sig/v1.6/sha256sum.txt](https://raw.githubusercontent.com/stedolan/jq/master/sig/v1.6/sha256sum.txt). The checksums for jq 1.5 are in [sig/v1.5/sha256sum.txt](https://raw.githubusercontent.com/stedolan/jq/master/sig/v1.5/sha256sum.txt).
Additionally, all binaries are signed by the [jq Package Signing Key](https://raw.githubusercontent.com/stedolan/jq/master/sig/jq-release.key). The signatures can be found under [sig/v1.x/\*.asc](https://github.com/stedolan/jq/tree/master/sig). The signatures for jq 1.6 are in [sig/v1.5/\*.asc](https://github.com/stedolan/jq/tree/master/sig/v1.6). The signatures for jq 1.5 are in [sig/v1.5/\*.asc](https://github.com/stedolan/jq/tree/master/sig/v1.5). You can use [GnuPG](https://gnupg.org/) to verify a signature by downloading the signature and running `gpg --verify signature.asc`.
### From source on Linux, OS X, Cygwin, and other POSIX-like operating systems
* [Source tarball for jq 1.6](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-1.6.tar.gz) * [Source tarball for jq 1.5](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-1.5.tar.gz)
You can build it using the usual `./configure && make && sudo make install` rigmarole.46 unmodified linesadded:docs/content/3.manual/v1.6/manual.yml+3287 added
1+---2+headline: jq Manual (development version)3+4+history: |5+6+ *For released versions, see [jq 1.5](/jq/manual/v1.5),7+ [jq 1.4](/jq/manual/v1.4) or [jq 1.3](/jq/manual/v1.3).*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/stedolan/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 out, again as a82+ sequence of whitespace-separated JSON data.83+84+ Note: it is important to mind the shell's quoting rules. As a85+ general rule it's best to always quote (with single-quote86+ characters) the jq program, as too many characters with special87+ meaning to jq are also shell meta-characters. For example, `jq88+ "foo"` will fail on most Unix shells because that will be the same89+ as `jq foo`, which will generally fail because `foo is not90+ defined`. When using the Windows command shell (cmd.exe) it's91+ best to use double quotes around your jq program when given on the92+ command-line (instead of the `-f program-file` option), but then93+ double-quotes in the jq program need backslash escaping.94+95+ You can affect how jq reads and writes its input and output96+ using some command-line options:97+98+ * `--version`:99+100+ Output the jq version and exit with zero.101+102+ * `--seq`:103+104+ Use the `application/json-seq` MIME type scheme for separating105+ JSON texts in jq's input and output. This means that an ASCII106+ RS (record separator) character is printed before each value on107+ output and an ASCII LF (line feed) is printed after every108+ output. Input JSON texts that fail to parse are ignored (but109+ warned about), discarding all subsequent input until the next110+ RS. This mode also parses the output of jq without the `--seq`111+ option.112+113+ * `--stream`:114+115+ Parse the input in streaming fashion, outputing arrays of path116+ and leaf values (scalars and empty arrays or empty objects).117+ For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]`118+ becomes `[[0],[]]`, `[[1],"a"]`, and `[[1,0],"b"]`.119+120+ This is useful for processing very large inputs. Use this in121+ conjunction with filtering and the `reduce` and `foreach` syntax122+ to reduce large inputs incrementally.123+124+ * `--slurp`/`-s`:125+126+ Instead of running the filter for each JSON object in the127+ input, read the entire input stream into a large array and run128+ the filter just once.129+130+ * `--raw-input`/`-R`:131+132+ Don't parse the input as JSON. Instead, each line of text is133+ passed to the filter as a string. If combined with `--slurp`,134+ then the entire input is passed to the filter as a single long135+ string.136+137+ * `--null-input`/`-n`:138+139+ Don't read any input at all! Instead, the filter is run once140+ using `null` as the input. This is useful when using jq as a141+ simple calculator or to construct JSON data from scratch.142+143+ * `--compact-output` / `-c`:144+145+ By default, jq pretty-prints JSON output. Using this option146+ will result in more compact output by instead putting each147+ JSON object on a single line.148+149+ * `--tab`:150+151+ Use a tab for each indentation level instead of two spaces.152+153+ * `--indent n`:154+155+ Use the given number of spaces (no more than 8) for indentation.156+157+ * `--color-output` / `-C` and `--monochrome-output` / `-M`:158+159+ By default, jq outputs colored JSON if writing to a160+ terminal. You can force it to produce color even if writing to161+ a pipe or a file using `-C`, and disable color with `-M`.162+163+ Colors can be configured with the `JQ_COLORS` environment164+ variable (see below).165+166+ * `--ascii-output` / `-a`:167+168+ jq usually outputs non-ASCII Unicode codepoints as UTF-8, even169+ if the input specified them as escape sequences (like170+ "\u03bc"). Using this option, you can force jq to produce pure171+ ASCII output with every non-ASCII character replaced with the172+ equivalent escape sequence.173+174+ * `--unbuffered`175+176+ Flush the output after each JSON object is printed (useful if177+ you're piping a slow data source into jq and piping jq's178+ output elsewhere).179+180+ * `--sort-keys` / `-S`:181+182+ Output the fields of each object with the keys in sorted order.183+184+ * `--raw-output` / `-r`:185+186+ With this option, if the filter's result is a string then it187+ will be written directly to standard output rather than being188+ formatted as a JSON string with quotes. This can be useful for189+ making jq filters talk to non-JSON-based systems.190+191+ * `--join-output` / `-j`:192+193+ Like `-r` but jq won't print a newline after each output.194+195+ * `-f filename` / `--from-file filename`:196+197+ Read filter from the file rather than from a command line, like198+ awk's -f option. You can also use '#' to make comments.199+200+ * `-Ldirectory` / `-L directory`:201+202+ Prepend `directory` to the search list for modules. If this203+ option is used then no builtin search list is used. See the204+ section on modules below.205+206+ * `-e` / `--exit-status`:207+208+ Sets the exit status of jq to 0 if the last output values was209+ neither `false` nor `null`, 1 if the last output value was210+ either `false` or `null`, or 4 if no valid result was ever211+ produced. Normally jq exits with 2 if there was any usage212+ problem or system error, 3 if there was a jq program compile213+ error, or 0 if the jq program ran.214+215+ Another way to set the exit status is with the `halt_error`216+ builtin function.217+218+ * `--arg name value`:219+220+ This option passes a value to the jq program as a predefined221+ variable. If you run jq with `--arg foo bar`, then `$foo` is222+ available in the program and has the value `"bar"`. Note that223+ `value` will be treated as a string, so `--arg foo 123` will224+ bind `$foo` to `"123"`.225+226+ Named arguments are also available to the jq program as227+ `$ARGS.named`.228+229+ * `--argjson name JSON-text`:230+231+ This option passes a JSON-encoded value to the jq program as a232+ predefined variable. If you run jq with `--argjson foo 123`, then233+ `$foo` is available in the program and has the value `123`.234+235+ * `--slurpfile variable-name filename`:236+237+ This option reads all the JSON texts in the named file and binds238+ an array of the parsed JSON values to the given global variable.239+ If you run jq with `--slurpfile foo bar`, then `$foo` is available240+ in the program and has an array whose elements correspond to the241+ texts in the file named `bar`.242+243+ * `--rawfile variable-name filename`:244+245+ This option reads in the named file and binds its contents to the given246+ global variable. If you run jq with `--rawfile foo bar`, then `$foo` is247+ available in the program and has a string whose contents are to the texs248+ in the file named `bar`.249+250+ * `--argfile variable-name filename`:251+252+ Do not use. Use `--slurpfile` instead.253+254+ (This option is like `--slurpfile`, but when the file has just255+ one text, then that is used, else an array of texts is used as256+ in `--slurpfile`.)257+258+ * `--args`:259+260+ Remaining arguments are positional string arguments. These are261+ available to the jq program as `$ARGS.positional[]`.262+263+ * `--jsonargs`:264+265+ Remaining arguments are positional JSON text arguments. These266+ are available to the jq program as `$ARGS.positional[]`.267+268+ * `--run-tests [filename]`:269+270+ Runs the tests in the given file or standard input. This must271+ be the last option given and does not honor all preceding272+ options. The input consists of comment lines, empty lines, and273+ program lines followed by one input line, as many lines of274+ output as are expected (one per output), and a terminating empty275+ line. Compilation failure tests start with a line containing276+ only "%%FAIL", then a line containing the program to compile,277+ then a line containing an error message to compare to the278+ actual.279+280+ Be warned that this option can change backwards-incompatibly.281+282+ - title: Basic filters283+ entries:284+ - title: "Identity: `.`"285+ body: |286+287+ The absolute simplest filter is `.` . This is a filter that288+ takes its input and produces it unchanged as output. That is,289+ this is the identity operator.290+291+ Since jq by default pretty-prints all output, this trivial292+ program can be a useful way of formatting JSON output from,293+ say, `curl`.294+295+ examples:296+ - program: '.'297+ input: '"Hello, world!"'298+ output: ['"Hello, world!"']299+300+ - title: "Object Identifier-Index: `.foo`, `.foo.bar`"301+ body: |302+303+ The simplest *useful* filter is `.foo`. When given a304+ JSON object (aka dictionary or hash) as input, it produces305+ the value at the key "foo", or null if there's none present.306+307+ A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.308+309+ This syntax only works for simple, identifier-like keys, that310+ is, keys that are all made of alphanumeric characters and311+ underscore, and which do not start with a digit.312+313+ If the key contains special characters, you need to surround314+ it with double quotes like this: `."foo$"`, or else `.["foo$"]`.315+316+ For example `.["foo::bar"]` and `.["foo.bar"]` work while317+ `.foo::bar` does not, and `.foo.bar` means `.["foo"].["bar"]`.318+319+ examples:320+ - program: '.foo'321+ input: '{"foo": 42, "bar": "less interesting data"}'322+ output: [42]323+ - program: '.foo'324+ input: '{"notfoo": true, "alsonotfoo": false}'325+ output: ['null']326+ - program: '.["foo"]'327+ input: '{"foo": 42}'328+ output: [42]329+330+ - title: "Optional Object Identifier-Index: `.foo?`"331+ body: |332+333+ Just like `.foo`, but does not output even an error when `.`334+ is not an array or an object.335+336+ examples:337+ - program: '.foo?'338+ input: '{"foo": 42, "bar": "less interesting data"}'339+ output: [42]340+ - program: '.foo?'341+ input: '{"notfoo": true, "alsonotfoo": false}'342+ output: ['null']343+ - program: '.["foo"]?'344+ input: '{"foo": 42}'345+ output: [42]346+ - program: '[.foo?]'347+ input: '[1,2]'348+ output: ['[]']349+350+ - title: "Generic Object Index: `.[<string>]`"351+ body: |352+353+ You can also look up fields of an object using syntax like354+ `.["foo"]` (.foo above is a shorthand version of this, but355+ only for identifier-like strings).356+357+ - title: "Array Index: `.[2]`"358+ body: |359+360+ When the index value is an integer, `.[<value>]` can index361+ arrays. Arrays are zero-based, so `.[2]` returns the third362+ element.363+364+ Negative indices are allowed, with -1 referring to the last365+ element, -2 referring to the next to last element, and so on.366+367+ examples:368+ - program: '.[0]'369+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'370+ output: ['{"name":"JSON", "good":true}']371+372+ - program: '.[2]'373+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'374+ output: ['null']375+376+ - program: '.[-2]'377+ input: '[1,2,3]'378+ output: ['2']379+380+ - title: "Array/String Slice: `.[10:15]`"381+ body: |382+383+ The `.[10:15]` syntax can be used to return a subarray of an384+ array or substring of a string. The array returned by385+ `.[10:15]` will be of length 5, containing the elements from386+ index 10 (inclusive) to index 15 (exclusive). Either index may387+ be negative (in which case it counts backwards from the end of388+ the array), or omitted (in which case it refers to the start389+ or end of the array).390+391+ examples:392+ - program: '.[2:4]'393+ input: '["a","b","c","d","e"]'394+ output: ['["c", "d"]']395+396+ - program: '.[2:4]'397+ input: '"abcdefghi"'398+ output: ['"cd"']399+400+ - program: '.[:3]'401+ input: '["a","b","c","d","e"]'402+ output: ['["a", "b", "c"]']403+404+ - program: '.[-2:]'405+ input: '["a","b","c","d","e"]'406+ output: ['["d", "e"]']407+408+ - title: "Array/Object Value Iterator: `.[]`"409+ body: |410+411+ If you use the `.[index]` syntax, but omit the index412+ entirely, it will return *all* of the elements of an413+ array. Running `.[]` with the input `[1,2,3]` will produce the414+ numbers as three separate results, rather than as a single415+ array.416+417+ You can also use this on an object, and it will return all418+ the values of the object.419+420+ examples:421+ - program: '.[]'422+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'423+ output:424+ - '{"name":"JSON", "good":true}'425+ - '{"name":"XML", "good":false}'426+427+ - program: '.[]'428+ input: '[]'429+ output: []430+431+ - program: '.[]'432+ input: '{"a": 1, "b": 1}'433+ output: ['1', '1']434+435+ - title: "`.[]?`"436+ body: |437+438+ Like `.[]`, but no errors will be output if . is not an array439+ or object.440+441+ - title: "Comma: `,`"442+ body: |443+444+ If two filters are separated by a comma, then the445+ same input will be fed into both and the two filters' output446+ value streams will be concatenated in order: first, all of the447+ outputs produced by the left expression, and then all of the448+ outputs produced by the right. For instance, filter `.foo,449+ .bar`, produces both the "foo" fields and "bar" fields as450+ separate outputs.451+452+ examples:453+ - program: '.foo, .bar'454+ input: '{"foo": 42, "bar": "something else", "baz": true}'455+ output: ['42', '"something else"']456+457+ - program: ".user, .projects[]"458+ input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'459+ output: ['"stedolan"', '"jq"', '"wikiflow"']460+461+ - program: '.[4,2]'462+ input: '["a","b","c","d","e"]'463+ output: ['"e"', '"c"']464+465+ - title: "Pipe: `|`"466+ body: |467+468+ The | operator combines two filters by feeding the output(s) of469+ the one on the left into the input of the one on the right. It's470+ pretty much the same as the Unix shell's pipe, if you're used to471+ that.472+473+ If the one on the left produces multiple results, the one on474+ the right will be run for each of those results. So, the475+ expression `.[] | .foo` retrieves the "foo" field of each476+ element of the input array.477+478+ Note that `.a.b.c` is the same as `.a | .b | .c`.479+480+ Note too that `.` is the input value at the particular stage481+ in a "pipeline", specifically: where the `.` expression appears.482+ Thus `.a | . | .b` is the same as `.a.b`, as the `.` in the483+ middle refers to whatever value `.a` produced.484+485+ examples:486+ - program: '.[] | .name'487+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'488+ output: ['"JSON"', '"XML"']489+490+ - title: "Parenthesis"491+ body: |492+493+ Parenthesis work as a grouping operator just as in any typical494+ programming language.495+496+ examples:497+ - program: '(. + 2) * 5'498+ input: '1'499+ output: [15]500+501+ - title: Types and Values502+ body: |503+504+ jq supports the same set of datatypes as JSON - numbers,505+ strings, booleans, arrays, objects (which in JSON-speak are506+ hashes with only string keys), and "null".507+508+ Booleans, null, strings and numbers are written the same way as509+ in javascript. Just like everything else in jq, these simple510+ values take an input and produce an output - `42` is a valid jq511+ expression that takes an input, ignores it, and returns 42512+ instead.513+514+ entries:515+ - title: "Array construction: `[]`"516+ body: |517+518+ As in JSON, `[]` is used to construct arrays, as in519+ `[1,2,3]`. The elements of the arrays can be any jq520+ expression, including a pipeline. All of the results produced521+ by all of the expressions are collected into one big array.522+ You can use it to construct an array out of a known quantity523+ of values (as in `[.foo, .bar, .baz]`) or to "collect" all the524+ results of a filter into an array (as in `[.items[].name]`)525+526+ Once you understand the "," operator, you can look at jq's array527+ syntax in a different light: the expression `[1,2,3]` is not using a528+ built-in syntax for comma-separated arrays, but is instead applying529+ the `[]` operator (collect results) to the expression 1,2,3 (which530+ produces three different results).531+532+ If you have a filter `X` that produces four results,533+ then the expression `[X]` will produce a single result, an534+ array of four elements.535+536+ examples:537+ - program: "[.user, .projects[]]"538+ input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'539+ output: ['["stedolan", "jq", "wikiflow"]']540+ - program: "[ .[] | . * 2]"541+ input: '[1, 2, 3]'542+ output: ['[2, 4, 6]']543+544+ - title: "Object Construction: `{}`"545+ body: |546+547+ Like JSON, `{}` is for constructing objects (aka548+ dictionaries or hashes), as in: `{"a": 42, "b": 17}`.549+550+ If the keys are "identifier-like", then the quotes can be left551+ off, as in `{a:42, b:17}`. Keys generated by expressions need552+ to be parenthesized, e.g., `{("a"+"b"):59}`.553+554+ The value can be any expression (although you may need to555+ wrap it in parentheses if it's a complicated one), which gets556+ applied to the {} expression's input (remember, all filters557+ have an input and an output).558+559+ {foo: .bar}560+561+ will produce the JSON object `{"foo": 42}` if given the JSON562+ object `{"bar":42, "baz":43}` as its input. You can use this563+ to select particular fields of an object: if the input is an564+ object with "user", "title", "id", and "content" fields and565+ you just want "user" and "title", you can write566+567+ {user: .user, title: .title}568+569+ Because that is so common, there's a shortcut syntax for it:570+ `{user, title}`.571+572+ If one of the expressions produces multiple results,573+ multiple dictionaries will be produced. If the input's574+575+ {"user":"stedolan","titles":["JQ Primer", "More JQ"]}576+577+ then the expression578+579+ {user, title: .titles[]}580+581+ will produce two outputs:582+583+ {"user":"stedolan", "title": "JQ Primer"}584+ {"user":"stedolan", "title": "More JQ"}585+586+ Putting parentheses around the key means it will be evaluated as an587+ expression. With the same input as above,588+589+ {(.user): .titles}590+591+ produces592+593+ {"stedolan": ["JQ Primer", "More JQ"]}594+595+ examples:596+ - program: '{user, title: .titles[]}'597+ input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'598+ output:599+ - '{"user":"stedolan", "title": "JQ Primer"}'600+ - '{"user":"stedolan", "title": "More JQ"}'601+ - program: '{(.user): .titles}'602+ input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'603+ output: ['{"stedolan": ["JQ Primer", "More JQ"]}']604+605+ - title: "Recursive Descent: `..`"606+ body: |607+608+ Recursively descends `.`, producing every value. This is the609+ same as the zero-argument `recurse` builtin (see below). This610+ is intended to resemble the XPath `//` operator. Note that611+ `..a` does not work; use `..|.a` instead. In the example612+ below we use `..|.a?` to find all the values of object keys613+ "a" in any object found "below" `.`.614+615+ This is particularly useful in conjunction with `path(EXP)`616+ (also see below) and the `?` operator.617+618+ examples:619+ - program: '..|.a?'620+ input: '[[{"a":1}]]'621+ output: ['1']622+623+ - title: Builtin operators and functions624+ body: |625+626+ Some jq operator (for instance, `+`) do different things627+ depending on the type of their arguments (arrays, numbers,628+ etc.). However, jq never does implicit type conversions. If you629+ try to add a string to an object you'll get an error message and630+ no result.631+632+ entries:633+ - title: "Addition: `+`"634+ body: |635+636+ The operator `+` takes two filters, applies them both637+ to the same input, and adds the results together. What638+ "adding" means depends on the types involved:639+640+ - **Numbers** are added by normal arithmetic.641+642+ - **Arrays** are added by being concatenated into a larger array.643+644+ - **Strings** are added by being joined into a larger string.645+646+ - **Objects** are added by merging, that is, inserting all647+ the key-value pairs from both objects into a single648+ combined object. If both objects contain a value for the649+ same key, the object on the right of the `+` wins. (For650+ recursive merge use the `*` operator.)651+652+ `null` can be added to any value, and returns the other653+ value unchanged.654+655+ examples:656+ - program: '.a + 1'657+ input: '{"a": 7}'658+ output: ['8']659+ - program: '.a + .b'660+ input: '{"a": [1,2], "b": [3,4]}'661+ output: ['[1,2,3,4]']662+ - program: '.a + null'663+ input: '{"a": 1}'664+ output: ['1']665+ - program: '.a + 1'666+ input: '{}'667+ output: ['1']668+ - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'669+ input: 'null'670+ output: ['{"a": 42, "b": 2, "c": 3}']671+672+ - title: "Subtraction: `-`"673+ body: |674+675+ As well as normal arithmetic subtraction on numbers, the `-`676+ operator can be used on arrays to remove all occurrences of677+ the second array's elements from the first array.678+679+ examples:680+ - program: '4 - .a'681+ input: '{"a":3}'682+ output: ['1']683+ - program: . - ["xml", "yaml"]684+ input: '["xml", "yaml", "json"]'685+ output: ['["json"]']686+687+ - title: "Multiplication, division, modulo: `*`, `/`, and `%`"688+ body: |689+690+ These infix operators behave as expected when given two numbers.691+ Division by zero raises an error. `x % y` computes x modulo y.692+693+ Multiplying a string by a number produces the concatenation of694+ that string that many times. `"x" * 0` produces **null**.695+696+ Dividing a string by another splits the first using the second697+ as separators.698+699+ Multiplying two objects will merge them recursively: this works700+ like addition but if both objects contain a value for the701+ same key, and the values are objects, the two are merged with702+ the same strategy.703+704+ examples:705+ - program: '10 / . * 3'706+ input: 5707+ output: [6]708+ - program: '. / ", "'709+ input: '"a, b,c,d, e"'710+ output: ['["a","b,c,d","e"]']711+ - program: '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'712+ input: 'null'713+ output: ['{"k": {"a": 0, "b": 2, "c": 3}}']714+ - program: '.[] | (1 / .)?'715+ input: '[1,0,-1]'716+ output: ['1', '-1']717+718+719+ - title: "`length`"720+ body: |721+722+ The builtin function `length` gets the length of various723+ different types of value:724+725+ - The length of a **string** is the number of Unicode726+ codepoints it contains (which will be the same as its727+ JSON-encoded length in bytes if it's pure ASCII).728+729+ - The length of an **array** is the number of elements.730+731+ - The length of an **object** is the number of key-value pairs.732+733+ - The length of **null** is zero.734+735+ examples:736+ - program: '.[] | length'737+ input: '[[1,2], "string", {"a":2}, null]'738+ output: [2, 6, 1, 0]739+740+741+ - title: "`utf8bytelength`"742+ body: |743+744+ The builtin function `utf8bytelength` outputs the number of745+ bytes used to encode a string in UTF-8.746+747+ examples:748+ - program: 'utf8bytelength'749+ input: '"\u03bc"'750+ output: [2]751+752+ - title: "`keys`, `keys_unsorted`"753+ body: |754+755+ The builtin function `keys`, when given an object, returns756+ its keys in an array.757+758+ The keys are sorted "alphabetically", by unicode codepoint759+ order. This is not an order that makes particular sense in760+ any particular language, but you can count on it being the761+ same for any two objects with the same set of keys,762+ regardless of locale settings.763+764+ When `keys` is given an array, it returns the valid indices765+ for that array: the integers from 0 to length-1.766+767+ The `keys_unsorted` function is just like `keys`, but if768+ the input is an object then the keys will not be sorted,769+ instead the keys will roughly be in insertion order.770+771+ examples:772+ - program: 'keys'773+ input: '{"abc": 1, "abcd": 2, "Foo": 3}'774+ output: ['["Foo", "abc", "abcd"]']775+ - program: 'keys'776+ input: '[42,3,35]'777+ output: ['[0,1,2]']778+779+ - title: "`has(key)`"780+ body: |781+782+ The builtin function `has` returns whether the input object783+ has the given key, or the input array has an element at the784+ given index.785+786+ `has($key)` has the same effect as checking whether `$key`787+ is a member of the array returned by `keys`, although `has`788+ will be faster.789+790+ examples:791+ - program: 'map(has("foo"))'792+ input: '[{"foo": 42}, {}]'793+ output: ['[true, false]']794+ - program: 'map(has(2))'795+ input: '[[0,1], ["a","b","c"]]'796+ output: ['[false, true]']797+798+ - title: "`in`"799+ body: |800+801+ The builtin function `in` returns whether or not the input key is in the802+ given object, or the input index corresponds to an element803+ in the given array. It is, essentially, an inversed version804+ of `has`.805+806+ examples:807+ - program: '.[] | in({"foo": 42})'808+ input: '["foo", "bar"]'809+ output: ['true', 'false']810+ - program: 'map(in([0,1]))'811+ input: '[2, 0]'812+ output: ['[false, true]']813+814+ - title: "`map(x)`, `map_values(x)`"815+ body: |816+817+ For any filter `x`, `map(x)` will run that filter for each818+ element of the input array, and return the outputs in a new819+ array. `map(.+1)` will increment each element of an array of numbers.820+821+ Similarly, `map_values(x)` will run that filter for each element,822+ but it will return an object when an object is passed.823+824+ `map(x)` is equivalent to `[.[] | x]`. In fact, this is how825+ it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`.826+827+ examples:828+ - program: 'map(.+1)'829+ input: '[1,2,3]'830+ output: ['[2,3,4]']831+832+ - program: 'map_values(.+1)'833+ input: '{"a": 1, "b": 2, "c": 3}'834+ output: ['{"a": 2, "b": 3, "c": 4}']835+836+ - title: "`path(path_expression)`"837+ body: |838+839+ Outputs array representations of the given path expression840+ in `.`. The outputs are arrays of strings (object keys)841+ and/or numbers (array indices).842+843+ Path expressions are jq expressions like `.a`, but also `.[]`.844+ There are two types of path expressions: ones that can match845+ exactly, and ones that cannot. For example, `.a.b.c` is an846+ exact match path expression, while `.a[].b` is not.847+848+ `path(exact_path_expression)` will produce the array849+ representation of the path expression even if it does not850+ exist in `.`, if `.` is `null` or an array or an object.851+852+ `path(pattern)` will produce array representations of the853+ paths matching `pattern` if the paths exist in `.`.854+855+ Note that the path expressions are not different from normal856+ expressions. The expression857+ `path(..|select(type=="boolean"))` outputs all the paths to858+ boolean values in `.`, and only those paths.859+860+ examples:861+ - program: 'path(.a[0].b)'862+ input: 'null'863+ output: ['["a",0,"b"]']864+ - program: '[path(..)]'865+ input: '{"a":[{"b":1}]}'866+ output: ['[[],["a"],["a",0],["a",0,"b"]]']867+868+ - title: "`del(path_expression)`"869+ body: |870+871+ The builtin function `del` removes a key and its corresponding872+ value from an object.873+874+ examples:875+ - program: 'del(.foo)'876+ input: '{"foo": 42, "bar": 9001, "baz": 42}'877+ output: ['{"bar": 9001, "baz": 42}']878+ - program: 'del(.[1, 2])'879+ input: '["foo", "bar", "baz"]'880+ output: ['["foo"]']881+882+ - title: "`getpath(PATHS)`"883+ body: |884+885+ The builtin function `getpath` outputs the values in `.` found886+ at each path in `PATHS`.887+888+ examples:889+ - program: 'getpath(["a","b"])'890+ input: 'null'891+ output: ['null']892+ - program: '[getpath(["a","b"], ["a","c"])]'893+ input: '{"a":{"b":0, "c":1}}'894+ output: ['[0, 1]']895+896+ - title: "`setpath(PATHS; VALUE)`"897+ body: |898+899+ The builtin function `setpath` sets the `PATHS` in `.` to `VALUE`.900+901+ examples:902+ - program: 'setpath(["a","b"]; 1)'903+ input: 'null'904+ output: ['{"a": {"b": 1}}']905+ - program: 'setpath(["a","b"]; 1)'906+ input: '{"a":{"b":0}}'907+ output: ['{"a": {"b": 1}}']908+ - program: 'setpath([0,"a"]; 1)'909+ input: 'null'910+ output: ['[{"a":1}]']911+912+ - title: "`delpaths(PATHS)`"913+ body: |914+915+ The builtin function `delpaths` sets the `PATHS` in `.`.916+ `PATHS` must be an array of paths, where each path is an array917+ of strings and numbers.918+919+ examples:920+ - program: 'delpaths([["a","b"]])'921+ input: '{"a":{"b":1},"x":{"y":2}}'922+ output: ['{"a":{},"x":{"y":2}}']923+924+ - title: "`to_entries`, `from_entries`, `with_entries`"925+ body: |926+927+ These functions convert between an object and an array of928+ key-value pairs. If `to_entries` is passed an object, then929+ for each `k: v` entry in the input, the output array930+ includes `{"key": k, "value": v}`.931+932+ `from_entries` does the opposite conversion, and933+ `with_entries(foo)` is a shorthand for `to_entries |934+ map(foo) | from_entries`, useful for doing some operation to935+ all keys and values of an object. `from_entries` accepts key, Key,936+ name, Name, value and Value as keys.937+938+ examples:939+ - program: 'to_entries'940+ input: '{"a": 1, "b": 2}'941+ output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']942+ - program: 'from_entries'943+ input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'944+ output: ['{"a": 1, "b": 2}']945+ - program: 'with_entries(.key |= "KEY_" + .)'946+ input: '{"a": 1, "b": 2}'947+ output: ['{"KEY_a": 1, "KEY_b": 2}']948+949+950+ - title: "`select(boolean_expression)`"951+ body: |952+953+ The function `select(foo)` produces its input unchanged if954+ `foo` returns true for that input, and produces no output955+ otherwise.956+957+ It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`958+ will give you `[2,3]`.959+960+ examples:961+ - program: 'map(select(. >= 2))'962+ input: '[1,5,3,0,7]'963+ output: ['[5,3,7]']964+ - program: '.[] | select(.id == "second")'965+ input: '[{"id": "first", "val": 1}, {"id": "second", "val": 2}]'966+ output: ['{"id": "second", "val": 2}']967+968+969+ - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"970+ body: |971+972+ These built-ins select only inputs that are arrays, objects,973+ iterables (arrays or objects), booleans, numbers, normal974+ numbers, finite numbers, strings, null, non-null values, and975+ non-iterables, respectively.976+977+ examples:978+ - program: '.[]|numbers'979+ input: '[[],{},1,"foo",null,true,false]'980+ output: ['1']981+982+ - title: "`empty`"983+ body: |984+985+ `empty` returns no results. None at all. Not even `null`.986+987+ It's useful on occasion. You'll know if you need it :)988+989+ examples:990+ - program: '1, empty, 2'991+ input: 'null'992+ output: [1, 2]993+ - program: '[1,2,empty,3]'994+ input: 'null'995+ output: ['[1,2,3]']996+997+ - title: "`error(message)`"998+ body: |999+1000+ Produces an error, just like `.a` applied to values other than1001+ null and objects would, but with the given message as the1002+ error's value. Errors can be caught with try/catch; see below.1003+1004+ - title: "`halt`"1005+ body: |1006+1007+ Stops the jq program with no further outputs. jq will exit1008+ with exit status `0`.1009+1010+ - title: "`halt_error`, `halt_error(exit_code)`"1011+ body: |1012+1013+ Stops the jq program with no further outputs. The input will1014+ be printed on `stderr` as raw output (i.e., strings will not1015+ have double quotes) with no decoration, not even a newline.1016+1017+ The given `exit_code` (defaulting to `5`) will be jq's exit1018+ status.1019+1020+ For example, `"Error: somthing went wrong\n"|halt_error(1)`.1021+1022+ - title: "`$__loc__`"1023+ body: |1024+1025+ Produces an object with a "file" key and a "line" key, with1026+ the filename and line number where `$__loc__` occurs, as1027+ values.1028+1029+ examples:1030+ - program: 'try error("\($__loc__)") catch .'1031+ input: 'null'1032+ output: ['"{\"file\":\"<top-level>\",\"line\":1}"']1033+1034+ - title: "`paths`, `paths(node_filter)`, `leaf_paths`"1035+ body: |1036+1037+ `paths` outputs the paths to all the elements in its input1038+ (except it does not output the empty list, representing .1039+ itself).1040+1041+ `paths(f)` outputs the paths to any values for which `f` is true.1042+ That is, `paths(numbers)` outputs the paths to all numeric1043+ values.1044+1045+ `leaf_paths` is an alias of `paths(scalars)`; `leaf_paths` is1046+ *deprecated* and will be removed in the next major release.1047+1048+ examples:1049+ - program: '[paths]'1050+ input: '[1,[[],{"a":2}]]'1051+ output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']1052+ - program: '[paths(scalars)]'1053+ input: '[1,[[],{"a":2}]]'1054+ output: ['[[0],[1,1,"a"]]']1055+1056+ - title: "`add`"1057+ body: |1058+1059+ The filter `add` takes as input an array, and produces as1060+ output the elements of the array added together. This might1061+ mean summed, concatenated or merged depending on the types1062+ of the elements of the input array - the rules are the same1063+ as those for the `+` operator (described above).1064+1065+ If the input is an empty array, `add` returns `null`.1066+1067+ examples:1068+ - program: add1069+ input: '["a","b","c"]'1070+ output: ['"abc"']1071+ - program: add1072+ input: '[1, 2, 3]'1073+ output: [6]1074+ - program: add1075+ input: '[]'1076+ output: ["null"]1077+1078+ - title: "`any`, `any(condition)`, `any(generator; condition)`"1079+ body: |1080+1081+ The filter `any` takes as input an array of boolean values,1082+ and produces `true` as output if any of the elements of1083+ the array are `true`.1084+1085+ If the input is an empty array, `any` returns `false`.1086+1087+ The `any(condition)` form applies the given condition to the1088+ elements of the input array.1089+1090+ The `any(generator; condition)` form applies the given1091+ condition to all the outputs of the given generator.1092+1093+ examples:1094+ - program: any1095+ input: '[true, false]'1096+ output: ["true"]1097+ - program: any1098+ input: '[false, false]'1099+ output: ["false"]1100+ - program: any1101+ input: '[]'1102+ output: ["false"]1103+1104+ - title: "`all`, `all(condition)`, `all(generator; condition)`"1105+ body: |1106+1107+ The filter `all` takes as input an array of boolean values,1108+ and produces `true` as output if all of the elements of1109+ the array are `true`.1110+1111+ The `all(condition)` form applies the given condition to the1112+ elements of the input array.1113+1114+ The `all(generator; condition)` form applies the given1115+ condition to all the outputs of the given generator.1116+1117+ If the input is an empty array, `all` returns `true`.1118+1119+ examples:1120+ - program: all1121+ input: '[true, false]'1122+ output: ["false"]1123+ - program: all1124+ input: '[true, true]'1125+ output: ["true"]1126+ - program: all1127+ input: '[]'1128+ output: ["true"]1129+1130+ - title: "`flatten`, `flatten(depth)`"1131+ body: |1132+1133+ The filter `flatten` takes as input an array of nested arrays,1134+ and produces a flat array in which all arrays inside the original1135+ array have been recursively replaced by their values. You can pass1136+ an argument to it to specify how many levels of nesting to flatten.1137+1138+ `flatten(2)` is like `flatten`, but going only up to two1139+ levels deep.1140+1141+ examples:1142+ - program: flatten1143+ input: '[1, [2], [[3]]]'1144+ output: ["[1, 2, 3]"]1145+ - program: flatten(1)1146+ input: '[1, [2], [[3]]]'1147+ output: ["[1, 2, [3]]"]1148+ - program: flatten1149+ input: '[[]]'1150+ output: ["[]"]1151+ - program: flatten1152+ input: '[{"foo": "bar"}, [{"foo": "baz"}]]'1153+ output: ['[{"foo": "bar"}, {"foo": "baz"}]']1154+1155+ - title: "`range(upto)`, `range(from;upto)` `range(from;upto;by)`"1156+ body: |1157+1158+ The `range` function produces a range of numbers. `range(4;10)`1159+ produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers1160+ are produced as separate outputs. Use `[range(4;10)]` to get a range as1161+ an array.1162+1163+ The one argument form generates numbers from 0 to the given1164+ number, with an increment of 1.1165+1166+ The two argument form generates numbers from `from` to `upto`1167+ with an increment of 1.1168+1169+ The three argument form generates numbers `from` to `upto`1170+ with an increment of `by`.1171+1172+ examples:1173+ - program: 'range(2;4)'1174+ input: 'null'1175+ output: ['2', '3']1176+ - program: '[range(2;4)]'1177+ input: 'null'1178+ output: ['[2,3]']1179+ - program: '[range(4)]'1180+ input: 'null'1181+ output: ['[0,1,2,3]']1182+ - program: '[range(0;10;3)]'1183+ input: 'null'1184+ output: ['[0,3,6,9]']1185+ - program: '[range(0;10;-1)]'1186+ input: 'null'1187+ output: ['[]']1188+ - program: '[range(0;-5;-1)]'1189+ input: 'null'1190+ output: ['[0,-1,-2,-3,-4]']1191+1192+ - title: "`floor`"1193+ body: |1194+1195+ The `floor` function returns the floor of its numeric input.1196+1197+ examples:1198+ - program: 'floor'1199+ input: '3.14159'1200+ output: ['3']1201+1202+ - title: "`sqrt`"1203+ body: |1204+1205+ The `sqrt` function returns the square root of its numeric input.1206+1207+ examples:1208+ - program: 'sqrt'1209+ input: '9'1210+ output: ['3']1211+1212+ - title: "`tonumber`"1213+ body: |1214+1215+ The `tonumber` function parses its input as a number. It1216+ will convert correctly-formatted strings to their numeric1217+ equivalent, leave numbers alone, and give an error on all other input.1218+1219+ examples:1220+ - program: '.[] | tonumber'1221+ input: '[1, "1"]'1222+ output: [1, 1]1223+1224+ - title: "`tostring`"1225+ body: |1226+1227+ The `tostring` function prints its input as a1228+ string. Strings are left unchanged, and all other values are1229+ JSON-encoded.1230+1231+ examples:1232+ - program: '.[] | tostring'1233+ input: '[1, "1", [1]]'1234+ output: ['"1"', '"1"', '"[1]"']1235+1236+ - title: "`type`"1237+ body: |1238+1239+ The `type` function returns the type of its argument as a1240+ string, which is one of null, boolean, number, string, array1241+ or object.1242+1243+ examples:1244+ - program: 'map(type)'1245+ input: '[0, false, [], {}, null, "hello"]'1246+ output: ['["number", "boolean", "array", "object", "null", "string"]']1247+1248+ - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1249+ body: |1250+1251+ Some arithmetic operations can yield infinities and "not a1252+ number" (NaN) values. The `isinfinite` builtin returns `true`1253+ if its input is infinite. The `isnan` builtin returns `true`1254+ if its input is a NaN. The `infinite` builtin returns a1255+ positive infinite value. The `nan` builtin returns a NaN.1256+ The `isnormal` builtin returns true if its input is a normal1257+ number.1258+1259+ Note that division by zero raises an error.1260+1261+ Currently most arithmetic operations operating on infinities,1262+ NaNs, and sub-normals do not raise errors.1263+1264+ examples:1265+ - program: '.[] | (infinite * .) < 0'1266+ input: '[-1, 1]'1267+ output: ['true', 'false']1268+ - program: 'infinite, nan | type'1269+ input: 'null'1270+ output: ['"number"', '"number"']1271+1272+ - title: "`sort, sort_by(path_expression)`"1273+ body: |1274+1275+ The `sort` functions sorts its input, which must be an1276+ array. Values are sorted in the following order:1277+1278+ * `null`1279+ * `false`1280+ * `true`1281+ * numbers1282+ * strings, in alphabetical order (by unicode codepoint value)1283+ * arrays, in lexical order1284+ * objects1285+1286+ The ordering for objects is a little complex: first they're1287+ compared by comparing their sets of keys (as arrays in1288+ sorted order), and if their keys are equal then the values1289+ are compared key by key.1290+1291+ `sort` may be used to sort by a particular field of an1292+ object, or by applying any jq filter.1293+1294+ `sort_by(foo)` compares two elements by comparing the result of1295+ `foo` on each element.1296+1297+ examples:1298+ - program: 'sort'1299+ input: '[8,3,null,6]'1300+ output: ['[null,3,6,8]']1301+ - program: 'sort_by(.foo)'1302+ input: '[{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}]'1303+ output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']1304+1305+ - title: "`group_by(path_expression)`"1306+ body: |1307+1308+ `group_by(.foo)` takes as input an array, groups the1309+ elements having the same `.foo` field into separate arrays,1310+ and produces all of these arrays as elements of a larger1311+ array, sorted by the value of the `.foo` field.1312+1313+ Any jq expression, not just a field access, may be used in1314+ place of `.foo`. The sorting order is the same as described1315+ in the `sort` function above.1316+1317+ examples:1318+ - program: 'group_by(.foo)'1319+ input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'1320+ output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']1321+1322+ - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1323+ body: |1324+1325+ Find the minimum or maximum element of the input array.1326+1327+ The `min_by(path_exp)` and `max_by(path_exp)` functions allow1328+ you to specify a particular field or property to examine, e.g.1329+ `min_by(.foo)` finds the object with the smallest `foo` field.1330+1331+ examples:1332+ - program: 'min'1333+ input: '[5,4,2,7]'1334+ output: ['2']1335+ - program: 'max_by(.foo)'1336+ input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'1337+ output: ['{"foo":2, "bar":3}']1338+1339+ - title: "`unique`, `unique_by(path_exp)`"1340+ body: |1341+1342+ The `unique` function takes as input an array and produces1343+ an array of the same elements, in sorted order, with1344+ duplicates removed.1345+1346+ The `unique_by(path_exp)` function will keep only one element1347+ for each value obtained by applying the argument. Think of it1348+ as making an array by taking one element out of every group1349+ produced by `group`.1350+1351+ examples:1352+ - program: 'unique'1353+ input: '[1,2,5,3,5,3,1,3]'1354+ output: ['[1,2,3,5]']1355+ - program: 'unique_by(.foo)'1356+ input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'1357+ output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']1358+ - program: 'unique_by(length)'1359+ input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'1360+ output: ['["bacon", "chunky", "asparagus"]']1361+1362+ - title: "`reverse`"1363+ body: |1364+1365+ This function reverses an array.1366+1367+ examples:1368+ - program: 'reverse'1369+ input: '[1,2,3,4]'1370+ output: ['[4,3,2,1]']1371+1372+ - title: "`contains(element)`"1373+ body: |1374+1375+ The filter `contains(b)` will produce true if b is1376+ completely contained within the input. A string B is1377+ contained in a string A if B is a substring of A. An array B1378+ is contained in an array A if all elements in B are1379+ contained in any element in A. An object B is contained in1380+ object A if all of the values in B are contained in the1381+ value in A with the same key. All other types are assumed to1382+ be contained in each other if they are equal.1383+1384+ examples:1385+ - program: 'contains("bar")'1386+ input: '"foobar"'1387+ output: ['true']1388+ - program: 'contains(["baz", "bar"])'1389+ input: '["foobar", "foobaz", "blarp"]'1390+ output: ['true']1391+ - program: 'contains(["bazzzzz", "bar"])'1392+ input: '["foobar", "foobaz", "blarp"]'1393+ output: ['false']1394+ - program: 'contains({foo: 12, bar: [{barp: 12}]})'1395+ input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1396+ output: ['true']1397+ - program: 'contains({foo: 12, bar: [{barp: 15}]})'1398+ input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1399+ output: ['false']1400+1401+ - title: "`indices(s)`"1402+ body: |1403+1404+ Outputs an array containing the indices in `.` where `s`1405+ occurs. The input may be an array, in which case if `s` is an1406+ array then the indices output will be those where all elements1407+ in `.` match those of `s`.1408+1409+ examples:1410+ - program: 'indices(", ")'1411+ input: '"a,b, cd, efg, hijk"'1412+ output: ['[3,7,12]']1413+ - program: 'indices(1)'1414+ input: '[0,1,2,1,3,1,4]'1415+ output: ['[1,3,5]']1416+ - program: 'indices([1,2])'1417+ input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1418+ output: ['[1,8]']1419+1420+ - title: "`index(s)`, `rindex(s)`"1421+ body: |1422+1423+ Outputs the index of the first (`index`) or last (`rindex`)1424+ occurrence of `s` in the input.1425+1426+ examples:1427+ - program: 'index(", ")'1428+ input: '"a,b, cd, efg, hijk"'1429+ output: ['3']1430+ - program: 'rindex(", ")'1431+ input: '"a,b, cd, efg, hijk"'1432+ output: ['12']1433+1434+ - title: "`inside`"1435+ body: |1436+1437+ The filter `inside(b)` will produce true if the input is1438+ completely contained within b. It is, essentially, an1439+ inversed version of `contains`.1440+1441+ examples:1442+ - program: 'inside("foobar")'1443+ input: '"bar"'1444+ output: ['true']1445+ - program: 'inside(["foobar", "foobaz", "blarp"])'1446+ input: '["baz", "bar"]'1447+ output: ['true']1448+ - program: 'inside(["foobar", "foobaz", "blarp"])'1449+ input: '["bazzzzz", "bar"]'1450+ output: ['false']1451+ - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1452+ input: '{"foo": 12, "bar": [{"barp": 12}]}'1453+ output: ['true']1454+ - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1455+ input: '{"foo": 12, "bar": [{"barp": 15}]}'1456+ output: ['false']1457+1458+ - title: "`startswith(str)`"1459+ body: |1460+1461+ Outputs `true` if . starts with the given string argument.1462+1463+ examples:1464+ - program: '[.[]|startswith("foo")]'1465+ input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1466+ output: ['[false, true, false, true, false]']1467+1468+ - title: "`endswith(str)`"1469+ body: |1470+1471+ Outputs `true` if . ends with the given string argument.1472+1473+ examples:1474+ - program: '[.[]|endswith("foo")]'1475+ input: '["foobar", "barfoo"]'1476+ output: ['[false, true]']1477+1478+ - title: "`combinations`, `combinations(n)`"1479+ body: |1480+1481+ Outputs all combinations of the elements of the arrays in the1482+ input array. If given an argument `n`, it outputs all combinations1483+ of `n` repetitions of the input array.1484+1485+ examples:1486+ - program: 'combinations'1487+ input: '[[1,2], [3, 4]]'1488+ output: ['[1, 3]', '[1, 4]', '[2, 3]', '[2, 4]']1489+ - program: 'combinations(2)'1490+ input: '[0, 1]'1491+ output: ['[0, 0]', '[0, 1]', '[1, 0]', '[1, 1]']1492+1493+ - title: "`ltrimstr(str)`"1494+ body: |1495+1496+ Outputs its input with the given prefix string removed, if it1497+ starts with it.1498+1499+ examples:1500+ - program: '[.[]|ltrimstr("foo")]'1501+ input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1502+ output: ['["fo","","barfoo","bar","afoo"]']1503+1504+ - title: "`rtrimstr(str)`"1505+ body: |1506+1507+ Outputs its input with the given suffix string removed, if it1508+ ends with it.1509+1510+ examples:1511+ - program: '[.[]|rtrimstr("foo")]'1512+ input: '["fo", "foo", "barfoo", "foobar", "foob"]'1513+ output: ['["fo","","bar","foobar","foob"]']1514+1515+ - title: "`explode`"1516+ body: |1517+1518+ Converts an input string into an array of the string's1519+ codepoint numbers.1520+1521+ examples:1522+ - program: 'explode'1523+ input: '"foobar"'1524+ output: ['[102,111,111,98,97,114]']1525+1526+ - title: "`implode`"1527+ body: |1528+1529+ The inverse of explode.1530+1531+ examples:1532+ - program: 'implode'1533+ input: '[65, 66, 67]'1534+ output: ['"ABC"']1535+1536+ - title: "`split(str)`"1537+ body: |1538+1539+ Splits an input string on the separator argument.1540+1541+ examples:1542+ - program: 'split(", ")'1543+ input: '"a, b,c,d, e, "'1544+ output: ['["a","b,c,d","e",""]']1545+1546+ - title: "`join(str)`"1547+ body: |1548+1549+ Joins the array of elements given as input, using the1550+ argument as separator. It is the inverse of `split`: that is,1551+ running `split("foo") | join("foo")` over any input string1552+ returns said input string.1553+1554+ Numbers and booleans in the input are converted to strings.1555+ Null values are treated as empty strings. Arrays and objects1556+ in the input are not supported.1557+1558+ examples:1559+ - program: 'join(", ")'1560+ input: '["a","b,c,d","e"]'1561+ output: ['"a, b,c,d, e"']1562+ - program: 'join(" ")'1563+ input: '["a",1,2.3,true,null,false]'1564+ output: ['"a 1 2.3 true false"']1565+1566+ - title: "`ascii_downcase`, `ascii_upcase`"1567+ body: |1568+1569+ Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1570+ converted to the specified case.1571+1572+ example:1573+ - program: 'ascii_upcase'1574+ input: '"useful but not for é"'1575+ output: '"USEFUL BUT NOT FOR é"'1576+1577+ - title: "`while(cond; update)`"1578+ body: |1579+1580+ The `while(cond; update)` function allows you to repeatedly1581+ apply an update to `.` until `cond` is false.1582+1583+ Note that `while(cond; update)` is internally defined as a1584+ recursive jq function. Recursive calls within `while` will1585+ not consume additional memory if `update` produces at most one1586+ output for each input. See advanced topics below.1587+1588+ examples:1589+ - program: '[while(.<100; .*2)]'1590+ input: '1'1591+ output: ['[1,2,4,8,16,32,64]']1592+1593+ - title: "`until(cond; next)`"1594+ body: |1595+1596+ The `until(cond; next)` function allows you to repeatedly1597+ apply the expression `next`, initially to `.` then to its own1598+ output, until `cond` is true. For example, this can be used1599+ to implement a factorial function (see below).1600+1601+ Note that `until(cond; next)` is internally defined as a1602+ recursive jq function. Recursive calls within `until()` will1603+ not consume additional memory if `next` produces at most one1604+ output for each input. See advanced topics below.1605+1606+ examples:1607+ - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1608+ input: '4'1609+ output: ['24']1610+1611+1612+ - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`, `recurse_down`"1613+ body: |1614+1615+ The `recurse(f)` function allows you to search through a1616+ recursive structure, and extract interesting data from all1617+ levels. Suppose your input represents a filesystem:1618+1619+ {"name": "/", "children": [1620+ {"name": "/bin", "children": [1621+ {"name": "/bin/ls", "children": []},1622+ {"name": "/bin/sh", "children": []}]},1623+ {"name": "/home", "children": [1624+ {"name": "/home/stephen", "children": [1625+ {"name": "/home/stephen/jq", "children": []}]}]}]}1626+1627+ Now suppose you want to extract all of the filenames1628+ present. You need to retrieve `.name`, `.children[].name`,1629+ `.children[].children[].name`, and so on. You can do this1630+ with:1631+1632+ recurse(.children[]) | .name1633+1634+ When called without an argument, `recurse` is equivalent to1635+ `recurse(.[]?)`.1636+1637+ `recurse(f)` is identical to `recurse(f; . != null)` and can be1638+ used without concerns about recursion depth.1639+1640+ `recurse(f; condition)` is a generator which begins by1641+ emitting . and then emits in turn .|f, .|f|f, .|f|f|f, ... so long1642+ as the computed value satisfies the condition. For example,1643+ to generate all the integers, at least in principle, one1644+ could write `recurse(.+1; true)`.1645+1646+ For legacy reasons, `recurse_down` exists as an alias to1647+ calling `recurse` without arguments. This alias is considered1648+ *deprecated* and will be removed in the next major release.1649+1650+ The recursive calls in `recurse` will not consume additional1651+ memory whenever `f` produces at most a single output for each1652+ input.1653+1654+ examples:1655+ - program: 'recurse(.foo[])'1656+ input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'1657+ output:1658+ - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'1659+ - '{"foo":[]}'1660+ - '{"foo":[{"foo":[]}]}'1661+ - '{"foo":[]}'1662+1663+ - program: 'recurse'1664+ input: '{"a":0,"b":[1]}'1665+ output:1666+ - '{"a":0,"b":[1]}'1667+ - '0'1668+ - '[1]'1669+ - '1'1670+1671+ - program: 'recurse(. * .; . < 20)'1672+ input: 21673+ output:1674+ - 21675+ - 41676+ - 161677+1678+ - title: "`walk(f)`"1679+ body: |1680+1681+ The `walk(f)` function applies f recursively to every1682+ component of the input entity. When an array is1683+ encountered, f is first applied to its elements and then to1684+ the array itself; when an object is encountered, f is first1685+ applied to all the values and then to the object. In1686+ practice, f will usually test the type of its input, as1687+ illustrated in the following examples. The first example1688+ highlights the usefulness of processing the elements of an1689+ array of arrays before processing the array itself. The second1690+ example shows how all the keys of all the objects within the1691+ input can be considered for alteration.1692+1693+ examples:1694+ - program: 'walk(if type == "array" then sort else . end)'1695+ input: '[[4, 1, 7], [8, 5, 2], [3, 6, 9]]'1696+ output:1697+ - '[[1,4,7],[2,5,8],[3,6,9]]'1698+1699+ - program: 'walk( if type == "object" then with_entries( .key |= sub( "^_+"; "") ) else . end )'1700+ input: '[ { "_a": { "__b": 2 } } ]'1701+ output:1702+ - '[{"a":{"b":2}}]'1703+1704+ - title: "`$ENV`, `env`"1705+ body: |1706+1707+ `$ENV` is an object representing the environment variables as1708+ set when the jq program started.1709+1710+ `env` outputs an object representing jq's current environment.1711+1712+ At the moment there is no builtin for setting environment1713+ variables.1714+1715+ examples:1716+ - program: '$ENV.PAGER'1717+ input: 'null'1718+ output: ['"less"']1719+1720+ - program: 'env.PAGER'1721+ input: 'null'1722+ output: ['"less"']1723+1724+ - title: "`transpose`"1725+ body: |1726+1727+ Transpose a possibly jagged matrix (an array of arrays).1728+ Rows are padded with nulls so the result is always rectangular.1729+1730+ examples:1731+ - program: 'transpose'1732+ input: '[[1], [2,3]]'1733+ output: ['[[1,2],[null,3]]']1734+1735+ - title: "`bsearch(x)`"1736+ body: |1737+1738+ bsearch(x) conducts a binary search for x in the input1739+ array. If the input is sorted and contains x, then1740+ bsearch(x) will return its index in the array; otherwise, if1741+ the array is sorted, it will return (-1 - ix) where ix is an1742+ insertion point such that the array would still be sorted1743+ after the insertion of x at ix. If the array is not sorted,1744+ bsearch(x) will return an integer that is probably of no1745+ interest.1746+1747+ examples:1748+ - program: 'bsearch(0)'1749+ input: '[0,1]'1750+ output: ['0']1751+ - program: 'bsearch(0)'1752+ input: '[1,2,3]'1753+ output: ['-1']1754+ - program: 'bsearch(4) as $ix | if $ix < 0 then .[-(1+$ix)] = 4 else . end'1755+ input: '[1,2,3]'1756+ output: ['[1,2,3,4]']1757+1758+ - title: "String interpolation - `\\(foo)`"1759+ body: |1760+1761+ Inside a string, you can put an expression inside parens1762+ after a backslash. Whatever the expression returns will be1763+ interpolated into the string.1764+1765+ examples:1766+ - program: '"The input was \(.), which is one less than \(.+1)"'1767+ input: '42'1768+ output: ['"The input was 42, which is one less than 43"']1769+1770+ - title: "Convert to/from JSON"1771+ body: |1772+1773+ The `tojson` and `fromjson` builtins dump values as JSON texts1774+ or parse JSON texts into values, respectively. The tojson1775+ builtin differs from tostring in that tostring returns strings1776+ unmodified, while tojson encodes strings as JSON strings.1777+1778+ examples:1779+ - program: '[.[]|tostring]'1780+ input: '[1, "foo", ["foo"]]'1781+ output: ['["1","foo","[\"foo\"]"]']1782+ - program: '[.[]|tojson]'1783+ input: '[1, "foo", ["foo"]]'1784+ output: ['["1","\"foo\"","[\"foo\"]"]']1785+ - program: '[.[]|tojson|fromjson]'1786+ input: '[1, "foo", ["foo"]]'1787+ output: ['[1,"foo",["foo"]]']1788+1789+ - title: "Format strings and escaping"1790+ body: |1791+1792+ The `@foo` syntax is used to format and escape strings,1793+ which is useful for building URLs, documents in a language1794+ like HTML or XML, and so forth. `@foo` can be used as a1795+ filter on its own, the possible escapings are:1796+1797+ * `@text`:1798+1799+ Calls `tostring`, see that function for details.1800+1801+ * `@json`:1802+1803+ Serializes the input as JSON.1804+1805+ * `@html`:1806+1807+ Applies HTML/XML escaping, by mapping the characters1808+ `<>&'"` to their entity equivalents `<`, `>`,1809+ `&`, `'`, `"`.1810+1811+ * `@uri`:1812+1813+ Applies percent-encoding, by mapping all reserved URI1814+ characters to a `%XX` sequence.1815+1816+ * `@csv`:1817+1818+ The input must be an array, and it is rendered as CSV1819+ with double quotes for strings, and quotes escaped by1820+ repetition.1821+1822+ * `@tsv`:1823+1824+ The input must be an array, and it is rendered as TSV1825+ (tab-separated values). Each input array will be printed as1826+ a single line. Fields are separated by a single1827+ tab (ascii `0x09`). Input characters line-feed (ascii `0x0a`),1828+ carriage-return (ascii `0x0d`), tab (ascii `0x09`) and1829+ backslash (ascii `0x5c`) will be output as escape sequences1830+ `\n`, `\r`, `\t`, `\\` respectively.1831+1832+ * `@sh`:1833+1834+ The input is escaped suitable for use in a command-line1835+ for a POSIX shell. If the input is an array, the output1836+ will be a series of space-separated strings.1837+1838+ * `@base64`:1839+1840+ The input is converted to base64 as specified by RFC 4648.1841+1842+ * `@base64d`:1843+1844+ The inverse of `@base64`, input is decoded as specified by RFC 4648.1845+ Note\: If the decoded string is not UTF-8, the results are undefined.1846+1847+ This syntax can be combined with string interpolation in a1848+ useful way. You can follow a `@foo` token with a string1849+ literal. The contents of the string literal will *not* be1850+ escaped. However, all interpolations made inside that string1851+ literal will be escaped. For instance,1852+1853+ @uri "https://www.google.com/search?q=\(.search)"1854+1855+ will produce the following output for the input1856+ `{"search":"what is jq?"}`:1857+1858+ "https://www.google.com/search?q=what%20is%20jq%3F"1859+1860+ Note that the slashes, question mark, etc. in the URL are1861+ not escaped, as they were part of the string literal.1862+1863+ examples:1864+ - program: '@html'1865+ input: '"This works if x < y"'1866+ output: ['"This works if x < y"']1867+1868+# - program: '@html "<span>Anonymous said: \(.)</span>"'1869+# input: '"<script>alert(\"lol hax\");</script>"'1870+# output: ["<span>Anonymous said: <script>alert("lol hax");</script></span>"]1871+1872+ - program: '@sh "echo \(.)"'1873+ input: "\"O'Hara's Ale\""1874+ output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]1875+1876+ - program: '@base64'1877+ input: '"This is a message"'1878+ output: ['"VGhpcyBpcyBhIG1lc3NhZ2U="']1879+1880+ - program: '@base64d'1881+ input: '"VGhpcyBpcyBhIG1lc3NhZ2U="'1882+ output: ['"This is a message"']1883+1884+ - title: "Dates"1885+ body: |1886+1887+ jq provides some basic date handling functionality, with some1888+ high-level and low-level builtins. In all cases these1889+ builtins deal exclusively with time in UTC.1890+1891+ The `fromdateiso8601` builtin parses datetimes in the ISO 86011892+ format to a number of seconds since the Unix epoch1893+ (1970-01-01T00:00:00Z). The `todateiso8601` builtin does the1894+ inverse.1895+1896+ The `fromdate` builtin parses datetime strings. Currently1897+ `fromdate` only supports ISO 8601 datetime strings, but in the1898+ future it will attempt to parse datetime strings in more1899+ formats.1900+1901+ The `todate` builtin is an alias for `todateiso8601`.1902+1903+ The `now` builtin outputs the current time, in seconds since1904+ the Unix epoch.1905+1906+ Low-level jq interfaces to the C-library time functions are1907+ also provided: `strptime`, `strftime`, `strflocaltime`,1908+ `mktime`, `gmtime`, and `localtime`. Refer to your host1909+ operating system's documentation for the format strings used1910+ by `strptime` and `strftime`. Note: these are not necessarily1911+ stable interfaces in jq, particularly as to their localization1912+ functionality.1913+1914+ The `gmtime` builtin consumes a number of seconds since the1915+ Unix epoch and outputs a "broken down time" representation of1916+ Greenwhich Meridian time as an array of numbers representing1917+ (in this order): the year, the month (zero-based), the day of1918+ the month (one-based), the hour of the day, the minute of the1919+ hour, the second of the minute, the day of the week, and the1920+ day of the year -- all one-based unless otherwise stated. The1921+ day of the week number may be wrong on some systems for dates1922+ before March 1st 1900, or after December 31 2099.1923+1924+ The `localtime` builtin works like the `gmtime` builtin, but1925+ using the local timezone setting.1926+1927+ The `mktime` builtin consumes "broken down time"1928+ representations of time output by `gmtime` and `strptime`.1929+1930+ The `strptime(fmt)` builtin parses input strings matching the1931+ `fmt` argument. The output is in the "broken down time"1932+ representation consumed by `gmtime` and output by `mktime`.1933+1934+ The `strftime(fmt)` builtin formats a time (GMT) with the1935+ given format. The `strflocaltime` does the same, but using1936+ the local timezone setting.1937+1938+ The format strings for `strptime` and `strftime` are described1939+ in typical C library documentation. The format string for ISO1940+ 8601 datetime is `"%Y-%m-%dT%H:%M:%SZ"`.1941+1942+ jq may not support some or all of this date functionality on1943+ some systems. In particular, the `%u` and `%j` specifiers for1944+ `strptime(fmt)` are not supported on macOS.1945+1946+ examples:1947+ - program: 'fromdate'1948+ input: '"2015-03-05T23:51:47Z"'1949+ output: ['1425599507']1950+1951+ - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")'1952+ input: '"2015-03-05T23:51:47Z"'1953+ output: ['[2015,2,5,23,51,47,4,63]']1954+1955+ - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'1956+ input: '"2015-03-05T23:51:47Z"'1957+ output: ['1425599507']1958+1959+ - title: "SQL-Style Operators"1960+ body: |1961+1962+ jq provides a few SQL-style operators.1963+1964+ * INDEX(stream; index_expression):1965+1966+ This builtin produces an object whose keys are computed by1967+ the given index expression applied to each value from the1968+ given stream.1969+1970+ * JOIN($idx; stream; idx_expr; join_expr):1971+1972+ This builtin joins the values from the given stream to the1973+ given index. The index's keys are computed by applying the1974+ given index expression to each value from the given stream.1975+ An array of the value in the stream and the corresponding1976+ value from the index is fed to the given join expression to1977+ produce each result.1978+1979+ * JOIN($idx; stream; idx_expr):1980+1981+ Same as `JOIN($idx; stream; idx_expr; .)`.1982+1983+ * JOIN($idx; idx_expr):1984+1985+ This builtin joins the input `.` to the given index, applying1986+ the given index expression to `.` to compute the index key.1987+ The join operation is as described above.1988+1989+ * IN(s):1990+1991+ This builtin outputs `true` if `.` appears in the given1992+ stream, otherwise it outputs `false`.1993+1994+ * IN(source; s):1995+1996+ This builtin outputs `true` if any value in the source stream1997+ appears in the second stream, otherwise it outputs `false`.1998+1999+ - title: "`builtins`"2000+ body: |2001+2002+ Returns a list of all builtin functions in the format `name/arity`.2003+ Since functions with the same name but different arities are considered2004+ separate functions, `all/0`, `all/1`, and `all/2` would all be present2005+ in the list.2006+2007+ - title: Conditionals and Comparisons2008+ entries:2009+ - title: "`==`, `!=`"2010+ body: |2011+2012+ The expression 'a == b' will produce 'true' if the result of a and b2013+ are equal (that is, if they represent equivalent JSON documents) and2014+ 'false' otherwise. In particular, strings are never considered equal2015+ to numbers. If you're coming from Javascript, jq's == is like2016+ Javascript's === - considering values equal only when they have the2017+ same type as well as the same value.2018+2019+ != is "not equal", and 'a != b' returns the opposite value of 'a == b'2020+2021+ examples:2022+ - program: '.[] == 1'2023+ input: '[1, 1.0, "1", "banana"]'2024+ output: ['true', 'true', 'false', 'false']2025+2026+ - title: if-then-else2027+ body: |2028+2029+ `if A then B else C end` will act the same as `B` if `A`2030+ produces a value other than false or null, but act the same2031+ as `C` otherwise.2032+2033+ Checking for false or null is a simpler notion of2034+ "truthiness" than is found in Javascript or Python, but it2035+ means that you'll sometimes have to be more explicit about2036+ the condition you want: you can't test whether, e.g. a2037+ string is empty using `if .name then A else B end`, you'll2038+ need something more like `if (.name | length) > 0 then A else2039+ B end` instead.2040+2041+ If the condition `A` produces multiple results, then `B` is evaluated2042+ once for each result that is not false or null, and `C` is evaluated2043+ once for each false or null.2044+2045+ More cases can be added to an if using `elif A then B` syntax.2046+2047+ examples:2048+ - program: |-2049+ if . == 0 then2050+ "zero"2051+ elif . == 1 then2052+ "one"2053+ else2054+ "many"2055+ end2056+ input: 22057+ output: ['"many"']2058+2059+ - title: "`>, >=, <=, <`"2060+ body: |2061+2062+ The comparison operators `>`, `>=`, `<=`, `<` return whether2063+ their left argument is greater than, greater than or equal2064+ to, less than or equal to or less than their right argument2065+ (respectively).2066+2067+ The ordering is the same as that described for `sort`, above.2068+2069+ examples:2070+ - program: '. < 5'2071+ input: 22072+ output: ['true']2073+2074+ - title: and/or/not2075+ body: |2076+2077+ jq supports the normal Boolean operators and/or/not. They have the2078+ same standard of truth as if expressions - false and null are2079+ considered "false values", and anything else is a "true value".2080+2081+ If an operand of one of these operators produces multiple2082+ results, the operator itself will produce a result for each input.2083+2084+ `not` is in fact a builtin function rather than an operator,2085+ so it is called as a filter to which things can be piped2086+ rather than with special syntax, as in `.foo and .bar |2087+ not`.2088+2089+ These three only produce the values "true" and "false", and2090+ so are only useful for genuine Boolean operations, rather2091+ than the common Perl/Python/Ruby idiom of2092+ "value_that_may_be_null or default". If you want to use this2093+ form of "or", picking between two values rather than2094+ evaluating a condition, see the "//" operator below.2095+2096+ examples:2097+ - program: '42 and "a string"'2098+ input: 'null'2099+ output: ['true']2100+ - program: '(true, false) or false'2101+ input: 'null'2102+ output: ['true', 'false']2103+# - program: '(true, false) and (true, false)'2104+# input: 'null'2105+# output: ['true', 'false', 'false', 'false']2106+ - program: '(true, true) and (true, false)'2107+ input: 'null'2108+ output: ['true', 'false', 'true', 'false']2109+ - program: '[true, false | not]'2110+ input: 'null'2111+ output: ['[false, true]']2112+2113+ - title: "Alternative operator: `//`"2114+ body: |2115+2116+ A filter of the form `a // b` produces the same2117+ results as `a`, if `a` produces results other than `false`2118+ and `null`. Otherwise, `a // b` produces the same results as `b`.2119+2120+ This is useful for providing defaults: `.foo // 1` will2121+ evaluate to `1` if there's no `.foo` element in the2122+ input. It's similar to how `or` is sometimes used in Python2123+ (jq's `or` operator is reserved for strictly Boolean2124+ operations).2125+2126+ examples:2127+ - program: '.foo // 42'2128+ input: '{"foo": 19}'2129+ output: [19]2130+ - program: '.foo // 42'2131+ input: '{}'2132+ output: [42]2133+2134+ - title: try-catch2135+ body: |2136+2137+ Errors can be caught by using `try EXP catch EXP`. The first2138+ expression is executed, and if it fails then the second is2139+ executed with the error message. The output of the handler,2140+ if any, is output as if it had been the output of the2141+ expression to try.2142+2143+ The `try EXP` form uses `empty` as the exception handler.2144+2145+ examples:2146+ - program: 'try .a catch ". is not an object"'2147+ input: 'true'2148+ output: ['". is not an object"']2149+ - program: '[.[]|try .a]'2150+ input: '[{}, true, {"a":1}]'2151+ output: ['[null, 1]']2152+ - program: 'try error("some exception") catch .'2153+ input: 'true'2154+ output: ['"some exception"']2155+2156+ - title: Breaking out of control structures2157+ body: |2158+2159+ A convenient use of try/catch is to break out of control2160+ structures like `reduce`, `foreach`, `while`, and so on.2161+2162+ For example:2163+2164+ # Repeat an expression until it raises "break" as an2165+ # error, then stop repeating without re-raising the error.2166+ # But if the error caught is not "break" then re-raise it.2167+ try repeat(exp) catch .=="break" then empty else error;2168+2169+ jq has a syntax for named lexical labels to "break" or "go (back) to":2170+2171+ label $out | ... break $out ...2172+2173+ The `break $label_name` expression will cause the program to2174+ to act as though the nearest (to the left) `label $label_name`2175+ produced `empty`.2176+2177+ The relationship between the `break` and corresponding `label`2178+ is lexical: the label has to be "visible" from the break.2179+2180+ To break out of a `reduce`, for example:2181+2182+ label $out | reduce .[] as $item (null; if .==false then break $out else ... end)2183+2184+ The following jq program produces a syntax error:2185+2186+ break $out2187+2188+ because no label `$out` is visible.2189+2190+ - title: "Error Suppression / Optional Operator: `?`"2191+ body: |2192+2193+ The `?` operator, used as `EXP?`, is shorthand for `try EXP`.2194+2195+ examples:2196+ - program: '[.[]|(.a)?]'2197+ input: '[{}, true, {"a":1}]'2198+ output: ['[null, 1]']2199+2200+2201+ - title: Regular expressions (PCRE)2202+ body: |2203+2204+ jq uses the Oniguruma regular expression library, as do php,2205+ ruby, TextMate, Sublime Text, etc, so the description here2206+ will focus on jq specifics.2207+2208+ The jq regex filters are defined so that they can be used using2209+ one of these patterns:2210+2211+ STRING | FILTER( REGEX )2212+ STRING | FILTER( REGEX; FLAGS )2213+ STRING | FILTER( [REGEX] )2214+ STRING | FILTER( [REGEX, FLAGS] )2215+2216+ where:2217+ * STRING, REGEX and FLAGS are jq strings and subject to jq string interpolation;2218+ * REGEX, after string interpolation, should be a valid PCRE regex;2219+ * FILTER is one of `test`, `match`, or `capture`, as described below.2220+2221+ FLAGS is a string consisting of one of more of the supported flags:2222+2223+ * `g` - Global search (find all matches, not just the first)2224+ * `i` - Case insensitive search2225+ * `m` - Multi line mode ('.' will match newlines)2226+ * `n` - Ignore empty matches2227+ * `p` - Both s and m modes are enabled2228+ * `s` - Single line mode ('^' -> '\A', '$' -> '\Z')2229+ * `l` - Find longest possible matches2230+ * `x` - Extended regex format (ignore whitespace and comments)2231+2232+ To match whitespace in an x pattern use an escape such as \s, e.g.2233+2234+ * test( "a\\sb", "x" ).2235+2236+ Note that certain flags may also be specified within REGEX, e.g.2237+2238+ * jq -n '("test", "TEst", "teST", "TEST") | test( "(?i)te(?-i)st" )'2239+2240+ evaluates to: true, true, false, false.2241+2242+ entries:2243+ - title: "`test(val)`, `test(regex; flags)`"2244+ body: |2245+2246+ Like `match`, but does not return match objects, only `true` or `false`2247+ for whether or not the regex matches the input.2248+2249+ examples:2250+ - program: 'test("foo")'2251+ input: '"foo"'2252+ output: ['true']2253+ - program: '.[] | test("a b c # spaces are ignored"; "ix")'2254+ input: '["xabcd", "ABC"]'2255+ output: ['true', 'true']2256+2257+ - title: "`match(val)`, `match(regex; flags)`"2258+ body: |2259+2260+ **match** outputs an object for each match it finds. Matches have2261+ the following fields:2262+2263+ * `offset` - offset in UTF-8 codepoints from the beginning of the input2264+ * `length` - length in UTF-8 codepoints of the match2265+ * `string` - the string that it matched2266+ * `captures` - an array of objects representing capturing groups.2267+2268+ Capturing group objects have the following fields:2269+2270+ * `offset` - offset in UTF-8 codepoints from the beginning of the input2271+ * `length` - length in UTF-8 codepoints of this capturing group2272+ * `string` - the string that was captured2273+ * `name` - the name of the capturing group (or `null` if it was unnamed)2274+2275+ Capturing groups that did not match anything return an offset of -12276+2277+ examples:2278+ - program: 'match("(abc)+"; "g")'2279+ input: '"abc abc"'2280+ output:2281+ - '{"offset": 0, "length": 3, "string": "abc", "captures": [{"offset": 0, "length": 3, "string": "abc", "name": null}]}'2282+ - '{"offset": 4, "length": 3, "string": "abc", "captures": [{"offset": 4, "length": 3, "string": "abc", "name": null}]}'2283+ - program: 'match("foo")'2284+ input: '"foo bar foo"'2285+ output: ['{"offset": 0, "length": 3, "string": "foo", "captures": []}']2286+ - program: 'match(["foo", "ig"])'2287+ input: '"foo bar FOO"'2288+ output:2289+ - '{"offset": 0, "length": 3, "string": "foo", "captures": []}'2290+ - '{"offset": 8, "length": 3, "string": "FOO", "captures": []}'2291+ - program: 'match("foo (?<bar123>bar)? foo"; "ig")'2292+ input: '"foo bar foo foo foo"'2293+ output:2294+ - '{"offset": 0, "length": 11, "string": "foo bar foo", "captures": [{"offset": 4, "length": 3, "string": "bar", "name": "bar123"}]}'2295+ - '{"offset": 12, "length": 8, "string": "foo foo", "captures": [{"offset": -1, "length": 0, "string": null, "name": "bar123"}]}'2296+2297+ - program: '[ match("."; "g")] | length'2298+ input: '"abc"'2299+ output: [3]2300+2301+2302+ - title: "`capture(val)`, `capture(regex; flags)`"2303+ body: |2304+2305+ Collects the named captures in a JSON object, with the name2306+ of each capture as the key, and the matched string as the2307+ corresponding value.2308+2309+ examples:2310+ - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2311+ input: '"xyzzy-14"'2312+ output: ['{ "a": "xyzzy", "n": "14" }']2313+2314+ - title: "`scan(regex)`, `scan(regex; flags)`"2315+ body: |2316+2317+ Emit a stream of the non-overlapping substrings of the input2318+ that match the regex in accordance with the flags, if any2319+ have been specified. If there is no match, the stream is empty.2320+ To capture all the matches for each input string, use the idiom2321+ `[ expr ]`, e.g. `[ scan(regex) ]`.2322+2323+ example:2324+ - program: 'scan("c")'2325+ input: '"abcdefabc"'2326+ output: ['"c"', '"c"']2327+2328+ - program: 'scan("b")'2329+ input: ("", "")2330+ output: ['[]', '[]']2331+2332+ - title: "`split(regex; flags)`"2333+ body: |2334+2335+ For backwards compatibility, `split` splits on a string, not a regex.2336+2337+ example:2338+ - program: 'split(", *"; null)'2339+ input: '"ab,cd, ef"'2340+ output: ['"ab","cd","ef"']2341+2342+2343+ - title: "`splits(regex)`, `splits(regex; flags)`"2344+ body: |2345+2346+ These provide the same results as their `split` counterparts,2347+ but as a stream instead of an array.2348+2349+ example:2350+ - program: 'splits(", *")'2351+ input: '("ab,cd", "ef, gh")'2352+ output: ['"ab"', '"cd"', '"ef"', '"gh"']2353+2354+ - title: "`sub(regex; tostring)` `sub(regex; string; flags)`"2355+ body: |2356+2357+ Emit the string obtained by replacing the first match of regex in the2358+ input string with `tostring`, after interpolation. `tostring` should2359+ be a jq string, and may contain references to named captures. The2360+ named captures are, in effect, presented as a JSON object (as2361+ constructed by `capture`) to `tostring`, so a reference to a captured2362+ variable named "x" would take the form: "\(.x)".2363+2364+ example:2365+ - program: 'sub("^[^a-z]*(?<x>[a-z]*).*")'2366+ input: '"123abc456"'2367+ output: '"ZabcZabc"'2368+2369+2370+ - title: "`gsub(regex; string)`, `gsub(regex; string; flags)`"2371+ body: |2372+2373+ `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2374+ replaced by the string, after interpolation.2375+2376+ example:2377+ - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2378+ input: '"Abcabc"'2379+ output: '"+A-+a-"'2380+2381+2382+ - title: Advanced features2383+ body: |2384+ Variables are an absolute necessity in most programming languages, but2385+ they're relegated to an "advanced feature" in jq.2386+2387+ In most languages, variables are the only means of passing around2388+ data. If you calculate a value, and you want to use it more than once,2389+ you'll need to store it in a variable. To pass a value to another part2390+ of the program, you'll need that part of the program to define a2391+ variable (as a function parameter, object member, or whatever) in2392+ which to place the data.2393+2394+ It is also possible to define functions in jq, although this is2395+ is a feature whose biggest use is defining jq's standard library2396+ (many jq functions such as `map` and `find` are in fact written2397+ in jq).2398+2399+ jq has reduction operators, which are very powerful but a bit2400+ tricky. Again, these are mostly used internally, to define some2401+ useful bits of jq's standard library.2402+2403+ It may not be obvious at first, but jq is all about generators2404+ (yes, as often found in other languages). Some utilities are2405+ provided to help deal with generators.2406+2407+ Some minimal I/O support (besides reading JSON from standard2408+ input, and writing JSON to standard output) is available.2409+2410+ Finally, there is a module/library system.2411+2412+ entries:2413+ - title: "Variable / Symbolic Binding Operator: `... as $identifier | ...`"2414+ body: |2415+2416+ In jq, all filters have an input and an output, so manual2417+ plumbing is not necessary to pass a value from one part of a program2418+ to the next. Many expressions, for instance `a + b`, pass their input2419+ to two distinct subexpressions (here `a` and `b` are both passed the2420+ same input), so variables aren't usually necessary in order to use a2421+ value twice.2422+2423+ For instance, calculating the average value of an array of numbers2424+ requires a few variables in most languages - at least one to hold the2425+ array, perhaps one for each element or for a loop counter. In jq, it's2426+ simply `add / length` - the `add` expression is given the array and2427+ produces its sum, and the `length` expression is given the array and2428+ produces its length.2429+2430+ So, there's generally a cleaner way to solve most problems in jq than2431+ defining variables. Still, sometimes they do make things easier, so jq2432+ lets you define variables using `expression as $variable`. All2433+ variable names start with `$`. Here's a slightly uglier version of the2434+ array-averaging example:2435+2436+ length as $array_length | add / $array_length2437+2438+ We'll need a more complicated problem to find a situation where using2439+ variables actually makes our lives easier.2440+2441+2442+ Suppose we have an array of blog posts, with "author" and "title"2443+ fields, and another object which is used to map author usernames to2444+ real names. Our input looks like:2445+2446+ {"posts": [{"title": "Frist psot", "author": "anon"},2447+ {"title": "A well-written article", "author": "person1"}],2448+ "realnames": {"anon": "Anonymous Coward",2449+ "person1": "Person McPherson"}}2450+2451+ We want to produce the posts with the author field containing a real2452+ name, as in:2453+2454+ {"title": "Frist psot", "author": "Anonymous Coward"}2455+ {"title": "A well-written article", "author": "Person McPherson"}2456+2457+ We use a variable, $names, to store the realnames object, so that we2458+ can refer to it later when looking up author usernames:2459+2460+ .realnames as $names | .posts[] | {title, author: $names[.author]}2461+2462+ The expression `exp as $x | ...` means: for each value of expression2463+ `exp`, run the rest of the pipeline with the entire original input, and2464+ with `$x` set to that value. Thus `as` functions as something of a2465+ foreach loop.2466+2467+ Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2468+ `{$foo}` is a handy way of writing `{foo:$foo}`.2469+2470+ Multiple variables may be declared using a single `as` expression by2471+ providing a pattern that matches the structure of the input2472+ (this is known as "destructuring"):2473+2474+ . as {realnames: $names, posts: [$first, $second]} | ...2475+2476+ The variable declarations in array patterns (e.g., `. as2477+ [$first, $second]`) bind to the elements of the array in from2478+ the element at index zero on up, in order. When there is no2479+ value at the index for an array pattern element, `null` is2480+ bound to that variable.2481+2482+ Variables are scoped over the rest of the expression that defines2483+ them, so2484+2485+ .realnames as $names | (.posts[] | {title, author: $names[.author]})2486+2487+ will work, but2488+2489+ (.realnames as $names | .posts[]) | {title, author: $names[.author]}2490+2491+ won't.2492+2493+ For programming language theorists, it's more accurate to2494+ say that jq variables are lexically-scoped bindings. In2495+ particular there's no way to change the value of a binding;2496+ one can only setup a new binding with the same name, but which2497+ will not be visible where the old one was.2498+2499+ examples:2500+ - program: '.bar as $x | .foo | . + $x'2501+ input: '{"foo":10, "bar":200}'2502+ output: ['210']2503+ - program: '. as $i|[(.*2|. as $i| $i), $i]'2504+ input: '5'2505+ output: ['[10,5]']2506+ - program: '. as [$a, $b, {c: $c}] | $a + $b + $c'2507+ input: '[2, 3, {"c": 4, "d": 5}]'2508+ output: ['9']2509+ - program: '.[] as [$a, $b] | {a: $a, b: $b}'2510+ input: '[[0], [0, 1], [2, 1, 0]]'2511+ output: ['{"a":0,"b":null}', '{"a":0,"b":1}', '{"a":2,"b":1}']2512+2513+ - title: 'Destructuring Alternative Operator: `?//`'2514+ body: |2515+ 2516+ The destructuring alternative operator provides a concise mechanism2517+ for destructuring an input that can take one of several forms.2518+2519+ Suppose we have an API that returns a list of resources and events2520+ associated with them, and we want to get the user_id and timestamp of2521+ the first event for each resource. The API (having been clumsily2522+ converted from XML) will only wrap the events in an array if the resource2523+ has multiple events:2524+ 2525+ {"resources": [{"id": 1, "kind": "widget", "events": {"action": "create", "user_id": 1, "ts": 13}},2526+ {"id": 2, "kind": "widget", "events": [{"action": "create", "user_id": 1, "ts": 14}, {"action": "destroy", "user_id": 1, "ts": 15}]}]}2527+ 2528+ We can use the destructuring alternative operator to handle this structural change simply:2529+2530+ .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$user_id, $ts}]} | {$user_id, $kind, $id, $ts}2531+2532+ Or, if we aren't sure if the input is an array of values or an object:2533+2534+ .[] as [$id, $kind, $user_id, $ts] ?// {$id, $kind, $user_id, $ts} | ...2535+2536+ Each alternative need not define all of the same variables, but all named2537+ variables will be available to the subsequent expression. Variables not2538+ matched in the alternative that succeeded will be `null`:2539+2540+ .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}2541+2542+ Additionally, if the subsequent expression returns an error, the2543+ alternative operator will attempt to try the next binding. Errors2544+ that occur during the final alternative are passed through.2545+2546+ [[3]] | .[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end2547+2548+ examples:2549+ - program: '.[] as {$a, $b, c: {$d, $e}} ?// {$a, $b, c: [{$d, $e}]} | {$a, $b, $d, $e}'2550+ input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2551+ output: ['{"a":1,"b":2,"d":3,"e":4}', '{"a":1,"b":2,"d":3,"e":4}']2552+ - program: '.[] as {$a, $b, c: {$d}} ?// {$a, $b, c: [{$e}]} | {$a, $b, $d, $e}'2553+ input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2554+ output: ['{"a":1,"b":2,"d":3,"e":null}', '{"a":1,"b":2,"d":null,"e":4}']2555+ - program: '.[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end'2556+ input: '[[3]]'2557+ output: ['{"a":null,"b":3}']2558+2559+ - title: 'Defining Functions'2560+ body: |2561+2562+ You can give a filter a name using "def" syntax:2563+2564+ def increment: . + 1;2565+2566+ From then on, `increment` is usable as a filter just like a2567+ builtin function (in fact, this is how many of the builtins2568+ are defined). A function may take arguments:2569+2570+ def map(f): [.[] | f];2571+2572+ Arguments are passed as _filters_ (functions with no2573+ arguments), _not_ as values. The same argument may be2574+ referenced multiple times with different inputs (here `f` is2575+ run for each element of the input array). Arguments to a2576+ function work more like callbacks than like value arguments.2577+ This is important to understand. Consider:2578+2579+ def foo(f): f|f;2580+ 5|foo(.*2)2581+2582+ The result will be 20 because `f` is `.*2`, and during the2583+ first invocation of `f` `.` will be 5, and the second time it2584+ will be 10 (5 * 2), so the result will be 20. Function2585+ arguments are filters, and filters expect an input when2586+ invoked.2587+2588+ If you want the value-argument behaviour for defining simple2589+ functions, you can just use a variable:2590+2591+ def addvalue(f): f as $f | map(. + $f);2592+2593+ Or use the short-hand:2594+2595+ def addvalue($f): ...;2596+2597+ With either definition, `addvalue(.foo)` will add the current2598+ input's `.foo` field to each element of the array. Do note2599+ that calling `addvalue(.[])` will cause the `map(. + $f)` part2600+ to be evaluated once per value in the value of `.` at the call2601+ site.2602+2603+ Multiple definitions using the same function name are allowed.2604+ Each re-definition replaces the previous one for the same2605+ number of function arguments, but only for references from2606+ functions (or main program) subsequent to the re-definition.2607+ See also the section below on scoping.2608+2609+ examples:2610+ - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'2611+ input: '[[1,2],[10,20]]'2612+ output: ['[[1,2,1], [10,20,10]]']2613+ - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'2614+ input: '[[1,2],[10,20]]'2615+ output: ['[[1,2,1,2], [10,20,1,2]]']2616+2617+ - title: 'Scoping'2618+ body: |2619+2620+ There are two types of symbols in jq: value bindings (a.k.a.,2621+ "variables"), and functions. Both are scoped lexically,2622+ with expressions being able to refer only to symbols that2623+ have been defined "to the left" of them. The only exception2624+ to this rule is that functions can refer to themselves so as2625+ to be able to create recursive functions.2626+2627+ For example, in the following expression there is a binding2628+ which is visible "to the right" of it, `... | .*3 as2629+ $times_three | [. + $times_three] | ...`, but not "to the2630+ left". Consider this expression now, `... | (.*3 as2631+ $times_three | [.+ $times_three]) | ...`: here the binding2632+ `$times_three` is _not_ visible past the closing parenthesis.2633+2634+ - title: Reduce2635+ body: |2636+2637+ The `reduce` syntax in jq allows you to combine all of the2638+ results of an expression by accumulating them into a single2639+ answer. As an example, we'll pass `[3,2,1]` to this expression:2640+2641+ reduce .[] as $item (0; . + $item)2642+2643+ For each result that `.[]` produces, `. + $item` is run to2644+ accumulate a running total, starting from 0. In this2645+ example, `.[]` produces the results 3, 2, and 1, so the2646+ effect is similar to running something like this:2647+2648+ 0 | (3 as $item | . + $item) |2649+ (2 as $item | . + $item) |2650+ (1 as $item | . + $item)2651+2652+ examples:2653+ - program: 'reduce .[] as $item (0; . + $item)'2654+ input: '[10,2,5,3]'2655+ output: ['20']2656+2657+ - title: "`isempty(exp)`"2658+ body: |2659+2660+ Returns true if `exp` produces no outputs, false otherwise.2661+2662+ examples:2663+ - program: 'isempty(empty)'2664+ input: 'null'2665+ output: ['true']2666+2667+ - title: "`limit(n; exp)`"2668+ body: |2669+2670+ The `limit` function extracts up to `n` outputs from `exp`.2671+2672+ examples:2673+ - program: '[limit(3;.[])]'2674+ input: '[0,1,2,3,4,5,6,7,8,9]'2675+ output: ['[0,1,2]']2676+2677+ - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"2678+ body: |2679+2680+ The `first(expr)` and `last(expr)` functions extract the first2681+ and last values from `expr`, respectively.2682+2683+ The `nth(n; expr)` function extracts the nth value output by2684+ `expr`. This can be defined as `def nth(n; expr):2685+ last(limit(n + 1; expr));`. Note that `nth(n; expr)` doesn't2686+ support negative values of `n`.2687+2688+ examples:2689+ - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'2690+ input: '10'2691+ output: ['[0,9,5]']2692+2693+ - title: "`first`, `last`, `nth(n)`"2694+ body: |2695+2696+ The `first` and `last` functions extract the first2697+ and last values from any array at `.`.2698+2699+ The `nth(n)` function extracts the nth value of any array at `.`.2700+2701+ examples:2702+ - program: '[range(.)]|[first, last, nth(5)]'2703+ input: '10'2704+ output: ['[0,9,5]']2705+2706+ - title: "`foreach`"2707+ body: |2708+2709+ The `foreach` syntax is similar to `reduce`, but intended to2710+ allow the construction of `limit` and reducers that produce2711+ intermediate results (see example).2712+2713+ The form is `foreach EXP as $var (INIT; UPDATE; EXTRACT)`.2714+ Like `reduce`, `INIT` is evaluated once to produce a state2715+ value, then each output of `EXP` is bound to `$var`, `UPDATE`2716+ is evaluated for each output of `EXP` with the current state2717+ and with `$var` visible. Each value output by `UPDATE`2718+ replaces the previous state. Finally, `EXTRACT` is evaluated2719+ for each new state to extract an output of `foreach`.2720+2721+ This is mostly useful only for constructing `reduce`- and2722+ `limit`-like functions. But it is much more general, as it2723+ allows for partial reductions (see the example below).2724+2725+ examples:2726+ - program: '[foreach .[] as $item2727+ ([[],[]];2728+ if $item == null then [[],.[0]] else [(.[0] + [$item]),[]] end;2729+ if $item == null then .[1] else empty end)]'2730+ input: '[1,2,3,4,null,"a","b",null]'2731+ output: ['[[1,2,3,4],["a","b"]]']2732+2733+ - title: Recursion2734+ body: |2735+2736+ As described above, `recurse` uses recursion, and any jq2737+ function can be recursive. The `while` builtin is also2738+ implemented in terms of recursion.2739+2740+ Tail calls are optimized whenever the expression to the left of2741+ the recursive call outputs its last value. In practice this2742+ means that the expression to the left of the recursive call2743+ should not produce more than one output for each input.2744+2745+ For example:2746+2747+ def recurse(f): def r: ., (f | select(. != null) | r); r;2748+2749+ def while(cond; update):2750+ def _while:2751+ if cond then ., (update | _while) else empty end;2752+ _while;2753+2754+ def repeat(exp):2755+ def _repeat:2756+ exp, _repeat;2757+ _repeat;2758+2759+ - title: Generators and iterators2760+ body: |2761+2762+ Some jq operators and functions are actually generators in2763+ that they can produce zero, one, or more values for each2764+ input, just as one might expect in other programming2765+ languages that have generators. For example, `.[]`2766+ generates all the values in its input (which must be an2767+ array or an object), `range(0; 10)` generates the integers2768+ between 0 and 10, and so on.2769+2770+ Even the comma operator is a generator, generating first the2771+ values generated by the expression to the left of the comma,2772+ then for each of those, the values generate by the2773+ expression on the right of the comma.2774+2775+ The `empty` builtin is the generator that produces zero2776+ outputs. The `empty` builtin backtracks to the preceding2777+ generator expression.2778+2779+ All jq functions can be generators just by using builtin2780+ generators. It is also possible to define new generators2781+ using only recursion and the comma operator. If the2782+ recursive call(s) is(are) "in tail position" then the2783+ generator will be efficient. In the example below the2784+ recursive call by `_range` to itself is in tail position.2785+ The example shows off three advanced topics: tail recursion,2786+ generator construction, and sub-functions.2787+2788+ examples:2789+ - program: 'def range(init; upto; by):2790+ def _range:2791+ if (by > 0 and . < upto) or (by < 0 and . > upto)2792+ then ., ((.+by)|_range)2793+ else . end;2794+ if by == 0 then init else init|_range end |2795+ select((by > 0 and . < upto) or (by < 0 and . > upto));2796+ range(0; 10; 3)'2797+ input: 'null'2798+ output: ['0', '3', '6', '9']2799+ - program: 'def while(cond; update):2800+ def _while:2801+ if cond then ., (update | _while) else empty end;2802+ _while;2803+ [while(.<100; .*2)]'2804+ input: '1'2805+ output: ['[1,2,4,8,16,32,64]']2806+2807+ - title: 'Math'2808+ body: |2809+2810+ jq currently only has IEEE754 double-precision (64-bit) floating2811+ point number support.2812+2813+ Besides simple arithmetic operators such as `+`, jq also has most2814+ standard math functions from the C math library. C math functions2815+ that take a single input argument (e.g., `sin()`) are available as2816+ zero-argument jq functions. C math functions that take two input2817+ arguments (e.g., `pow()`) are available as two-argument jq2818+ functions that ignore `.`. C math functions that take three input2819+ arguments are available as three-argument jq functions that ignore2820+ `.`.2821+2822+ Availability of standard math functions depends on the2823+ availability of the corresponding math functions in your operating2824+ system and C math library. Unavailable math functions will be2825+ defined but will raise an error.2826+2827+ One-input C math functions: `acos` `acosh` `asin` `asinh` `atan`2828+ `atanh` `cbrt` `ceil` `cos` `cosh` `erf` `erfc` `exp` `exp10`2829+ `exp2` `expm1` `fabs` `floor` `gamma` `j0` `j1` `lgamma` `log`2830+ `log10` `log1p` `log2` `logb` `nearbyint` `pow10` `rint` `round`2831+ `significand` `sin` `sinh` `sqrt` `tan` `tanh` `tgamma` `trunc`2832+ `y0` `y1`.2833+2834+ Two-input C math functions: `atan2` `copysign` `drem` `fdim`2835+ `fmax` `fmin` `fmod` `frexp` `hypot` `jn` `ldexp` `modf`2836+ `nextafter` `nexttoward` `pow` `remainder` `scalb` `scalbln` `yn`.2837+2838+ Three-input C math functions: `fma`.2839+2840+ See your system's manual for more information on each of these.2841+2842+ - title: 'I/O'2843+ body: |2844+2845+ At this time jq has minimal support for I/O, mostly in the2846+ form of control over when inputs are read. Two builtins functions2847+ are provided for this, `input` and `inputs`, that read from the2848+ same sources (e.g., `stdin`, files named on the command-line) as2849+ jq itself. These two builtins, and jq's own reading actions, can2850+ be interleaved with each other.2851+2852+ Two builtins provide minimal output capabilities, `debug`, and2853+ `stderr`. (Recall that a jq program's output values are always2854+ output as JSON texts on `stdout`.) The `debug` builtin can have2855+ application-specific behavior, such as for executables that use2856+ the libjq C API but aren't the jq executable itself. The `stderr`2857+ builtin outputs its input in raw mode to stder with no additional2858+ decoration, not even a newline.2859+2860+ Most jq builtins are referentially transparent, and yield constant2861+ and repeatable value streams when applied to constant inputs.2862+ This is not true of I/O builtins.2863+2864+ entries:2865+ - title: "`input`"2866+ body: |2867+2868+ Outputs one new input.2869+2870+ - title: "`inputs`"2871+ body: |2872+2873+ Outputs all remaining inputs, one by one.2874+2875+ This is primarily useful for reductions over a program's2876+ inputs.2877+2878+ - title: "`debug`"2879+ body: |2880+2881+ Causes a debug message based on the input value to be2882+ produced. The jq executable wraps the input value with2883+ `["DEBUG:", <input-value>]` and prints that and a newline on2884+ stderr, compactly. This may change in the future.2885+2886+ - title: "`stderr`"2887+ body: |2888+2889+ Prints its input in raw and compact mode to stderr with no2890+ additional decoration, not even a newline.2891+2892+ - title: "`input_filename`"2893+ body: |2894+2895+ Returns the name of the file whose input is currently being2896+ filtered. Note that this will not work well unless jq is2897+ running in a UTF-8 locale.2898+2899+ - title: "`input_line_number`"2900+ body: |2901+2902+ Returns the line number of the input currently being filtered.2903+2904+ - title: 'Streaming'2905+ body: |2906+2907+ With the `--stream` option jq can parse input texts in a streaming2908+ fashion, allowing jq programs to start processing large JSON texts2909+ immediately rather than after the parse completes. If you have a2910+ single JSON text that is 1GB in size, streaming it will allow you2911+ to process it much more quickly.2912+2913+ However, streaming isn't easy to deal with as the jq program will2914+ have `[<path>, <leaf-value>]` (and a few other forms) as inputs.2915+2916+ Several builtins are provided to make handling streams easier.2917+2918+ The examples below use the streamed form of `[0,[1]]`, which is2919+ `[[0],0],[[1,0],1],[[1,0]],[[1]]`.2920+2921+ Streaming forms include `[<path>, <leaf-value>]` (to indicate any2922+ scalar value, empty array, or empty object), and `[<path>]` (to2923+ indicate the end of an array or object). Future versions of jq2924+ run with `--stream` and `-seq` may output additional forms such as2925+ `["error message"]` when an input text fails to parse.2926+2927+ entries:2928+ - title: "`truncate_stream(stream_expression)`"2929+ body: |2930+2931+ Consumes a number as input and truncates the corresponding2932+ number of path elements from the left of the outputs of the2933+ given streaming expression.2934+2935+ examples:2936+ - program: '[1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]'2937+ input: '1'2938+ output: ['[[[0],2],[[0]]]']2939+2940+ - title: "`fromstream(stream_expression)`"2941+ body: |2942+2943+ Outputs values corresponding to the stream expression's2944+ outputs.2945+2946+ examples:2947+ - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'2948+ input: 'null'2949+ output: ['[2]']2950+2951+ - title: "`tostream`"2952+ body: |2953+2954+ The `tostream` builtin outputs the streamed form of its input.2955+2956+ examples:2957+ - program: '. as $dot|fromstream($dot|tostream)|.==$dot'2958+ input: '[0,[1,{"a":1},{"b":2}]]'2959+ output: ['true']2960+2961+ - title: Assignment2962+ body: |2963+ Assignment works a little differently in jq than in most2964+ programming languages. jq doesn't distinguish between references2965+ to and copies of something - two objects or arrays are either2966+ equal or not equal, without any further notion of being "the2967+ same object" or "not the same object".2968+2969+ If an object has two fields which are arrays, `.foo` and `.bar`,2970+ and you append something to `.foo`, then `.bar` will not get2971+ bigger, even if you've previously set `.bar = .foo`. If you're2972+ used to programming in languages like Python, Java, Ruby,2973+ Javascript, etc. then you can think of it as though jq does a full2974+ deep copy of every object before it does the assignment (for2975+ performance it doesn't actually do that, but that's the general2976+ idea).2977+2978+ This means that it's impossible to build circular values in jq2979+ (such as an array whose first element is itself). This is quite2980+ intentional, and ensures that anything a jq program can produce2981+ can be represented in JSON.2982+2983+ All the assignment operators in jq have path expressions on the2984+ left-hand side (LHS). The right-hand side (RHS) provides values2985+ to set to the paths named by the LHS path expressions.2986+2987+ Values in jq are always immutable. Internally, assignment works2988+ by using a reduction to compute new, replacement values for `.` that2989+ have had all the desired assignments applied to `.`, then2990+ outputting the modified value. This might be made clear by this2991+ example: `{a:{b:{c:1}}} | (.a.b|=3), .`. This will output2992+ `{"a":{"b":3}}` and `{"a":{"b":{"c":1}}}` because the last2993+ sub-expression, `.`, sees the original value, not the modified2994+ value.2995+2996+ Most users will want to use modification assignment operators,2997+ such as `|=` or `+=`, rather than `=`.2998+2999+ Note that the LHS of assignment operators refers to a value in3000+ `.`. Thus `$var.foo = 1` won't work as expected (`$var.foo` is3001+ not a valid or useful path expression in `.`); use `$var | .foo =3002+ 1` instead.3003+3004+ Note too that `.a,.b=0` does not set `.a` and `.b`, but3005+ `(.a,.b)=0` sets both.3006+3007+ entries:3008+ - title: "Update-assignment: `|=`"3009+ body: |3010+ This is the "update" operator '|='. It takes a filter on the3011+ right-hand side and works out the new value for the property3012+ of `.` being assigned to by running the old value through this3013+ expression. For instance, (.foo, .bar) |= .+1 will build an3014+ object with the "foo" field set to the input's "foo" plus 1,3015+ and the "bar" field set to the input's "bar" plus 1.3016+3017+ The left-hand side can be any general path expression; see `path()`.3018+3019+ Note that the left-hand side of '|=' refers to a value in `.`.3020+ Thus `$var.foo |= . + 1` won't work as expected (`$var.foo` is3021+ not a valid or useful path expression in `.`); use `$var |3022+ .foo |= . + 1` instead.3023+3024+ If the right-hand side outputs no values (i.e., `empty`), then3025+ the left-hand side path will be deleted, as with `del(path)`.3026+3027+ If the right-hand side outputs multiple values, only the first3028+ one will be used (COMPATIBILITY NOTE: in jq 1.5 and earlier3029+ releases, it used to be that only the last one was used).3030+3031+ examples:3032+ - program: '(..|select(type=="boolean")) |= if . then 1 else 0 end'3033+ input: '[true,false,[5,true,[true,[false]],false]]'3034+ output: ['[1,0,[5,1,[1,[0]],0]]']3035+3036+ - title: "Arithmetic update-assignment: `+=`, `-=`, `*=`, `/=`, `%=`, `//=`"3037+ body: |3038+3039+ jq has a few operators of the form `a op= b`, which are all3040+ equivalent to `a |= . op b`. So, `+= 1` can be used to3041+ increment values, being the same as `|= . + 1`.3042+3043+ examples:3044+ - program: .foo += 13045+ input: '{"foo": 42}'3046+ output: ['{"foo": 43}']3047+3048+ - title: "Plain assignment: `=`"3049+ body: |3050+3051+ This is the plain assignment operator. Unlike the others, the3052+ input to the right-hand-side (RHS) is the same as the input to3053+ the left-hand-side (LHS) rather than the value at the LHS3054+ path, and all values output by the RHS will be used (as shown3055+ below).3056+3057+ If the RHS of '=' produces multiple values, then for each such3058+ value jq will set the paths on the left-hand side to the value3059+ and then it will output the modified `.`. For example,3060+ `(.a,.b)=range(2)` outputs `{"a":0,"b":0}`, then3061+ `{"a":1,"b":1}`. The "update" assignment forms (see above) do3062+ not do this.3063+3064+ This example should show the difference between '=' and '|=':3065+3066+ Provide input '{"a": {"b": 10}, "b": 20}' to the programs:3067+3068+ .a = .b3069+3070+ .a |= .b3071+3072+ The former will set the "a" field of the input to the "b"3073+ field of the input, and produce the output {"a": 20, "b": 20}.3074+ The latter will set the "a" field of the input to the "a"3075+ field's "b" field, producing {"a": 10, "b": 20}.3076+3077+ Another example of the difference between '=' and '|=':3078+3079+ null|(.a,.b)=range(3)3080+3081+ outputs '{"a":0,"b":0}', '{"a":1,"b":1}', and '{"a":2,"b":2}',3082+ while3083+3084+ null|(.a,.b)|=range(3)3085+3086+ outputs just '{"a":0,"b":0}'.3087+3088+ - title: Complex assignments3089+ body: |3090+ Lots more things are allowed on the left-hand side of a jq assignment3091+ than in most languages. We've already seen simple field accesses on3092+ the left hand side, and it's no surprise that array accesses work just3093+ as well:3094+3095+ .posts[0].title = "JQ Manual"3096+3097+ What may come as a surprise is that the expression on the left may3098+ produce multiple results, referring to different points in the input3099+ document:3100+3101+ .posts[].comments |= . + ["this is great"]3102+3103+ That example appends the string "this is great" to the "comments"3104+ array of each post in the input (where the input is an object with a3105+ field "posts" which is an array of posts).3106+3107+ When jq encounters an assignment like 'a = b', it records the "path"3108+ taken to select a part of the input document while executing a. This3109+ path is then used to find which part of the input to change while3110+ executing the assignment. Any filter may be used on the3111+ left-hand side of an equals - whichever paths it selects from the3112+ input will be where the assignment is performed.3113+3114+ This is a very powerful operation. Suppose we wanted to add a comment3115+ to blog posts, using the same "blog" input above. This time, we only3116+ want to comment on the posts written by "stedolan". We can find those3117+ posts using the "select" function described earlier:3118+3119+ .posts[] | select(.author == "stedolan")3120+3121+ The paths provided by this operation point to each of the posts that3122+ "stedolan" wrote, and we can comment on each of them in the same way3123+ that we did before:3124+3125+ (.posts[] | select(.author == "stedolan") | .comments) |=3126+ . + ["terrible."]3127+3128+ - title: Modules3129+ body: |3130+3131+ jq has a library/module system. Modules are files whose names end3132+ in `.jq`.3133+3134+ Modules imported by a program are searched for in a default search3135+ path (see below). The `import` and `include` directives allow the3136+ importer to alter this path.3137+3138+ Paths in the a search path are subject to various substitutions.3139+3140+ For paths starting with "~/", the user's home directory is3141+ substituted for "~".3142+3143+ For paths starting with "$ORIGIN/", the path of the jq executable3144+ is substituted for "$ORIGIN".3145+3146+ For paths starting with "./" or paths that are ".", the path of3147+ the including file is substituted for ".". For top-level programs3148+ given on the command-line, the current directory is used.3149+3150+ Import directives can optionally specify a search path to which3151+ the default is appended.3152+3153+ The default search path is the search path given to the `-L`3154+ command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",3155+ "$ORIGIN/../lib"]`.3156+3157+ Null and empty string path elements terminate search path3158+ processing.3159+3160+ A dependency with relative path "foo/bar" would be searched for in3161+ "foo/bar.jq" and "foo/bar/bar.jq" in the given search path. This3162+ is intended to allow modules to be placed in a directory along3163+ with, for example, version control files, README files, and so on,3164+ but also to allow for single-file modules.3165+3166+ Consecutive components with the same name are not allowed to avoid3167+ ambiguities (e.g., "foo/foo").3168+3169+ For example, with `-L$HOME/.jq` a module `foo` can be found in3170+ `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.3171+3172+ If "$HOME/.jq" is a file, it is sourced into the main program.3173+3174+ entries:3175+ - title: "`import RelativePathString as NAME [<metadata>];`"3176+ body: |3177+3178+ Imports a module found at the given path relative to a3179+ directory in a search path. A ".jq" suffix will be added to3180+ the relative path string. The module's symbols are prefixed3181+ with "NAME::".3182+3183+ The optional metadata must be a constant jq expression. It3184+ should be an object with keys like "homepage" and so on. At3185+ this time jq only uses the "search" key/value of the metadata.3186+ The metadata is also made available to users via the3187+ `modulemeta` builtin.3188+3189+ The "search" key in the metadata, if present, should have a3190+ string or array value (array of strings); this is the search3191+ path to be prefixed to the top-level search path.3192+3193+ - title: "`include RelativePathString [<metadata>];`"3194+ body: |3195+3196+ Imports a module found at the given path relative to a3197+ directory in a search path as if it were included in place. A3198+ ".jq" suffix will be added to the relative path string. The3199+ module's symbols are imported into the caller's namespace as3200+ if the module's content had been included directly.3201+3202+ The optional metadata must be a constant jq expression. It3203+ should be an object with keys like "homepage" and so on. At3204+ this time jq only uses the "search" key/value of the metadata.3205+ The metadata is also made available to users via the3206+ `modulemeta` builtin.3207+3208+ - title: "`import RelativePathString as $NAME [<metadata>];`"3209+ body: |3210+3211+ Imports a JSON file found at the given path relative to a3212+ directory in a search path. A ".json" suffix will be added to3213+ the relative path string. The file's data will be available3214+ as `$NAME::NAME`.3215+3216+ The optional metadata must be a constant jq expression. It3217+ should be an object with keys like "homepage" and so on. At3218+ this time jq only uses the "search" key/value of the metadata.3219+ The metadata is also made available to users via the3220+ `modulemeta` builtin.3221+3222+ The "search" key in the metadata, if present, should have a3223+ string or array value (array of strings); this is the search3224+ path to be prefixed to the top-level search path.3225+3226+ - title: "`module <metadata>;`"3227+ body: |3228+3229+ This directive is entirely optional. It's not required for3230+ proper operation. It serves only the purpose of providing3231+ metadata that can be read with the `modulemeta` builtin.3232+3233+ The metadata must be a constant jq expression. It should be3234+ an object with keys like "homepage". At this time jq doesn't3235+ use this metadata, but it is made available to users via the3236+ `modulemeta` builtin.3237+3238+ - title: "`modulemeta`"3239+ body: |3240+3241+ Takes a module name as input and outputs the module's metadata3242+ as an object, with the module's imports (including metadata)3243+ as an array value for the "deps" key.3244+3245+ Programs can use this to query a module's metadata, which they3246+ could then use to, for example, search for, download, and3247+ install missing dependencies.3248+3249+ - title: Colors3250+ body: |3251+3252+ To configure alternative colors just set the `JQ_COLORS`3253+ environment variable to colon-delimited list of partial terminal3254+ escape sequences like `"1;31"`, in this order:3255+3256+ - color for `null`3257+ - color for `false`3258+ - color for `true`3259+ - color for numbers3260+ - color for strings3261+ - color for arrays3262+ - color for objects3263+3264+ The default color scheme is the same as setting3265+ `"JQ_COLORS=1;30:0;39:0;39:0;39:0;32:1;39:1;39"`.3266+3267+ This is not a manual for VT100/ANSI escapes. However, each of3268+ these color specifications should consist of two numbers separated3269+ by a semi-colon, where the first number is one of these:3270+3271+ - 1 (bright)3272+ - 2 (dim)3273+ - 4 (underscore)3274+ - 5 (blink)3275+ - 7 (reverse)3276+ - 8 (hidden)3277+3278+ and the second is one of these:3279+3280+ - 30 (black)3281+ - 31 (red)3282+ - 32 (green)3283+ - 33 (yellow)3284+ - 34 (blue)3285+ - 35 (magenta)3286+ - 36 (cyan)3287+ - 37 (white)modified:docs/content/3.manual/manual.yml+3 added-2 removed
1 unmodified line2 headline: jq Manual (development version)3 4 history: |5 6- *For released versions, see [jq 1.5](/jq/manual/v1.5),7- [jq 1.4](/jq/manual/v1.4) or [jq 1.3](/jq/manual/v1.3).*6+ *For released versions, see [jq 1.6](/jq/manual/v1.6),7+ [jq 1.5](/jq/manual/v1.5), [jq 1.4](/jq/manual/v1.4)8+ or [jq 1.3](/jq/manual/v1.3).*9 10 body: |11 12 A jq program is a "filter": it takes an input, and produces an3276 unmodified linesmodified:docs/content/index/index.yml+6 added
31 unmodified lines32 [#jq](http://irc.lc/freenode/%23jq/) channel on33 [Freenode](https://webchat.freenode.net/).34 35 news:36+ - date: 1 November 201837+ body: |38+ jq 1.6 released. See installation options on the [download](/jq/download/)39+ page, and the [release notes](https://github.com/stedolan/jq/releases/tag/jq-1.6)40+ for details.41+42 - date: 15 August 201543 body: |44 45 jq 1.5 released, including new datetime, math, and regexp functions,28 unmodified lines