Update website for jq 1.5 (fix #910)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Tolnay · committed by David Tolnay · parent 461f04b · Browse files · 7 files·+2931 added−33 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+2931 added−33 removed
- other:+2931 added−33 removed
Provenance
- Commit
3608341- Tree
8486a22- Author
David Tolnay <dtolnay@gmail.com>- Committer
David Tolnay <dtolnay@gmail.com>- Parent
461f04b
7 files changed+2931 added−33 removed
modified:docs/content/2.download/default.yml+19 added-11 removed
28 unmodified lines293031323334353637383940414 unmodified lines4647484945464750515253545518 unmodified lines7475767778798081828384858610 unmodified lines979899100921011021031041051061071081091101021111121131141151161171091101181191201216 unmodified lines12812913013112512612712813213313413513613713813914010 unmodified lines28 unmodified lines Refer to the [ArchWiki](https://wiki.archlinux.org/index.php/Arch_User_Repository) for how to install from AUR.
* 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).
* jq 1.4 binaries for [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-linux-x86_64) or [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-linux-x86).4 unmodified lines [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.3/jq-linux-x86).
### OS X
* Use [Homebrew](http://brew.sh/) to install jq 1.4 with `brew install jq`. You can also install 1.5rc2 with `brew install --devel jq`. * Use [Homebrew](http://brew.sh/) to install jq 1.5 with `brew install jq`.
* jq 1.4 binaries for [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-osx-x86_64) or18 unmodified lines
* Use [Chocolatey NuGet](https://chocolatey.org/) to install jq 1.4 with `chocolatey install jq`.
* 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).
* jq 1.4 executables for [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-win64.exe) or [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-win32.exe).10 unmodified lines for SHA-1 checksums of the binaries linked above.
### From source on Linux, OS X, Cygwin, and other POSIX-like operating systems
* [Source tarball for jq 1.4](https://github.com/stedolan/jq/archive/jq-1.4.tar.gz) * [Source tarball for jq 1.5](https://github.com/stedolan/jq/archive/jq-1.5.tar.gz)
You can build it using the usual `./configure && make && sudo make install` rigmarole.
If you're interested in using the lastest development version, try:
git clone https://github.com/stedolan/jq.git cd jq autoreconf -i ./configure ./configure --disable-maintainer-mode make sudo make install
To build it from a git clone, you'll need to install a few packages first:
* [Flex](http://flex.sourceforge.net/) * [Bison](https://www.gnu.org/software/bison/) * [GCC](https://gcc.gnu.org) * [Make](https://www.gnu.org/software/make/) * [Autotools](https://www.gnu.org/software/automake/)
6 unmodified lines you may find that you need a newer version of Bison than the one provided by Apple. This can be found in [Homebrew](http://brew.sh) or [MacPorts](https://macports.org/).
Flex and Bison are used to generate the lexer and parser for jq. For jq 1.5, neither is required if you use `./configure --disable-maintainer-mode` instead of `./configure`. This flag says to use the pre-generated lexer and parser that come with the code. The `--disable-maintainer-mode` flag says to use the pre-generated lexer and parser that come with the code. To compile the lexer and parser also from source, leave out this flag. You will need to install [Flex](http://flex.sourceforge.net/) and [Bison](https://www.gnu.org/software/bison/).
#### Building the documentation
jq's documentation is compiled into static HTML using10 unmodified linesadded:docs/content/3.manual/v1.5/manual.yml+2878 added
1+---2+headline: jq Manual (development version)3+4+history: |5+6+ *The manual for the development version of jq can be found7+ [here](/jq/manual).*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 more 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+ * `--ascii-output` / `-a`:164+165+ jq usually outputs non-ASCII Unicode codepoints as UTF-8, even166+ if the input specified them as escape sequences (like167+ "\u03bc"). Using this option, you can force jq to produce pure168+ ASCII output with every non-ASCII character replaced with the169+ equivalent escape sequence.170+171+ * `--unbuffered`172+173+ Flush the output after each JSON object is printed (useful if174+ you're piping a slow data source into jq and piping jq's175+ output elsewhere).176+177+ * `--sort-keys` / `-S`:178+179+ Output the fields of each object with the keys in sorted order.180+181+ * `--raw-output` / `-r`:182+183+ With this option, if the filter's result is a string then it184+ will be written directly to standard output rather than being185+ formatted as a JSON string with quotes. This can be useful for186+ making jq filters talk to non-JSON-based systems.187+188+ * `--join-output` / `-j`:189+190+ Like `-r` but jq won't print a newline after each output.191+192+ * `-f filename` / `--from-file filename`:193+194+ Read filter from the file rather than from a command line, like195+ awk's -f option. You can also use '#' to make comments.196+197+ * `-Ldirectory` / `-L directory`:198+199+ Prepend `directory` to the search list for modules. If this200+ option is used then no builtin search list is used. See the201+ section on modules below.202+203+ * `-e` / `--exit-status`:204+205+ Sets the exit status of jq to 0 if the last output values was206+ neither `false` nor `null`, 1 if the last output value was207+ either `false` or `null`, or 4 if no valid result was ever208+ produced. Normally jq exits with 2 if there was any usage209+ problem or system error, 3 if there was a jq program compile210+ error, or 0 if the jq program ran.211+212+ * `--arg name value`:213+214+ This option passes a value to the jq program as a predefined215+ variable. If you run jq with `--arg foo bar`, then `$foo` is216+ available in the program and has the value `"bar"`. Note that217+ `value` will be treated as a string, so `--arg foo 123` will218+ bind `$foo` to `"123"`.219+220+ * `--argjson name JSON-text`:221+222+ This option passes a JSON-encoded value to the jq program as a223+ predefined variable. If you run jq with `--argjson foo 123`, then224+ `$foo` is available in the program and has the value `123`.225+226+ * `--slurpfile variable-name filename`:227+228+ This option reads all the JSON texts in the named file and binds229+ an array of the parsed JSON values to the given global variable.230+ If you run jq with `--argfile foo bar`, then `$foo` is available231+ in the program and has an array whose elements correspond to the232+ texts in the file named `bar`.233+234+ * `--argfile variable-name filename`:235+236+ Do not use. Use `--slurpfile` instead.237+238+ (This option is like `--slurpfile`, but when the file has just239+ one text, then that is used, else an array of texts is used as240+ in `--slurpfile`.)241+242+ * `--run-tests [filename]`:243+244+ Runs the tests in the given file or standard input. This must245+ be the last option given and does not honor all preceding246+ options. The input consists of comment lines, empty lines, and247+ program lines followed by one input line, as many lines of248+ output as are expected (one per output), and a terminating empty249+ line. Compilation failure tests start with a line containing250+ only "%%FAIL", then a line containing the program to compile,251+ then a line containing an error message to compare to the252+ actual.253+254+ Be warned that this option can change backwards-incompatibly.255+256+ - title: Basic filters257+ entries:258+ - title: "`.`"259+ body: |260+261+ The absolute simplest (and least interesting) filter262+ is `.`. This is a filter that takes its input and263+ produces it unchanged as output.264+265+ Since jq by default pretty-prints all output, this trivial266+ program can be a useful way of formatting JSON output from,267+ say, `curl`.268+269+ examples:270+ - program: '.'271+ input: '"Hello, world!"'272+ output: ['"Hello, world!"']273+274+ - title: "`.foo`, `.foo.bar`"275+ body: |276+277+ The simplest *useful* filter is `.foo`. When given a278+ JSON object (aka dictionary or hash) as input, it produces279+ the value at the key "foo", or null if there's none present.280+281+ If the key contains special characters, you need to surround282+ it with double quotes like this: `."foo$"`.283+284+ A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.285+286+ examples:287+ - program: '.foo'288+ input: '{"foo": 42, "bar": "less interesting data"}'289+ output: [42]290+ - program: '.foo'291+ input: '{"notfoo": true, "alsonotfoo": false}'292+ output: ['null']293+ - program: '.["foo"]'294+ input: '{"foo": 42}'295+ output: [42]296+297+ - title: "`.foo?`"298+ body: |299+300+ Just like `.foo`, but does not output even an error when `.`301+ is not an array or an object.302+303+ examples:304+ - program: '.foo?'305+ input: '{"foo": 42, "bar": "less interesting data"}'306+ output: [42]307+ - program: '.foo?'308+ input: '{"notfoo": true, "alsonotfoo": false}'309+ output: ['null']310+ - program: '.["foo"]?'311+ input: '{"foo": 42}'312+ output: [42]313+ - program: '[.foo?]'314+ input: '[1,2]'315+ output: ['[]']316+317+ - title: "`.[<string>]`, `.[2]`, `.[10:15]`"318+ body: |319+320+ You can also look up fields of an object using syntax like321+ `.["foo"]` (.foo above is a shorthand version of this). This322+ one works for arrays as well, if the key is an323+ integer. Arrays are zero-based (like javascript), so `.[2]`324+ returns the third element of the array.325+326+ The `.[10:15]` syntax can be used to return a subarray of an327+ array or substring of a string. The array returned by328+ `.[10:15]` will be of length 5, containing the elements from329+ index 10 (inclusive) to index 15 (exclusive). Either index may330+ be negative (in which case it counts backwards from the end of331+ the array), or omitted (in which case it refers to the start332+ or end of the array).333+334+ The `.[2]` syntax can be used to return the element at the335+ given index. Negative indices are allowed, with -1 referring336+ to the last element, -2 referring to the next to last element,337+ and so on.338+339+ The `.foo` syntax only works for simply keys i.e. keys that340+ are all alphanumeric characters. `.[<string>]` works with341+ keys that contain special characters such as colons and dots.342+ For example `.["foo::bar"]` and `.["foo.bar"]` work while343+ `.foo::bar` and `.foo.bar` would not.344+345+ The `?` "operator" can also be used with the slice operator,346+ as in `.[10:15]?`, which outputs values where the inputs are347+ slice-able.348+349+ examples:350+ - program: '.[0]'351+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'352+ output: ['{"name":"JSON", "good":true}']353+354+ - program: '.[2]'355+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'356+ output: ['null']357+358+ - program: '.[2:4]'359+ input: '["a","b","c","d","e"]'360+ output: ['["c", "d"]']361+362+ - program: '.[2:4]'363+ input: '"abcdefghi"'364+ output: ['"cd"']365+366+ - program: '.[:3]'367+ input: '["a","b","c","d","e"]'368+ output: ['["a", "b", "c"]']369+370+ - program: '.[-2:]'371+ input: '["a","b","c","d","e"]'372+ output: ['["d", "e"]']373+374+ - program: '.[-2]'375+ input: '[1,2,3]'376+ output: ['2']377+378+ - title: "`.[]`"379+ body: |380+381+ If you use the `.[index]` syntax, but omit the index382+ entirely, it will return *all* of the elements of an383+ array. Running `.[]` with the input `[1,2,3]` will produce the384+ numbers as three separate results, rather than as a single385+ array.386+387+ You can also use this on an object, and it will return all388+ the values of the object.389+390+ examples:391+ - program: '.[]'392+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'393+ output:394+ - '{"name":"JSON", "good":true}'395+ - '{"name":"XML", "good":false}'396+397+ - program: '.[]'398+ input: '[]'399+ output: []400+401+ - program: '.[]'402+ input: '{"a": 1, "b": 1}'403+ output: ['1', '1']404+405+ - title: "`.[]?`"406+ body: |407+408+ Like `.[]`, but no errors will be output if . is not an array409+ or object.410+411+ - title: "`,`"412+ body: |413+414+ If two filters are separated by a comma, then the415+ input will be fed into both and there will be multiple416+ outputs: first, all of the outputs produced by the left417+ expression, and then all of the outputs produced by the418+ right. For instance, filter `.foo, .bar`, produces419+ both the "foo" fields and "bar" fields as separate outputs.420+421+ examples:422+ - program: '.foo, .bar'423+ input: '{"foo": 42, "bar": "something else", "baz": true}'424+ output: ['42', '"something else"']425+426+ - program: ".user, .projects[]"427+ input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'428+ output: ['"stedolan"', '"jq"', '"wikiflow"']429+430+ - program: '.[4,2]'431+ input: '["a","b","c","d","e"]'432+ output: ['"e"', '"c"']433+434+ - title: "`|`"435+ body: |436+ The | operator combines two filters by feeding the output(s) of437+ the one on the left into the input of the one on the right. It's438+ pretty much the same as the Unix shell's pipe, if you're used to439+ that.440+441+ If the one on the left produces multiple results, the one on442+ the right will be run for each of those results. So, the443+ expression `.[] | .foo` retrieves the "foo" field of each444+ element of the input array.445+446+ examples:447+ - program: '.[] | .name'448+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'449+ output: ['"JSON"', '"XML"']450+451+ - title: Types and Values452+ body: |453+454+ jq supports the same set of datatypes as JSON - numbers,455+ strings, booleans, arrays, objects (which in JSON-speak are456+ hashes with only string keys), and "null".457+458+ Booleans, null, strings and numbers are written the same way as459+ in javascript. Just like everything else in jq, these simple460+ values take an input and produce an output - `42` is a valid jq461+ expression that takes an input, ignores it, and returns 42462+ instead.463+464+ entries:465+ - title: Array construction - `[]`466+ body: |467+468+ As in JSON, `[]` is used to construct arrays, as in469+ `[1,2,3]`. The elements of the arrays can be any jq470+ expression. All of the results produced by all of the471+ expressions are collected into one big array. You can use it472+ to construct an array out of a known quantity of values (as473+ in `[.foo, .bar, .baz]`) or to "collect" all the results of a474+ filter into an array (as in `[.items[].name]`)475+476+ Once you understand the "," operator, you can look at jq's array477+ syntax in a different light: the expression `[1,2,3]` is not using a478+ built-in syntax for comma-separated arrays, but is instead applying479+ the `[]` operator (collect results) to the expression 1,2,3 (which480+ produces three different results).481+482+ If you have a filter `X` that produces four results,483+ then the expression `[X]` will produce a single result, an484+ array of four elements.485+486+ examples:487+ - program: "[.user, .projects[]]"488+ input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'489+ output: ['["stedolan", "jq", "wikiflow"]']490+ - title: Objects - `{}`491+ body: |492+493+ Like JSON, `{}` is for constructing objects (aka494+ dictionaries or hashes), as in: `{"a": 42, "b": 17}`.495+496+ If the keys are "sensible" (all alphabetic characters), then497+ the quotes can be left off. The value can be any expression498+ (although you may need to wrap it in parentheses if it's a499+ complicated one), which gets applied to the {} expression's500+ input (remember, all filters have an input and an501+ output).502+503+ {foo: .bar}504+505+ will produce the JSON object `{"foo": 42}` if given the JSON506+ object `{"bar":42, "baz":43}`. You can use this to select507+ particular fields of an object: if the input is an object508+ with "user", "title", "id", and "content" fields and you509+ just want "user" and "title", you can write510+511+ {user: .user, title: .title}512+513+ Because that's so common, there's a shortcut syntax: `{user, title}`.514+515+ If one of the expressions produces multiple results,516+ multiple dictionaries will be produced. If the input's517+518+ {"user":"stedolan","titles":["JQ Primer", "More JQ"]}519+520+ then the expression521+522+ {user, title: .titles[]}523+524+ will produce two outputs:525+526+ {"user":"stedolan", "title": "JQ Primer"}527+ {"user":"stedolan", "title": "More JQ"}528+529+ Putting parentheses around the key means it will be evaluated as an530+ expression. With the same input as above,531+532+ {(.user): .titles}533+534+ produces535+536+ {"stedolan": ["JQ Primer", "More JQ"]}537+538+ examples:539+ - program: '{user, title: .titles[]}'540+ input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'541+ output:542+ - '{"user":"stedolan", "title": "JQ Primer"}'543+ - '{"user":"stedolan", "title": "More JQ"}'544+ - program: '{(.user): .titles}'545+ input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'546+ output: ['{"stedolan": ["JQ Primer", "More JQ"]}']547+548+ - title: Builtin operators and functions549+ body: |550+551+ Some jq operator (for instance, `+`) do different things552+ depending on the type of their arguments (arrays, numbers,553+ etc.). However, jq never does implicit type conversions. If you554+ try to add a string to an object you'll get an error message and555+ no result.556+557+ entries:558+ - title: Addition - `+`559+ body: |560+561+ The operator `+` takes two filters, applies them both562+ to the same input, and adds the results together. What563+ "adding" means depends on the types involved:564+565+ - **Numbers** are added by normal arithmetic.566+567+ - **Arrays** are added by being concatenated into a larger array.568+569+ - **Strings** are added by being joined into a larger string.570+571+ - **Objects** are added by merging, that is, inserting all572+ the key-value pairs from both objects into a single573+ combined object. If both objects contain a value for the574+ same key, the object on the right of the `+` wins. (For575+ recursive merge use the `*` operator.)576+577+ `null` can be added to any value, and returns the other578+ value unchanged.579+580+ examples:581+ - program: '.a + 1'582+ input: '{"a": 7}'583+ output: ['8']584+ - program: '.a + .b'585+ input: '{"a": [1,2], "b": [3,4]}'586+ output: ['[1,2,3,4]']587+ - program: '.a + null'588+ input: '{"a": 1}'589+ output: ['1']590+ - program: '.a + 1'591+ input: '{}'592+ output: ['1']593+ - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'594+ input: 'null'595+ output: ['{"a": 42, "b": 2, "c": 3}']596+597+ - title: Subtraction - `-`598+ body: |599+600+ As well as normal arithmetic subtraction on numbers, the `-`601+ operator can be used on arrays to remove all occurrences of602+ the second array's elements from the first array.603+604+ examples:605+ - program: '4 - .a'606+ input: '{"a":3}'607+ output: ['1']608+ - program: . - ["xml", "yaml"]609+ input: '["xml", "yaml", "json"]'610+ output: ['["json"]']611+612+ - title: Multiplication, division, modulo - `*`, `/`, and `%`613+ body: |614+615+ These infix operators behave as expected when given two numbers.616+ Division by zero raises an error. `x % y` computes x modulo y.617+618+ Multiplying a string by a number produces the concatenation of619+ that string that many times. `"x" * 0` produces **null**.620+621+ Dividing a string by another splits the first using the second622+ as separators.623+624+ Multiplying two objects will merge them recursively: this works625+ like addition but if both objects contain a value for the626+ same key, and the values are objects, the two are merged with627+ the same strategy.628+629+ examples:630+ - program: '10 / . * 3'631+ input: 5632+ output: [6]633+ - program: '. / ", "'634+ input: '"a, b,c,d, e"'635+ output: ['["a","b,c,d","e"]']636+ - program: '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'637+ input: 'null'638+ output: ['{"k": {"a": 0, "b": 2, "c": 3}}']639+ - program: '.[] | (1 / .)?'640+ input: '[1,0,-1]'641+ output: ['1', '-1']642+643+644+ - title: "`length`"645+ body: |646+647+ The builtin function `length` gets the length of various648+ different types of value:649+650+ - The length of a **string** is the number of Unicode651+ codepoints it contains (which will be the same as its652+ JSON-encoded length in bytes if it's pure ASCII).653+654+ - The length of an **array** is the number of elements.655+656+ - The length of an **object** is the number of key-value pairs.657+658+ - The length of **null** is zero.659+660+ examples:661+ - program: '.[] | length'662+ input: '[[1,2], "string", {"a":2}, null]'663+ output: [2, 6, 1, 0]664+665+ - title: "`keys`, `keys_unsorted`"666+ body: |667+668+ The builtin function `keys`, when given an object, returns669+ its keys in an array.670+671+ The keys are sorted "alphabetically", by unicode codepoint672+ order. This is not an order that makes particular sense in673+ any particular language, but you can count on it being the674+ same for any two objects with the same set of keys,675+ regardless of locale settings.676+677+ When `keys` is given an array, it returns the valid indices678+ for that array: the integers from 0 to length-1.679+680+ The `keys_unsorted` function is just like `keys`, but if681+ the input is an object then the keys will not be sorted,682+ instead the keys will roughly be in insertion order.683+684+ examples:685+ - program: 'keys'686+ input: '{"abc": 1, "abcd": 2, "Foo": 3}'687+ output: ['["Foo", "abc", "abcd"]']688+ - program: 'keys'689+ input: '[42,3,35]'690+ output: ['[0,1,2]']691+692+ - title: "`has(key)`"693+ body: |694+695+ The builtin function `has` returns whether the input object696+ has the given key, or the input array has an element at the697+ given index.698+699+ `has($key)` has the same effect as checking whether `$key`700+ is a member of the array returned by `keys`, although `has`701+ will be faster.702+703+ examples:704+ - program: 'map(has("foo"))'705+ input: '[{"foo": 42}, {}]'706+ output: ['[true, false]']707+ - program: 'map(has(2))'708+ input: '[[0,1], ["a","b","c"]]'709+ output: ['[false, true]']710+711+ - title: "`in`"712+ body: |713+714+ The builtin function `in` returns the input key is in the715+ given object, or the input index corresponds to an element716+ in the given array. It is, essentially, an inversed version717+ of `has`.718+719+ examples:720+ - program: '.[] | in({"foo": 42})'721+ input: '["foo", "bar"]'722+ output: ['true', 'false']723+ - program: 'map(in([0,1]))'724+ input: '[2, 0]'725+ output: ['[false, true]']726+727+ - title: "`path(path_expression)`"728+ body: |729+730+ Outputs array representations of the given path expression731+ in `.`. The outputs are arrays of strings (keys in objects0732+ and/or numbers (array indices.733+734+ Path expressions are jq expressions like `.a`, but also `.[]`.735+ There are two types of path expressions: ones that can match736+ exactly, and ones that cannot. For example, `.a.b.c` is an737+ exact match path expression, while `.a[].b` is not.738+739+ `path(exact_path_expression)` will produce the array740+ representation of the path expression even if it does not741+ exist in `.`, if `.` is `null` or an array or an object.742+743+ `path(pattern)` will produce array representations of the744+ paths matching `pattern` if the paths exist in `.`.745+746+ Note that the path expressions are not different from normal747+ expressions. The expression748+ `path(..|select(type=="boolean"))` outputs all the paths to749+ boolean values in `.`, and only those paths.750+751+ examples:752+ - program: 'path(.a[0].b)'753+ input: 'null'754+ output: ['["a",0,"b"]']755+ - program: '[path(..)]'756+ input: '{"a":[{"b":1}]}'757+ output: ['[[],["a"],["a",0],["a",0,"b"]]']758+759+ - title: "`del(path_expression)`"760+ body: |761+762+ The builtin function `del` removes a key and its corresponding763+ value from an object.764+765+ examples:766+ - program: 'del(.foo)'767+ input: '{"foo": 42, "bar": 9001, "baz": 42}'768+ output: ['{"bar": 9001, "baz": 42}']769+ - program: 'del(.[1, 2])'770+ input: '["foo", "bar", "baz"]'771+ output: ['["foo"]']772+773+ - title: "`to_entries`, `from_entries`, `with_entries`"774+ body: |775+776+ These functions convert between an object and an array of777+ key-value pairs. If `to_entries` is passed an object, then778+ for each `k: v` entry in the input, the output array779+ includes `{"key": k, "value": v}`.780+781+ `from_entries` does the opposite conversion, and782+ `with_entries(foo)` is a shorthand for `to_entries |783+ map(foo) | from_entries`, useful for doing some operation to784+ all keys and values of an object. `from_entries` accepts key, Key,785+ Name, value and Value as keys.786+787+ examples:788+ - program: 'to_entries'789+ input: '{"a": 1, "b": 2}'790+ output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']791+ - program: 'from_entries'792+ input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'793+ output: ['{"a": 1, "b": 2}']794+ - program: 'with_entries(.key |= "KEY_" + .)'795+ input: '{"a": 1, "b": 2}'796+ output: ['{"KEY_a": 1, "KEY_b": 2}']797+798+799+ - title: "`select(boolean_expression)`"800+ body: |801+802+ The function `select(foo)` produces its input unchanged if803+ `foo` returns true for that input, and produces no output804+ otherwise.805+806+ It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`807+ will give you `[2,3]`.808+809+ examples:810+ - program: 'map(select(. >= 2))'811+ input: '[1,5,3,0,7]'812+ output: ['[5,3,7]']813+ - program: '.[] | select(.id == "second")'814+ input: '[{"id": "first", "val": 1}, {"id": "second", "val": 2}]'815+ output: ['{"id": "second", "val": 2}']816+817+818+ - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"819+ body: |820+821+ These built-ins select only inputs that are arrays, objects,822+ iterables (arrays or objects), booleans, numbers, normal823+ numbers, finite numbers, strings, null, non-null values, and824+ non-iterables, respectively.825+826+ examples:827+ - program: '.[]|numbers'828+ input: '[[],{},1,"foo",null,true,false]'829+ output: ['1']830+831+ - title: "`empty`"832+ body: |833+834+ `empty` returns no results. None at all. Not even `null`.835+836+ It's useful on occasion. You'll know if you need it :)837+838+ examples:839+ - program: '1, empty, 2'840+ input: 'null'841+ output: [1, 2]842+ - program: '[1,2,empty,3]'843+ input: 'null'844+ output: ['[1,2,3]']845+846+ - title: "`error(message)`"847+ body: |848+849+ Produces an error, just like `.a` applied to values other than850+ null and objects would, but with the given message as the851+ error's value.852+853+ - title: "`$__loc__`"854+ body: |855+856+ Produces an object with a "file" key and a "line" key, with857+ the filename and line number where `$__loc__` occurs, as858+ values.859+860+ examples:861+ - program: 'try error("\($__loc__)") catch .'862+ input: 'null'863+ output: ['"{\"file\":\"<top-level>\",\"line\":1}"']864+865+ - title: "`map(x)`, `map_values(x)`"866+ body: |867+868+ For any filter `x`, `map(x)` will run that filter for each869+ element of the input array, and produce the outputs a new870+ array. `map(.+1)` will increment each element of an array of numbers.871+872+ Similarly, `map_values(x)` will run that filter for each element,873+ but it will return an object when an object is passed.874+875+ `map(x)` is equivalent to `[.[] | x]`. In fact, this is how876+ it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`.877+878+ examples:879+ - program: 'map(.+1)'880+ input: '[1,2,3]'881+ output: ['[2,3,4]']882+883+ - program: 'map_values(.+1)'884+ input: '{"a": 1, "b": 2, "c": 3}'885+ output: ['{"a": 2, "b": 3, "c": 4}']886+887+ - title: "`paths`, `paths(node_filter)`, `leaf_paths`"888+ body: |889+890+ `paths` outputs the paths to all the elements in its input891+ (except it does not output the empty list, representing .892+ itself).893+894+ `paths(f)` outputs the paths to any values for which `f` is true.895+ That is, `paths(numbers)` outputs the paths to all numeric896+ values.897+898+ `leaf_paths` is an alias of `paths(scalars)`; `leaf_paths` is899+ *deprecated* and will be removed in the next major release.900+901+ examples:902+ - program: '[paths]'903+ input: '[1,[[],{"a":2}]]'904+ output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']905+ - program: '[paths(scalars)]'906+ input: '[1,[[],{"a":2}]]'907+ output: ['[[0],[1,1,"a"]]']908+909+ - title: "`add`"910+ body: |911+912+ The filter `add` takes as input an array, and produces as913+ output the elements of the array added together. This might914+ mean summed, concatenated or merged depending on the types915+ of the elements of the input array - the rules are the same916+ as those for the `+` operator (described above).917+918+ If the input is an empty array, `add` returns `null`.919+920+ examples:921+ - program: add922+ input: '["a","b","c"]'923+ output: ['"abc"']924+ - program: add925+ input: '[1, 2, 3]'926+ output: [6]927+ - program: add928+ input: '[]'929+ output: ["null"]930+931+ - title: "`any`, `any(condition)`, `any(generator; condition)`"932+ body: |933+934+ The filter `any` takes as input an array of boolean values,935+ and produces `true` as output if any of the the elements of936+ the array is `true`.937+938+ If the input is an empty array, `any` returns `false`.939+940+ The `any(condition)` form applies the given condition to the941+ elements of the input array.942+943+ The `any(generator; condition)` form applies the given944+ condition to all the outputs of the given generator.945+946+ examples:947+ - program: any948+ input: '[true, false]'949+ output: ["true"]950+ - program: any951+ input: '[false, false]'952+ output: ["false"]953+ - program: any954+ input: '[]'955+ output: ["false"]956+957+ - title: "`all`, `all(condition)`, `all(generator; condition)`"958+ body: |959+960+ The filter `all` takes as input an array of boolean values,961+ and produces `true` as output if all of the the elements of962+ the array are `true`.963+964+ The `all(condition)` form applies the given condition to the965+ elements of the input array.966+967+ The `all(generator; condition)` form applies the given968+ condition to all the outputs of the given generator.969+970+ If the input is an empty array, `all` returns `true`.971+972+ examples:973+ - program: all974+ input: '[true, false]'975+ output: ["false"]976+ - program: all977+ input: '[true, true]'978+ output: ["true"]979+ - program: all980+ input: '[]'981+ output: ["true"]982+983+ - title: "\\[Requires 1.5\\] `flatten`, `flatten(depth)`"984+ body: |985+986+ The filter `flatten` takes as input an array of nested arrays,987+ and produces a flat array in which all arrays inside the original988+ array have been recursively replaced by their values. You can pass989+ an argument to it to specify how many levels of nesting to flatten.990+991+ `flatten(2)` is like `flatten`, but going only up to two992+ levels deep.993+994+ examples:995+ - program: flatten996+ input: '[1, [2], [[3]]]'997+ output: ["[1, 2, 3]"]998+ - program: flatten(1)999+ input: '[1, [2], [[3]]]'1000+ output: ["[1, 2, [3]]"]1001+ - program: flatten1002+ input: '[[]]'1003+ output: ["[]"]1004+ - program: flatten1005+ input: '[{"foo": "bar"}, [{"foo": "baz"}]]'1006+ output: ['[{"foo": "bar"}, {"foo": "baz"}]']1007+1008+ - title: "`range(upto)`, `range(from;upto)` `range(from;upto;by)`"1009+ body: |1010+1011+ The `range` function produces a range of numbers. `range(4;10)`1012+ produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers1013+ are produced as separate outputs. Use `[range(4;10)]` to get a range as1014+ an array.1015+1016+ The one argument form generates numbers from 0 to the given1017+ number, with an increment of 1.1018+1019+ The two argument form generates numbers from `from` to `upto`1020+ with an increment of 1.1021+1022+ The three argument form generates numbers `from` to `upto`1023+ with an increment of `by`.1024+1025+ examples:1026+ - program: 'range(2;4)'1027+ input: 'null'1028+ output: ['2', '3']1029+ - program: '[range(2;4)]'1030+ input: 'null'1031+ output: ['[2,3]']1032+ - program: '[range(4)]'1033+ input: 'null'1034+ output: ['[0,1,2,3]']1035+ - program: '[range(0;10;3)]'1036+ input: 'null'1037+ output: ['[0,3,6,9]']1038+ - program: '[range(0;10;-1)]'1039+ input: 'null'1040+ output: ['[]']1041+ - program: '[range(0;-5;-1)]'1042+ input: 'null'1043+ output: ['[0,-1,-2,-3,-4]']1044+1045+ - title: "`floor`"1046+ body: |1047+1048+ The `floor` function returns the floor of its numeric input.1049+1050+ examples:1051+ - program: 'floor'1052+ input: '3.14159'1053+ output: ['3']1054+1055+ - title: "`sqrt`"1056+ body: |1057+1058+ The `sqrt` function returns the square root of its numeric input.1059+1060+ examples:1061+ - program: 'sqrt'1062+ input: '9'1063+ output: ['3']1064+1065+ - title: "`tonumber`"1066+ body: |1067+1068+ The `tonumber` function parses its input as a number. It1069+ will convert correctly-formatted strings to their numeric1070+ equivalent, leave numbers alone, and give an error on all other input.1071+1072+ examples:1073+ - program: '.[] | tonumber'1074+ input: '[1, "1"]'1075+ output: [1, 1]1076+1077+ - title: "`tostring`"1078+ body: |1079+1080+ The `tostring` function prints its input as a1081+ string. Strings are left unchanged, and all other values are1082+ JSON-encoded.1083+1084+ examples:1085+ - program: '.[] | tostring'1086+ input: '[1, "1", [1]]'1087+ output: ['"1"', '"1"', '"[1]"']1088+1089+ - title: "`type`"1090+ body: |1091+1092+ The `type` function returns the type of its argument as a1093+ string, which is one of null, boolean, number, string, array1094+ or object.1095+1096+ examples:1097+ - program: 'map(type)'1098+ input: '[0, false, [], {}, null, "hello"]'1099+ output: ['["number", "boolean", "array", "object", "null", "string"]']1100+1101+ - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1102+ body: |1103+1104+ Some arithmetic operations can yield infinities and "not a1105+ number" (NaN) values. The `isinfinite` builtin returns `true`1106+ if its input is infinite. The `isnan` builtin returns `true`1107+ if its input is a NaN. The `infinite` builtin returns a1108+ positive infinite value. The `nan` builtin returns a NaN.1109+ The `isnormal` builtin returns true if its input is a normal1110+ number.1111+1112+ Note that division by zero raises an error.1113+1114+ Currently most arithmetic operations operating on infinities,1115+ NaNs, and sub-normals do not raise errors.1116+1117+ examples:1118+ - program: '.[] | (infinite * .) < 0'1119+ input: '[-1, 1]'1120+ output: ['true', 'false']1121+ - program: 'infinite, nan | type'1122+ input: 'null'1123+ output: ['"number"', '"number"']1124+1125+ - title: "`sort, sort_by(path_expression)`"1126+ body: |1127+1128+ The `sort` functions sorts its input, which must be an1129+ array. Values are sorted in the following order:1130+1131+ * `null`1132+ * `false`1133+ * `true`1134+ * numbers1135+ * strings, in alphabetical order (by unicode codepoint value)1136+ * arrays, in lexical order1137+ * objects1138+1139+ The ordering for objects is a little complex: first they're1140+ compared by comparing their sets of keys (as arrays in1141+ sorted order), and if their keys are equal then the values1142+ are compared key by key.1143+1144+ `sort` may be used to sort by a particular field of an1145+ object, or by applying any jq filter.1146+1147+ `sort_by(foo)` compares two elements by comparing the result of1148+ `foo` on each element.1149+1150+ examples:1151+ - program: 'sort'1152+ input: '[8,3,null,6]'1153+ output: ['[null,3,6,8]']1154+ - program: 'sort_by(.foo)'1155+ input: '[{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}]'1156+ output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']1157+1158+ - title: "`group_by(path_expression)`"1159+ body: |1160+1161+ `group_by(.foo)` takes as input an array, groups the1162+ elements having the same `.foo` field into separate arrays,1163+ and produces all of these arrays as elements of a larger1164+ array, sorted by the value of the `.foo` field.1165+1166+ Any jq expression, not just a field access, may be used in1167+ place of `.foo`. The sorting order is the same as described1168+ in the `sort` function above.1169+1170+ examples:1171+ - program: 'group_by(.foo)'1172+ input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'1173+ output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']1174+1175+ - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1176+ body: |1177+1178+ Find the minimum or maximum element of the input array.1179+1180+ The `min_by(path_exp)` and `max_by(path_exp)` functions allow1181+ you to specify a particular field or property to examine, e.g.1182+ `min_by(.foo)` finds the object with the smallest `foo` field.1183+1184+ examples:1185+ - program: 'min'1186+ input: '[5,4,2,7]'1187+ output: ['2']1188+ - program: 'max_by(.foo)'1189+ input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'1190+ output: ['{"foo":2, "bar":3}']1191+1192+ - title: "`unique`, `unique_by(path_exp)`"1193+ body: |1194+1195+ The `unique` function takes as input an array and produces1196+ an array of the same elements, in sorted order, with1197+ duplicates removed.1198+1199+ The `unique_by(path_exp)` function will keep only one element1200+ for each value obtained by applying the argument. Think of it1201+ as making an array by taking one element out of every group1202+ produced by `group`.1203+1204+ examples:1205+ - program: 'unique'1206+ input: '[1,2,5,3,5,3,1,3]'1207+ output: ['[1,2,3,5]']1208+ - program: 'unique_by(.foo)'1209+ input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'1210+ output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']1211+ - program: 'unique_by(length)'1212+ input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'1213+ output: ['["bacon", "chunky", "asparagus"]']1214+1215+ - title: "`reverse`"1216+ body: |1217+1218+ This function reverses an array.1219+1220+ examples:1221+ - program: 'reverse'1222+ input: '[1,2,3,4]'1223+ output: ['[4,3,2,1]']1224+1225+ - title: "`contains(element)`"1226+ body: |1227+1228+ The filter `contains(b)` will produce true if b is1229+ completely contained within the input. A string B is1230+ contained in a string A if B is a substring of A. An array B1231+ is contained in an array A if all elements in B are1232+ contained in any element in A. An object B is contained in1233+ object A if all of the values in B are contained in the1234+ value in A with the same key. All other types are assumed to1235+ be contained in each other if they are equal.1236+1237+ examples:1238+ - program: 'contains("bar")'1239+ input: '"foobar"'1240+ output: ['true']1241+ - program: 'contains(["baz", "bar"])'1242+ input: '["foobar", "foobaz", "blarp"]'1243+ output: ['true']1244+ - program: 'contains(["bazzzzz", "bar"])'1245+ input: '["foobar", "foobaz", "blarp"]'1246+ output: ['false']1247+ - program: 'contains({foo: 12, bar: [{barp: 12}]})'1248+ input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1249+ output: ['true']1250+ - program: 'contains({foo: 12, bar: [{barp: 15}]})'1251+ input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1252+ output: ['false']1253+1254+ - title: "`indices(s)`"1255+ body: |1256+1257+ Outputs an array containing the indices in `.` where `s`1258+ occurs. The input may be an array, in which case if `s` is an1259+ array then the indices output will be those where all elements1260+ in `.` match those of `s`.1261+1262+ examples:1263+ - program: 'indices(", ")'1264+ input: '"a,b, cd, efg, hijk"'1265+ output: ['[3,7,12]']1266+ - program: 'indices(1)'1267+ input: '[0,1,2,1,3,1,4]'1268+ output: ['[1,3,5]']1269+ - program: 'indices([1,2])'1270+ input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1271+ output: ['[1,8]']1272+1273+ - title: "`index(s)`, `rindex(s)`"1274+ body: |1275+1276+ Outputs the index of the first (`index`) or last (`rindex`)1277+ occurrence of `s` in the input.1278+1279+ examples:1280+ - program: 'index(", ")'1281+ input: '"a,b, cd, efg, hijk"'1282+ output: ['3']1283+ - program: 'rindex(", ")'1284+ input: '"a,b, cd, efg, hijk"'1285+ output: ['12']1286+1287+ - title: "`inside`"1288+ body: |1289+1290+ The filter `inside(b)` will produce true if the input is1291+ completely contained within b. It is, essentially, an1292+ inversed version of `contains`.1293+1294+ examples:1295+ - program: 'inside("foobar")'1296+ input: '"bar"'1297+ output: ['true']1298+ - program: 'inside(["foobar", "foobaz", "blarp"])'1299+ input: '["baz", "bar"]'1300+ output: ['true']1301+ - program: 'inside(["foobar", "foobaz", "blarp"])'1302+ input: '["bazzzzz", "bar"]'1303+ output: ['false']1304+ - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1305+ input: '{"foo": 12, "bar": [{"barp": 12}]}'1306+ output: ['true']1307+ - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1308+ input: '{"foo": 12, "bar": [{"barp": 15}]}'1309+ output: ['false']1310+1311+ - title: "`startswith(str)`"1312+ body: |1313+1314+ Outputs `true` if . starts with the given string argument.1315+1316+ examples:1317+ - program: '[.[]|startswith("foo")]'1318+ input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1319+ output: ['[false, true, false, true, false]']1320+1321+ - title: "`endswith(str)`"1322+ body: |1323+1324+ Outputs `true` if . ends with the given string argument.1325+1326+ examples:1327+ - program: '[.[]|endswith("foo")]'1328+ input: '["foobar", "barfoo"]'1329+ output: ['[false, true]']1330+1331+ - title: "`combinations`, `combinations(n)`"1332+ body: |1333+1334+ Outputs all combinations of the elements of the arrays in the1335+ input array. If given an argument `n`, it outputs all combinations1336+ of `n` repetitions of the input array.1337+1338+ examples:1339+ - program: 'combinations'1340+ input: '[[1,2], [3, 4]]'1341+ output: ['[1, 3]', '[1, 4]', '[2, 3]', '[2, 4]']1342+ - program: 'combinations(2)'1343+ input: '[0, 1]'1344+ output: ['[0, 0]', '[0, 1]', '[1, 0]', '[1, 1]']1345+1346+ - title: "`ltrimstr(str)`"1347+ body: |1348+1349+ Outputs its input with the given prefix string removed, if it1350+ starts with it.1351+1352+ examples:1353+ - program: '[.[]|ltrimstr("foo")]'1354+ input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1355+ output: ['["fo","","barfoo","bar","afoo"]']1356+1357+ - title: "`rtrimstr(str)`"1358+ body: |1359+1360+ Outputs its input with the given suffix string removed, if it1361+ ends with it.1362+1363+ examples:1364+ - program: '[.[]|rtrimstr("foo")]'1365+ input: '["fo", "foo", "barfoo", "foobar", "foob"]'1366+ output: ['["fo","","bar","foobar","foob"]']1367+1368+ - title: "`explode`"1369+ body: |1370+1371+ Converts an input string into an array of the string's1372+ codepoint numbers.1373+1374+ examples:1375+ - program: 'explode'1376+ input: '"foobar"'1377+ output: ['[102,111,111,98,97,114]']1378+1379+ - title: "`implode`"1380+ body: |1381+1382+ The inverse of explode.1383+1384+ examples:1385+ - program: 'implode'1386+ input: '[65, 66, 67]'1387+ output: ['"ABC"']1388+1389+ - title: "`split`"1390+ body: |1391+1392+ Splits an input string on the separator argument.1393+1394+ examples:1395+ - program: 'split(", ")'1396+ input: '"a, b,c,d, e, "'1397+ output: ['["a","b,c,d","e",""]']1398+1399+ - title: "`join(str)`"1400+ body: |1401+1402+ Joins the array of elements given as input, using the1403+ argument as separator. It is the inverse of `split`: that is,1404+ running `split("foo") | join("foo")` over any input string1405+ returns said input string.1406+1407+ examples:1408+ - program: 'join(", ")'1409+ input: '["a","b,c,d","e"]'1410+ output: ['"a, b,c,d, e"']1411+1412+1413+ - title: "`ascii_downcase`, `ascii_upcase`"1414+ body: |1415+1416+ Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1417+ converted to the specified case.1418+1419+ example:1420+ - program: 'ascii_upcase'1421+ input: '"useful but not for é"'1422+ output: '"USEFUL BUT NOT FOR é"'1423+1424+ - title: "`while(cond; update)`"1425+ body: |1426+1427+ The `while(cond; update)` function allows you to repeatedly1428+ apply an update to `.` until `cond` is false.1429+1430+ Note that `while(cond; update)` is internally defined as a1431+ recursive jq function. Recursive calls within `while` will1432+ not consume additional memory if `update` produces at most one1433+ output for each input. See advanced topics below.1434+1435+ examples:1436+ - program: '[while(.<100; .*2)]'1437+ input: '1'1438+ output: ['[1,2,4,8,16,32,64]']1439+1440+ - title: "`until(cond; next)`"1441+ body: |1442+1443+ The `until(cond; next)` function allows you to repeatedly1444+ apply the expression `next`, initially to `.` then to its own1445+ output, until `cond` is true. For example, this can be used1446+ to implement a factorial function (see below).1447+1448+ Note that `until(cond; next)` is internally defined as a1449+ recursive jq function. Recursive calls within `until()` will1450+ not consume additional memory if `next` produces at most one1451+ output for each input. See advanced topics below.1452+1453+ examples:1454+ - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1455+ input: '4'1456+ output: ['24']1457+1458+1459+ - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`, `recurse_down`"1460+ body: |1461+1462+ The `recurse(f)` function allows you to search through a1463+ recursive structure, and extract interesting data from all1464+ levels. Suppose your input represents a filesystem:1465+1466+ {"name": "/", "children": [1467+ {"name": "/bin", "children": [1468+ {"name": "/bin/ls", "children": []},1469+ {"name": "/bin/sh", "children": []}]},1470+ {"name": "/home", "children": [1471+ {"name": "/home/stephen", "children": [1472+ {"name": "/home/stephen/jq", "children": []}]}]}]}1473+1474+ Now suppose you want to extract all of the filenames1475+ present. You need to retrieve `.name`, `.children[].name`,1476+ `.children[].children[].name`, and so on. You can do this1477+ with:1478+1479+ recurse(.children[]) | .name1480+1481+ When called without an argument, `recurse` is equivalent to1482+ `recurse(.[]?)`.1483+1484+ `recurse(f)` is identical to `recurse(f; . != null)` and can be1485+ used without concerns about recursion depth.1486+1487+ `recurse(f; condition)` is a generator which begins by1488+ emitting . and then emits in turn .|f, .|f|f, .|f|f|f, ... so long1489+ as the computed value satisfies the condition. For example,1490+ to generate all the integers, at least in principle, one1491+ could write `recurse(.+1; true)`.1492+1493+ For legacy reasons, `recurse_down` exists as an alias to1494+ calling `recurse` without arguments. This alias is considered1495+ *deprecated* and will be removed in the next major release.1496+1497+ The recursive calls in `recurse` will not consume additional1498+ memory whenever `f` produces at most a single output for each1499+ input.1500+1501+ examples:1502+ - program: 'recurse(.foo[])'1503+ input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'1504+ output:1505+ - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'1506+ - '{"foo":[]}'1507+ - '{"foo":[{"foo":[]}]}'1508+ - '{"foo":[]}'1509+1510+ - program: 'recurse'1511+ input: '{"a":0,"b":[1]}'1512+ output:1513+ - '{"a":0,"b":[1]}'1514+ - '0'1515+ - '[1]'1516+ - '1'1517+1518+ - program: 'recurse(. * .; . < 20)'1519+ input: 21520+ output:1521+ - 21522+ - 41523+ - 161524+1525+ - title: "`..`"1526+ body: |1527+1528+ Short-hand for `recurse` without arguments. This is intended1529+ to resemble the XPath `//` operator. Note that `..a` does not1530+ work; use `..|a` instead. In the example below we use1531+ `..|.a?` to find all the values of object keys "a" in any1532+ object found "below" `.`.1533+1534+ examples:1535+ - program: '..|.a?'1536+ input: '[[{"a":1}]]'1537+ output: ['1']1538+1539+ - title: "`env`"1540+ body: |1541+1542+ Outputs an object representing jq's environment.1543+1544+ examples:1545+ - program: 'env.PAGER'1546+ input: 'null'1547+ output: ['"less"']1548+1549+ - title: "`transpose`"1550+ body: |1551+1552+ Transpose a possibly jagged matrix (an array of arrays).1553+ Rows are padded with nulls so the result is always rectangular.1554+1555+ examples:1556+ - program: 'transpose'1557+ input: '[[1], [2,3]]'1558+ output: ['[[1,2],[null,3]]']1559+1560+ - title: "`bsearch(x)`"1561+ body: |1562+1563+ bsearch(x) conducts a binary search for x in the input1564+ array. If the input is sorted and contains x, then1565+ bsearch(x) will return its index in the array; otherwise, if1566+ the array is sorted, it will return (-1 - ix) where ix is an1567+ insertion point such that the array would still be sorted1568+ after the insertion of x at ix. If the array is not sorted,1569+ bsearch(x) will return an integer that is probably of no1570+ interest.1571+1572+ examples:1573+ - program: 'bsearch(0)'1574+ input: '[0,1]'1575+ output: ['0']1576+ - program: 'bsearch(0)'1577+ input: '[1,2,3]'1578+ output: ['-1']1579+ - program: 'bsearch(4) as $ix | if $ix < 0 then .[-(1+$ix)] = 4 else . end'1580+ input: '[1,2,3]'1581+ output: ['[1,2,3,4]']1582+1583+ - title: "String interpolation - `\\(foo)`"1584+ body: |1585+1586+ Inside a string, you can put an expression inside parens1587+ after a backslash. Whatever the expression returns will be1588+ interpolated into the string.1589+1590+ examples:1591+ - program: '"The input was \(.), which is one less than \(.+1)"'1592+ input: '42'1593+ output: ['"The input was 42, which is one less than 43"']1594+1595+ - title: "Convert to/from JSON"1596+ body: |1597+1598+ The `tojson` and `fromjson` builtins dump values as JSON texts1599+ or parse JSON texts into values, respectively. The tojson1600+ builtin differs from tostring in that tostring returns strings1601+ unmodified, while tojson encodes strings as JSON strings.1602+1603+ examples:1604+ - program: '[.[]|tostring]'1605+ input: '[1, "foo", ["foo"]]'1606+ output: ['["1","foo","[\"foo\"]"]']1607+ - program: '[.[]|tojson]'1608+ input: '[1, "foo", ["foo"]]'1609+ output: ['["1","\"foo\"","[\"foo\"]"]']1610+ - program: '[.[]|tojson|fromjson]'1611+ input: '[1, "foo", ["foo"]]'1612+ output: ['[1,"foo",["foo"]]']1613+1614+ - title: "Format strings and escaping"1615+ body: |1616+1617+ The `@foo` syntax is used to format and escape strings,1618+ which is useful for building URLs, documents in a language1619+ like HTML or XML, and so forth. `@foo` can be used as a1620+ filter on its own, the possible escapings are:1621+1622+ * `@text`:1623+1624+ Calls `tostring`, see that function for details.1625+1626+ * `@json`:1627+1628+ Serializes the input as JSON.1629+1630+ * `@html`:1631+1632+ Applies HTML/XML escaping, by mapping the characters1633+ `<>&'"` to their entity equivalents `<`, `>`,1634+ `&`, `'`, `"`.1635+1636+ * `@uri`:1637+1638+ Applies percent-encoding, by mapping all reserved URI1639+ characters to a `%XX` sequence.1640+1641+ * `@csv`:1642+1643+ The input must be an array, and it is rendered as CSV1644+ with double quotes for strings, and quotes escaped by1645+ repetition.1646+1647+ * `@tsv`:1648+1649+ The input must be an array, and it is rendered as TSV1650+ (tab-separated values). Each input array will be printed as1651+ a single line. Fields are separated by a single1652+ tab (ascii `0x09`). Input characters line-feed (ascii `0x0a`),1653+ carriage-return (ascii `0x0d`), tab (ascii `0x09`) and1654+ backslash (ascii `0x5c`) will be output as escape sequences1655+ `\n`, `\r`, `\t`, `\\` respectively.1656+1657+ * `@sh`:1658+1659+ The input is escaped suitable for use in a command-line1660+ for a POSIX shell. If the input is an array, the output1661+ will be a series of space-separated strings.1662+1663+ * `@base64`:1664+1665+ The input is converted to base64 as specified by RFC 4648.1666+1667+ This syntax can be combined with string interpolation in a1668+ useful way. You can follow a `@foo` token with a string1669+ literal. The contents of the string literal will *not* be1670+ escaped. However, all interpolations made inside that string1671+ literal will be escaped. For instance,1672+1673+ @uri "https://www.google.com/search?q=\(.search)"1674+1675+ will produce the following output for the input1676+ `{"search":"what is jq?"}`:1677+1678+ "https://www.google.com/search?q=what%20is%20jq%3F"1679+1680+ Note that the slashes, question mark, etc. in the URL are1681+ not escaped, as they were part of the string literal.1682+1683+ examples:1684+ - program: '@html'1685+ input: '"This works if x < y"'1686+ output: ['"This works if x < y"']1687+1688+# - program: '@html "<span>Anonymous said: \(.)</span>"'1689+# input: '"<script>alert(\"lol hax\");</script>"'1690+# output: ["<span>Anonymous said: <script>alert("lol hax");</script></span>"]1691+1692+ - program: '@sh "echo \(.)"'1693+ input: "\"O'Hara's Ale\""1694+ output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]1695+1696+ - title: "Dates"1697+ body: |1698+1699+ jq provides some basic date handling functionality, with some1700+ high-level and low-level builtins. In all cases these1701+ builtins deal exclusively with time in UTC.1702+1703+ The `fromdateiso8601` builtin parses datetimes in the ISO 86011704+ format to a number of seconds since the Unix epoch1705+ (1970-01-01T00:00:00Z). The `todateiso8601` builtin does the1706+ inverse.1707+1708+ The `fromdate` builtin parses datetime strings. Currently1709+ `fromdate` only supports ISO 8601 datetime strings, but in the1710+ future it will attempt to parse datetime strings in more1711+ formats.1712+1713+ The `todate` builtin is an alias for `todateiso8601`.1714+1715+ The `now` builtin outputs the current time, in seconds since1716+ the Unix epoch.1717+1718+ Low-level jq interfaces to the C-library time functions are1719+ also provided: `strptime`, `strftime`, `mktime`, and `gmtime`.1720+ Refer to your host operating system's documentation for the1721+ format strings used by `strptime` and `strftime`. Note: these1722+ are not necessarily stable interfaces in jq, particularly as1723+ to their localization functionality.1724+1725+ The `gmtime` builtin consumes a number of seconds since the1726+ Unix epoch and outputs a "broken down time" representation of1727+ time as an array of numbers representing (in this order): the1728+ year, the month (zero-based), the day of the month, the hour1729+ of the day, the minute of the hour, the second of the minute,1730+ the day of the week, and the day of the year -- all one-based1731+ unless otherwise stated.1732+1733+ The `mktime` builtin consumes "broken down time"1734+ representations of time output by `gmtime` and `strptime`.1735+1736+ The `strptime(fmt)` builtin parses input strings matching the1737+ `fmt` argument. The output is in the "broken down time"1738+ representation consumed by `gmtime` and output by `mktime`.1739+1740+ The `strftime(fmt)` builtin formats a time with the given1741+ format.1742+1743+ The format strings for `strptime` and `strftime` are described1744+ in typical C library documentation. The format string for ISO1745+ 8601 datetime is `"%Y-%m-%dT%H:%M:%SZ"`.1746+1747+ jq may not support some or all of this date functionality on1748+ some systems.1749+1750+ examples:1751+ - program: 'fromdate'1752+ input: '"2015-03-05T23:51:47Z"'1753+ output: ['1425599507']1754+1755+ - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")'1756+ input: '"2015-03-05T23:51:47Z"'1757+ output: ['[2015,2,5,23,51,47,4,63]']1758+1759+ - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'1760+ input: '"2015-03-05T23:51:47Z"'1761+ output: ['1425599507']1762+1763+ - title: Conditionals and Comparisons1764+ entries:1765+ - title: "`==`, `!=`"1766+ body: |1767+1768+ The expression 'a == b' will produce 'true' if the result of a and b1769+ are equal (that is, if they represent equivalent JSON documents) and1770+ 'false' otherwise. In particular, strings are never considered equal1771+ to numbers. If you're coming from Javascript, jq's == is like1772+ Javascript's === - considering values equal only when they have the1773+ same type as well as the same value.1774+1775+ != is "not equal", and 'a != b' returns the opposite value of 'a == b'1776+1777+ examples:1778+ - program: '.[] == 1'1779+ input: '[1, 1.0, "1", "banana"]'1780+ output: ['true', 'true', 'false', 'false']1781+1782+ - title: if-then-else1783+ body: |1784+1785+ `if A then B else C end` will act the same as `B` if `A`1786+ produces a value other than false or null, but act the same1787+ as `C` otherwise.1788+1789+ Checking for false or null is a simpler notion of1790+ "truthiness" than is found in Javascript or Python, but it1791+ means that you'll sometimes have to be more explicit about1792+ the condition you want: you can't test whether, e.g. a1793+ string is empty using `if .name then A else B end`, you'll1794+ need something more like `if (.name | length) > 0 then A else1795+ B end` instead.1796+1797+ If the condition A produces multiple results, it is1798+ considered "true" if any of those results is not false or1799+ null. If it produces zero results, it's considered false.1800+1801+ More cases can be added to an if using `elif A then B` syntax.1802+1803+ examples:1804+ - program: |-1805+ if . == 0 then1806+ "zero"1807+ elif . == 1 then1808+ "one"1809+ else1810+ "many"1811+ end1812+ input: 21813+ output: ['"many"']1814+1815+ - title: "`>, >=, <=, <`"1816+ body: |1817+1818+ The comparison operators `>`, `>=`, `<=`, `<` return whether1819+ their left argument is greater than, greater than or equal1820+ to, less than or equal to or less than their right argument1821+ (respectively).1822+1823+ The ordering is the same as that described for `sort`, above.1824+1825+ examples:1826+ - program: '. < 5'1827+ input: 21828+ output: ['true']1829+1830+ - title: and/or/not1831+ body: |1832+1833+ jq supports the normal Boolean operators and/or/not. They have the1834+ same standard of truth as if expressions - false and null are1835+ considered "false values", and anything else is a "true value".1836+1837+ If an operand of one of these operators produces multiple1838+ results, the operator itself will produce a result for each input.1839+1840+ `not` is in fact a builtin function rather than an operator,1841+ so it is called as a filter to which things can be piped1842+ rather than with special syntax, as in `.foo and .bar |1843+ not`.1844+1845+ These three only produce the values "true" and "false", and1846+ so are only useful for genuine Boolean operations, rather1847+ than the common Perl/Python/Ruby idiom of1848+ "value_that_may_be_null or default". If you want to use this1849+ form of "or", picking between two values rather than1850+ evaluating a condition, see the "//" operator below.1851+1852+ examples:1853+ - program: '42 and "a string"'1854+ input: 'null'1855+ output: ['true']1856+ - program: '(true, false) or false'1857+ input: 'null'1858+ output: ['true', 'false']1859+# - program: '(true, false) and (true, false)'1860+# input: 'null'1861+# output: ['true', 'false', 'false', 'false']1862+ - program: '(true, true) and (true, false)'1863+ input: 'null'1864+ output: ['true', 'false', 'true', 'false']1865+ - program: '[true, false | not]'1866+ input: 'null'1867+ output: ['[false, true]']1868+1869+ - title: Alternative operator - `//`1870+ body: |1871+1872+ A filter of the form `a // b` produces the same1873+ results as `a`, if `a` produces results other than `false`1874+ and `null`. Otherwise, `a // b` produces the same results as `b`.1875+1876+ This is useful for providing defaults: `.foo // 1` will1877+ evaluate to `1` if there's no `.foo` element in the1878+ input. It's similar to how `or` is sometimes used in Python1879+ (jq's `or` operator is reserved for strictly Boolean1880+ operations).1881+1882+ examples:1883+ - program: '.foo // 42'1884+ input: '{"foo": 19}'1885+ output: [19]1886+ - program: '.foo // 42'1887+ input: '{}'1888+ output: [42]1889+1890+ - title: try-catch1891+ body: |1892+1893+ Errors can be caught by using `try EXP catch EXP`. The first1894+ expression is executed, and if it fails then the second is1895+ executed with the error message. The output of the handler,1896+ if any, is output as if it had been the output of the1897+ expression to try.1898+1899+ The `try EXP` form uses `empty` as the exception handler.1900+1901+ examples:1902+ - program: 'try .a catch ". is not an object"'1903+ input: 'true'1904+ output: ['". is not an object"']1905+ - program: '[.[]|try .a]'1906+ input: '[{}, true, {"a":1}]'1907+ output: ['[null, 1]']1908+ - program: 'try error("some exception") catch .'1909+ input: 'true'1910+ output: ['"some exception"']1911+1912+ - title: Breaking out of control structures1913+ body: |1914+1915+ A convenient use of try/catch is to break out of control1916+ structures like `reduce`, `foreach`, `while`, and so on.1917+1918+ For example:1919+1920+ # Repeat an expression until it raises "break" as an1921+ # error, then stop repeating without re-raising the error.1922+ # But if the error caught is not "break" then re-raise it.1923+ try repeat(exp) catch .=="break" then empty else error;1924+1925+ jq has a syntax for named lexical labels to "break" or "go (back) to":1926+1927+ label $out | ... break $out ...1928+1929+ The `break $label_name` expression will cause the program to1930+ to act as though the nearest (to the left) `label $label_name`1931+ produced `empty`.1932+1933+ The relationship between the `break` and corresponding `label`1934+ is lexical: the label has to be "visible" from the break.1935+1936+ To break out of a `reduce`, for example:1937+1938+ label $out | reduce .[] as $item (null; if .==false then break $out else ... end)1939+1940+ The following jq program produces a syntax error:1941+1942+ break $out1943+1944+ because no label `$out` is visible.1945+1946+ - title: "`?` operator"1947+ body: |1948+1949+ The `?` operator, used as `EXP?`, is shorthand for `try EXP`.1950+1951+ examples:1952+ - program: '[.[]|(.a)?]'1953+ input: '[{}, true, {"a":1}]'1954+ output: ['[null, 1]']1955+1956+1957+ - title: Regular expressions (PCRE)1958+ body: |1959+1960+ jq uses the Oniguruma regular expression library, as do php,1961+ ruby, TextMate, Sublime Text, etc, so the description here1962+ will focus on jq specifics.1963+1964+ The jq regex filters are defined so that they can be used using1965+ one of these patterns:1966+1967+ STRING | FILTER( REGEX )1968+ STRING | FILTER( REGEX; FLAGS )1969+ STRING | FILTER( [REGEX] )1970+ STRING | FILTER( [REGEX, FLAGS] )1971+1972+ where:1973+ * STRING, REGEX and FLAGS are jq strings and subject to jq string interpolation;1974+ * REGEX, after string interpolation, should be a valid PCRE regex;1975+ * FILTER is one of `test`, `match`, or `capture`, as described below.1976+1977+ FLAGS is a string consisting of one of more of the supported flags:1978+1979+ * `g` - Global search (find all matches, not just the first)1980+ * `i` - Case insensitive search1981+ * `m` - Multi line mode ('.' will match newlines)1982+ * `n` - Ignore empty matches1983+ * `p` - Both s and m modes are enabled1984+ * `s` - Single line mode ('^' -> '\A', '$' -> '\Z')1985+ * `l` - Find longest possible matches1986+ * `x` - Extended regex format (ignore whitespace and comments)1987+1988+ To match whitespace in an x pattern use an escape such as \s, e.g.1989+1990+ * test( "a\\sb", "x" ).1991+1992+ Note that certain flags may also be specified within REGEX, e.g.1993+1994+ * jq -n '("test", "TEst", "teST", "TEST") | test( "(?i)te(?-i)st" )'1995+1996+ evaluates to: true, true, false, false.1997+1998+ entries:1999+ - title: "\\[Requires 1.5\\] `test(val)`, `test(regex; flags)`"2000+ body: |2001+2002+ Like `match`, but does not return match objects, only `true` or `false`2003+ for whether or not the regex matches the input.2004+2005+ examples:2006+ - program: 'test("foo")'2007+ input: '"foo"'2008+ output: ['true']2009+ - program: '.[] | test("a b c # spaces are ignored"; "ix")'2010+ input: '["xabcd", "ABC"]'2011+ output: ['true', 'true']2012+2013+ - title: "\\[Requires 1.5\\] `match(val)`, `match(regex; flags)`"2014+ body: |2015+2016+ **match** outputs an object for each match it finds. Matches have2017+ the following fields:2018+2019+ * `offset` - offset in UTF-8 codepoints from the beginning of the input2020+ * `length` - length in UTF-8 codepoints of the match2021+ * `string` - the string that it matched2022+ * `captures` - an array of objects representing capturing groups.2023+2024+ Capturing group objects have the following fields:2025+2026+ * `offset` - offset in UTF-8 codepoints from the beginning of the input2027+ * `length` - length in UTF-8 codepoints of this capturing group2028+ * `string` - the string that was captured2029+ * `name` - the name of the capturing group (or `null` if it was unnamed)2030+2031+ Capturing groups that did not match anything return an offset of -12032+2033+ examples:2034+ - program: 'match("(abc)+"; "g")'2035+ input: '"abc abc"'2036+ output:2037+ - '{"offset": 0, "length": 3, "string": "abc", "captures": [{"offset": 0, "length": 3, "string": "abc", "name": null}]}'2038+ - '{"offset": 4, "length": 3, "string": "abc", "captures": [{"offset": 4, "length": 3, "string": "abc", "name": null}]}'2039+ - program: 'match("foo")'2040+ input: '"foo bar foo"'2041+ output: ['{"offset": 0, "length": 3, "string": "foo", "captures": []}']2042+ - program: 'match(["foo", "ig"])'2043+ input: '"foo bar FOO"'2044+ output:2045+ - '{"offset": 0, "length": 3, "string": "foo", "captures": []}'2046+ - '{"offset": 8, "length": 3, "string": "FOO", "captures": []}'2047+ - program: 'match("foo (?<bar123>bar)? foo"; "ig")'2048+ input: '"foo bar foo foo foo"'2049+ output:2050+ - '{"offset": 0, "length": 11, "string": "foo bar foo", "captures": [{"offset": 4, "length": 3, "string": "bar", "name": "bar123"}]}'2051+ - '{"offset": 12, "length": 8, "string": "foo foo", "captures": [{"offset": -1, "length": 0, "string": null, "name": "bar123"}]}'2052+2053+ - program: '[ match("."; "g")] | length'2054+ input: '"abc"'2055+ output: [3]2056+2057+2058+ - title: "\\[Requires 1.5\\] `capture(val)`, `capture(regex; flags)`"2059+ body: |2060+2061+ Collects the named captures in a JSON object, with the name2062+ of each capture as the key, and the matched string as the2063+ corresponding value.2064+2065+ examples:2066+ - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2067+ input: '"xyzzy-14"'2068+ output: ['{ "a": "xyzzy", "n": "14" }']2069+2070+ - title: "\\[Requires 1.5\\] `scan(regex)`, `scan(regex; flags)`"2071+ body: |2072+2073+ Emit a stream of the non-overlapping substrings of the input2074+ that match the regex in accordance with the flags, if any2075+ have been specified. If there is no match, the stream is empty.2076+ To capture all the matches for each input string, use the idiom2077+ `[ expr ]`, e.g. `[ scan(regex) ]`.2078+2079+ example:2080+ - program: 'scan("c")'2081+ input: '"abcdefabc"'2082+ output: ['"c"', '"c"']2083+2084+ - program: 'scan("b")'2085+ input: ("", "")2086+ output: ['[]', '[]']2087+2088+ - title: "`split(regex; flags)`"2089+ body: |2090+2091+ For backwards compatibility, `split` splits on a string, not a regex.2092+2093+ example:2094+ - program: 'split(", *"; null)'2095+ input: '"ab,cd, ef"'2096+ output: ['"ab","cd","ef"']2097+2098+2099+ - title: "\\[Requires 1.5\\] `splits(regex)`, `splits(regex; flags)`"2100+ body: |2101+2102+ These provide the same results as their `split` counterparts,2103+ but as a stream instead of an array.2104+2105+ example:2106+ - program: 'splits(", *")'2107+ input: '("ab,cd", "ef, gh")'2108+ output: ['"ab"', '"cd"', '"ef"', '"gh"']2109+2110+ - title: "\\[Requires 1.5\\] `sub(regex; tostring)` `sub(regex; string; flags)`"2111+ body: |2112+2113+ Emit the string obtained by replacing the first match of regex in the2114+ input string with `tostring`, after interpolation. `tostring` should2115+ be a jq string, and may contain references to named captures. The2116+ named captures are, in effect, presented as a JSON object (as2117+ constructed by `capture`) to `tostring`, so a reference to a captured2118+ variable named "x" would take the form: "\(.x)".2119+2120+ example:2121+ - program: 'sub("^[^a-z]*(?<x>[a-z]*).*")'2122+ input: '"123abc456"'2123+ output: '"ZabcZabc"'2124+2125+2126+ - title: "\\[Requires 1.5\\] `gsub(regex; string)`, `gsub(regex; string; flags)`"2127+ body: |2128+2129+ `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2130+ replaced by the string, after interpolation.2131+2132+ example:2133+ - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2134+ input: '"Abcabc"'2135+ output: '"+A-+a-"'2136+2137+2138+ - title: Advanced features2139+ body: |2140+ Variables are an absolute necessity in most programming languages, but2141+ they're relegated to an "advanced feature" in jq.2142+2143+ In most languages, variables are the only means of passing around2144+ data. If you calculate a value, and you want to use it more than once,2145+ you'll need to store it in a variable. To pass a value to another part2146+ of the program, you'll need that part of the program to define a2147+ variable (as a function parameter, object member, or whatever) in2148+ which to place the data.2149+2150+ It is also possible to define functions in jq, although this is2151+ is a feature whose biggest use is defining jq's standard library2152+ (many jq functions such as `map` and `find` are in fact written2153+ in jq).2154+2155+ jq has reduction operators, which are very powerful but a bit2156+ tricky. Again, these are mostly used internally, to define some2157+ useful bits of jq's standard library.2158+2159+ It may not be obvious at first, but jq is all about generators2160+ (yes, as often found in other languages). Some utilities are2161+ provided to help deal with generators.2162+2163+ Some minimal I/O support (besides reading JSON from standard2164+ input, and writing JSON to standard output) is available.2165+2166+ Finally, there is a module/library system.2167+2168+ entries:2169+ - title: Variables2170+ body: |2171+2172+ In jq, all filters have an input and an output, so manual2173+ plumbing is not necessary to pass a value from one part of a program2174+ to the next. Many expressions, for instance `a + b`, pass their input2175+ to two distinct subexpressions (here `a` and `b` are both passed the2176+ same input), so variables aren't usually necessary in order to use a2177+ value twice.2178+2179+ For instance, calculating the average value of an array of numbers2180+ requires a few variables in most languages - at least one to hold the2181+ array, perhaps one for each element or for a loop counter. In jq, it's2182+ simply `add / length` - the `add` expression is given the array and2183+ produces its sum, and the `length` expression is given the array and2184+ produces its length.2185+2186+ So, there's generally a cleaner way to solve most problems in jq than2187+ defining variables. Still, sometimes they do make things easier, so jq2188+ lets you define variables using `expression as $variable`. All2189+ variable names start with `$`. Here's a slightly uglier version of the2190+ array-averaging example:2191+2192+ length as $array_length | add / $array_length2193+2194+ We'll need a more complicated problem to find a situation where using2195+ variables actually makes our lives easier.2196+2197+2198+ Suppose we have an array of blog posts, with "author" and "title"2199+ fields, and another object which is used to map author usernames to2200+ real names. Our input looks like:2201+2202+ {"posts": [{"title": "Frist psot", "author": "anon"},2203+ {"title": "A well-written article", "author": "person1"}],2204+ "realnames": {"anon": "Anonymous Coward",2205+ "person1": "Person McPherson"}}2206+2207+ We want to produce the posts with the author field containing a real2208+ name, as in:2209+2210+ {"title": "Frist psot", "author": "Anonymous Coward"}2211+ {"title": "A well-written article", "author": "Person McPherson"}2212+2213+ We use a variable, $names, to store the realnames object, so that we2214+ can refer to it later when looking up author usernames:2215+2216+ .realnames as $names | .posts[] | {title, author: $names[.author]}2217+2218+ The expression `exp as $x | ...` means: for each value of expression2219+ `exp`, run the rest of the pipeline with the entire original input, and2220+ with `$x` set to that value. Thus `as` functions as something of a2221+ foreach loop.2222+2223+ Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2224+ `{$foo}` is a handy way of writing `{foo:$foo}`.2225+2226+ Multiple variables may be declared using a single `as` expression by2227+ providing a pattern that matches the structure of the input2228+ (this is known as "destructuring"):2229+2230+ . as {realnames: $names, posts: [$first, $second]} | ...2231+2232+ The variable declarations in array patterns (e.g., `. as2233+ [$first, $second]`) bind to the elements of the array in from2234+ the element at index zero on up, in order. When there is no2235+ value at the index for an array pattern element, `null` is2236+ bound to that variable.2237+2238+ Variables are scoped over the rest of the expression that defines2239+ them, so2240+2241+ .realnames as $names | (.posts[] | {title, author: $names[.author]})2242+2243+ will work, but2244+2245+ (.realnames as $names | .posts[]) | {title, author: $names[.author]}2246+2247+ won't.2248+2249+ For programming language theorists, it's more accurate to2250+ say that jq variables are lexically-scoped bindings. In2251+ particular there's no way to change the value of a binding;2252+ one can only setup a new binding with the same name, but which2253+ will not be visible where the old one was.2254+2255+ examples:2256+ - program: '.bar as $x | .foo | . + $x'2257+ input: '{"foo":10, "bar":200}'2258+ output: ['210']2259+ - program: '. as $i|[(.*2|. as $i| $i), $i]'2260+ input: '5'2261+ output: ['[10,5]']2262+ - program: '. as [$a, $b, {c: $c}] | $a + $b + $c'2263+ input: '[2, 3, {"c": 4, "d": 5}]'2264+ output: ['9']2265+ - program: '.[] as [$a, $b] | {a: $a, b: $b}'2266+ input: '[[0], [0, 1], [2, 1, 0]]'2267+ output: ['{"a":0,"b":null}', '{"a":0,"b":1}', '{"a":2,"b":1}']2268+2269+ - title: 'Defining Functions'2270+ body: |2271+2272+ You can give a filter a name using "def" syntax:2273+2274+ def increment: . + 1;2275+2276+ From then on, `increment` is usable as a filter just like a2277+ builtin function (in fact, this is how some of the builtins2278+ are defined). A function may take arguments:2279+2280+ def map(f): [.[] | f];2281+2282+ Arguments are passed as filters, not as values. The2283+ same argument may be referenced multiple times with2284+ different inputs (here `f` is run for each element of the2285+ input array). Arguments to a function work more like2286+ callbacks than like value arguments. This is important to2287+ understand. Consider:2288+2289+ def foo(f): f|f;2290+ 5|foo(.*2)2291+2292+ The result will be 20 because `f` is `.*2`, and during the2293+ first invocation of `f` `.` will be 5, and the second time it2294+ will be 10 (5 * 2), so the result will be 20. Function2295+ arguments are filters, and filters expect an input when2296+ invoked.2297+2298+ If you want the value-argument behaviour for defining simple2299+ functions, you can just use a variable:2300+2301+ def addvalue(f): f as $f | map(. + $f);2302+2303+ Or use the short-hand:2304+2305+ def addvalue($f): ...;2306+2307+ With either definition, `addvalue(.foo)` will add the current2308+ input's `.foo` field to each element of the array.2309+2310+ Multiple definitions using the same function name are allowed.2311+ Each re-definition replaces the previous one for the same2312+ number of function arguments, but only for references from2313+ functions (or main program) subsequent to the re-definition.2314+2315+ examples:2316+ - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'2317+ input: '[[1,2],[10,20]]'2318+ output: ['[[1,2,1], [10,20,10]]']2319+ - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'2320+ input: '[[1,2],[10,20]]'2321+ output: ['[[1,2,1,2], [10,20,1,2]]']2322+2323+ - title: Reduce2324+ body: |2325+2326+ The `reduce` syntax in jq allows you to combine all of the2327+ results of an expression by accumulating them into a single2328+ answer. As an example, we'll pass `[3,2,1]` to this expression:2329+2330+ reduce .[] as $item (0; . + $item)2331+2332+ For each result that `.[]` produces, `. + $item` is run to2333+ accumulate a running total, starting from 0. In this2334+ example, `.[]` produces the results 3, 2, and 1, so the2335+ effect is similar to running something like this:2336+2337+ 0 | (3 as $item | . + $item) |2338+ (2 as $item | . + $item) |2339+ (1 as $item | . + $item)2340+2341+ examples:2342+ - program: 'reduce .[] as $item (0; . + $item)'2343+ input: '[10,2,5,3]'2344+ output: ['20']2345+2346+ - title: "`limit(n; exp)`"2347+ body: |2348+2349+ The `limit` function extracts up to `n` outputs from `exp`.2350+2351+ examples:2352+ - program: '[limit(3;.[])]'2353+ input: '[0,1,2,3,4,5,6,7,8,9]'2354+ output: ['[0,1,2]']2355+2356+ - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"2357+ body: |2358+2359+ The `first(expr)` and `last(expr)` functions extract the first2360+ and last values from `expr`, respectively.2361+2362+ The `nth(n; expr)` function extracts the nth value output by2363+ `expr`. This can be defined as `def nth(n; expr):2364+ last(limit(n + 1; expr));`. Note that `nth(n; expr)` doesn't2365+ support negative values of `n`.2366+2367+ examples:2368+ - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'2369+ input: '10'2370+ output: ['[0,9,5]']2371+2372+ - title: "`first`, `last`, `nth(n)`"2373+ body: |2374+2375+ The `first` and `last` functions extract the first2376+ and last values from any array at `.`.2377+2378+ The `nth(n)` function extracts the nth value of any array at `.`.2379+2380+ examples:2381+ - program: '[range(.)]|[first, last, nth(5)]'2382+ input: '10'2383+ output: ['[0,9,5]']2384+2385+ - title: "`foreach`"2386+ body: |2387+2388+ The `foreach` syntax is similar to `reduce`, but intended to2389+ allow the construction of `limit` and reducers that produce2390+ intermediate results (see example).2391+2392+ The form is `foreach EXP as $var (INIT; UPDATE; EXTRACT)`.2393+ Like `reduce`, `INIT` is evaluated once to produce a state2394+ value, then each output of `EXP` is bound to `$var`, `UPDATE`2395+ is evaluated for each output of `EXP` with the current state2396+ and with `$var` visible. Each value output by `UPDATE`2397+ replaces the previous state. Finally, `EXTRACT` is evaluated2398+ for each new state to extract an output of `foreach`.2399+2400+ This is mostly useful only for constructing `reduce`- and2401+ `limit`-like functions. But it is much more general, as it2402+ allows for partial reductions (see the example below).2403+2404+ examples:2405+ - program: '[foreach .[] as $item2406+ ([[],[]];2407+ if $item == null then [[],.[0]] else [(.[0] + [$item]),[]] end;2408+ if $item == null then .[1] else empty end)]'2409+ input: '[1,2,3,4,null,"a","b",null]'2410+ output: ['[[1,2,3,4],["a","b"]]']2411+2412+ - title: Recursion2413+ body: |2414+2415+ As described above, `recurse` uses recursion, and any jq2416+ function can be recursive. The `while` builtin is also2417+ implemented in terms of recursion.2418+2419+ Tail calls are optimized whenever the expression to the left of2420+ the recursive call outputs its last value. In practice this2421+ means that the expression to the left of the recursive call2422+ should not produce more than one output for each input.2423+2424+ For example:2425+2426+ def recurse(f): def r: ., (f | select(. != null) | r); r;2427+2428+ def while(cond; update):2429+ def _while:2430+ if cond then ., (update | _while) else empty end;2431+ _while;2432+2433+ def repeat(exp):2434+ def _repeat:2435+ exp, _repeat;2436+ _repeat;2437+2438+ - title: Generators and iterators2439+ body: |2440+2441+ Some jq operators and functions are actually generators in2442+ that they can produce zero, one, or more values for each2443+ input, just as one might expect in other programming2444+ languages that have generators. For example, `.[]`2445+ generates all the values in its input (which must be an2446+ array or an object), `range(0; 10)` generates the integers2447+ between 0 and 10, and so on.2448+2449+ Even the comma operator is a generator, generating first the2450+ values generated by the expression to the left of the comma,2451+ then for each of those, the values generate by the2452+ expression on the right of the comma.2453+2454+ The `empty` builtin is the generator that produces zero2455+ outputs. The `empty` builtin backtracks to the preceding2456+ generator expression.2457+2458+ All jq functions can be generators just by using builtin2459+ generators. It is also possible to define new generators2460+ using only recursion and the comma operator. If the2461+ recursive call(s) is(are) "in tail position" then the2462+ generator will be efficient. In the example below the2463+ recursive call by `_range` to itself is in tail position.2464+ The example shows off three advanced topics: tail recursion,2465+ generator construction, and sub-functions.2466+2467+ examples:2468+ - program: 'def range(init; upto; by):2469+ def _range:2470+ if (by > 0 and . < upto) or (by < 0 and . > upto)2471+ then ., ((.+by)|_range)2472+ else . end;2473+ if by == 0 then init else init|_range end |2474+ select((by > 0 and . < upto) or (by < 0 and . > upto));2475+ range(0; 10; 3)'2476+ input: 'null'2477+ output: ['0', '3', '6', '9']2478+ - program: 'def while(cond; update):2479+ def _while:2480+ if cond then ., (update | _while) else empty end;2481+ _while;2482+ [while(.<100; .*2)]'2483+ input: '1'2484+ output: ['[1,2,4,8,16,32,64]']2485+2486+ - title: 'Math'2487+ body: |2488+2489+ jq currently only has IEEE754 double-precision (64-bit) floating2490+ point number support.2491+2492+ Besides simple arithmetic operators such as `+`, jq also has most2493+ standard math functions from the C math library. C math functions2494+ that take a single input argument (e.g., `sin()`) are available as2495+ zero-argument jq functions. C math functions that take two input2496+ arguments (e.g., `pow()`) are available as two-argument jq2497+ functions that ignore `.`.2498+2499+ Availability of standard math functions depends on the2500+ availability of the corresponding math functions in your operating2501+ system and C math library. Unavailable math functions will be2502+ defined but will raise an error.2503+2504+ - title: 'I/O'2505+ body: |2506+2507+ At this time jq has minimal support for I/O, mostly in the2508+ form of control over when inputs are read. Two builtins functions2509+ are provided for this, `input` and `inputs`, that read from the2510+ same sources (e.g., `stdin`, files named on the command-line) as2511+ jq itself. These two builtins, and jq's own reading actions, can2512+ be interleaved with each other.2513+2514+ One builtin provides minimal output capabilities, `debug`.2515+ (Recall that a jq program's output values are always output as2516+ JSON texts on `stdout`.) The `debug` builtin can have2517+ application-specific behavior, such as for executables that use2518+ the libjq C API but aren't the jq executable itself.2519+2520+ entries:2521+ - title: "`input`"2522+ body: |2523+2524+ Outputs one new input.2525+2526+ - title: "`inputs`"2527+ body: |2528+2529+ Outputs all remaining inputs, one by one.2530+2531+ This is primarily useful for reductions over a program's2532+ inputs.2533+2534+ - title: "`debug`"2535+ body: |2536+2537+ Causes a debug message based on the input value to be2538+ produced. The jq executable wraps the input value with2539+ `["DEBUG:", <input-value>]` and prints that and a newline on2540+ stderr, compactly. This may change in the future.2541+2542+ - title: "`input_filename`"2543+ body: |2544+2545+ Returns the name of the file whose input is currently being2546+ filtered. Note that this will not work well unless jq is2547+ running in a UTF-8 locale.2548+2549+ - title: "`input_line_number`"2550+ body: |2551+2552+ Returns the line number of the input currently being filtered.2553+2554+ - title: 'Streaming'2555+ body: |2556+2557+ With the `--stream` option jq can parse input texts in a streaming2558+ fashion, allowing jq programs to start processing large JSON texts2559+ immediately rather than after the parse completes. If you have a2560+ single JSON text that is 1GB in size, streaming it will allow you2561+ to process it much more quickly.2562+2563+ However, streaming isn't easy to deal with as the jq program will2564+ have `[<path>, <leaf-value>]` (and a few other forms) as inputs.2565+2566+ Several builtins are provided to make handling streams easier.2567+2568+ The examples below use the the streamed form of `[0,[1]]`, which2569+ is `[[0],0],[[1,0],1],[[1,0]],[[1]]`.2570+2571+ Streaming forms include `[<path>, <leaf-value>]` (to indicate any2572+ scalar value, empty array, or empty object), and `[<path>]` (to2573+ indicate the end of an array or object). Future versions of jq2574+ run with `--stream` and `-seq` may output additional forms such as2575+ `["error message"]` when an input text fails to parse.2576+2577+ entries:2578+ - title: "`truncate_stream(stream_expression)`"2579+ body: |2580+2581+ Consumes a number as input and truncates the corresponding2582+ number of path elements from the left of the outputs of the2583+ given streaming expression.2584+2585+ examples:2586+ - program: '[1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]'2587+ input: '1'2588+ output: ['[[[0],2],[[0]]]']2589+2590+ - title: "`fromstream(stream_expression)`"2591+ body: |2592+2593+ Outputs values corresponding to the stream expression's2594+ outputs.2595+2596+ examples:2597+ - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'2598+ input: 'null'2599+ output: ['[2]']2600+2601+ - title: "`tostream`"2602+ body: |2603+2604+ The `tostream` builtin outputs the streamed form of its input.2605+2606+ examples:2607+ - program: '. as $dot|fromstream($dot|tostream)|.==$dot'2608+ input: '[0,[1,{"a":1},{"b":2}]]'2609+ output: ['true']2610+2611+ - title: Assignment2612+ body: |2613+2614+ Assignment works a little differently in jq than in most2615+ programming languages. jq doesn't distinguish between references2616+ to and copies of something - two objects or arrays are either2617+ equal or not equal, without any further notion of being "the2618+ same object" or "not the same object".2619+2620+ If an object has two fields which are arrays, `.foo` and `.bar`,2621+ and you append something to `.foo`, then `.bar` will not get2622+ bigger. Even if you've just set `.bar = .foo`. If you're used to2623+ programming in languages like Python, Java, Ruby, Javascript,2624+ etc. then you can think of it as though jq does a full deep copy2625+ of every object before it does the assignment (for performance,2626+ it doesn't actually do that, but that's the general idea).2627+2628+ All the assignment operators in jq have path expressions on the2629+ left-hand side.2630+2631+ entries:2632+ - title: "`=`"2633+ body: |2634+2635+ The filter `.foo = 1` will take as input an object2636+ and produce as output an object with the "foo" field set to2637+ 1. There is no notion of "modifying" or "changing" something2638+ in jq - all jq values are immutable. For instance,2639+2640+ .foo = .bar | .foo.baz = 12641+2642+ will not have the side-effect of setting .bar.baz to be set2643+ to 1, as the similar-looking program in Javascript, Python,2644+ Ruby or other languages would. Unlike these languages (but2645+ like Haskell and some other functional languages), there is2646+ no notion of two arrays or objects being "the same array" or2647+ "the same object". They can be equal, or not equal, but if2648+ we change one of them in no circumstances will the other2649+ change behind our backs.2650+2651+ This means that it's impossible to build circular values in2652+ jq (such as an array whose first element is itself). This is2653+ quite intentional, and ensures that anything a jq program2654+ can produce can be represented in JSON.2655+2656+ Note that the left-hand side of '=' refers to a value in `.`.2657+ Thus `$var.foo = 1` won't work as expected (`$var.foo` is not2658+ a valid or useful path expression in `.`); use `$var | .foo =2659+ 1` instead.2660+2661+ If the right-hand side of '=' produces multiple values, then2662+ for each such value jq will set the paths on the left-hand2663+ side to the value and then it will output the modified `.`.2664+ For example, `(.a,.b)=range(2)` outputs `{"a":0,"b":0}`, then2665+ `{"a":1,"b":1}`. The "update" assignment forms (see below) do2666+ not do this.2667+2668+ Note too that `.a,.b=0` does not set `.a` and `.b`, but2669+ `(.a,.b)=0` sets both.2670+2671+ - title: "`|=`"2672+ body: |2673+ As well as the assignment operator '=', jq provides the "update"2674+ operator '|=', which takes a filter on the right-hand side and2675+ works out the new value for the property of `.` being assigned2676+ to by running the old value through this expression. For2677+ instance, .foo |= .+1 will build an object with the "foo"2678+ field set to the input's "foo" plus 1.2679+2680+ This example should show the difference between '=' and '|=':2681+2682+ Provide input '{"a": {"b": 10}, "b": 20}' to the programs:2683+2684+ .a = .b2685+ .a |= .b2686+2687+ The former will set the "a" field of the input to the "b" field of the2688+ input, and produce the output {"a": 20}. The latter will set the "a"2689+ field of the input to the "a" field's "b" field, producing {"a": 10}.2690+2691+ The left-hand side can be any general path expression; see `path()`.2692+2693+ Note that the left-hand side of '|=' refers to a value in `.`.2694+ Thus `$var.foo |= . + 1` won't work as expected (`$var.foo` is2695+ not a valid or useful path expression in `.`); use `$var |2696+ .foo |= . + 1` instead.2697+2698+ If the right-hand side outputs multiple values, only the last2699+ one will be used.2700+2701+ examples:2702+2703+ - program: '(..|select(type=="boolean")) |= if . then 1 else 0 end'2704+ input: '[true,false,[5,true,[true,[false]],false]]'2705+ output: ['[1,0,[5,1,[1,[0]],0]]']2706+2707+ - title: "`+=`, `-=`, `*=`, `/=`, `%=`, `//=`"2708+ body: |2709+2710+ jq has a few operators of the form `a op= b`, which are all2711+ equivalent to `a |= . op b`. So, `+= 1` can be used to increment values.2712+2713+ examples:2714+ - program: .foo += 12715+ input: '{"foo": 42}'2716+ output: ['{"foo": 43}']2717+2718+ - title: Complex assignments2719+ body: |2720+ Lots more things are allowed on the left-hand side of a jq assignment2721+ than in most languages. We've already seen simple field accesses on2722+ the left hand side, and it's no surprise that array accesses work just2723+ as well:2724+2725+ .posts[0].title = "JQ Manual"2726+2727+ What may come as a surprise is that the expression on the left may2728+ produce multiple results, referring to different points in the input2729+ document:2730+2731+ .posts[].comments |= . + ["this is great"]2732+2733+ That example appends the string "this is great" to the "comments"2734+ array of each post in the input (where the input is an object with a2735+ field "posts" which is an array of posts).2736+2737+ When jq encounters an assignment like 'a = b', it records the "path"2738+ taken to select a part of the input document while executing a. This2739+ path is then used to find which part of the input to change while2740+ executing the assignment. Any filter may be used on the2741+ left-hand side of an equals - whichever paths it selects from the2742+ input will be where the assignment is performed.2743+2744+ This is a very powerful operation. Suppose we wanted to add a comment2745+ to blog posts, using the same "blog" input above. This time, we only2746+ want to comment on the posts written by "stedolan". We can find those2747+ posts using the "select" function described earlier:2748+2749+ .posts[] | select(.author == "stedolan")2750+2751+ The paths provided by this operation point to each of the posts that2752+ "stedolan" wrote, and we can comment on each of them in the same way2753+ that we did before:2754+2755+ (.posts[] | select(.author == "stedolan") | .comments) |=2756+ . + ["terrible."]2757+2758+ - title: Modules2759+ body: |2760+2761+ jq has a library/module system. Modules are files whose names end2762+ in `.jq`.2763+2764+ Modules imported by a program are searched for in a default search2765+ path (see below). The `import` and `include` directives allow the2766+ importer to alter this path.2767+2768+ Paths in the a search path are subject to various substitutions.2769+2770+ For paths starting with "~/", the user's home directory is2771+ substituted for "~".2772+2773+ For paths starting with "$ORIGIN/", the path of the jq executable2774+ is substituted for "$ORIGIN".2775+2776+ For paths starting with "./" or paths that are ".", the path of2777+ the including file is substituted for ".". For top-level programs2778+ given on the command-line, the current directory is used.2779+2780+ Import directives can optionally specify a search path to which2781+ the default is appended.2782+2783+ The default search path is the search path given to the `-L`2784+ command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",2785+ "$ORIGIN/../lib"]`.2786+2787+ Null and empty string path elements terminate search path2788+ processing.2789+2790+ A dependency with relative path "foo/bar" would be searched for in2791+ "foo/bar.jq" and "foo/bar/bar.jq" in the given search path. This2792+ is intended to allow modules to be placed in a directory along2793+ with, for example, version control files, README files, and so on,2794+ but also to allow for single-file modules.2795+2796+ Consecutive components with the same name are not allowed to avoid2797+ ambiguities (e.g., "foo/foo").2798+2799+ For example, with `-L$HOME/.jq` a module `foo` can be found in2800+ `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.2801+2802+ If "$HOME/.jq" is a file, it is sourced into the main program.2803+2804+ entries:2805+ - title: "`import RelativePathString as NAME [<metadata>];`"2806+ body: |2807+2808+ Imports a module found at the given path relative to a2809+ directory in a search path. A ".jq" suffix will be added to2810+ the relative path string. The module's symbols are prefixed2811+ with "NAME::".2812+2813+ The optional metadata must be a constant jq expression. It2814+ should be an object with keys like "homepage" and so on. At2815+ this time jq only uses the "search" key/value of the metadata.2816+ The metadata is also made available to users via the2817+ `modulemeta` builtin.2818+2819+ The "search" key in the metadata, if present, should have a2820+ string or array value (array of strings); this is the search2821+ path to be prefixed to the top-level search path.2822+2823+ - title: "`include RelativePathString [<metadata>];`"2824+ body: |2825+2826+ Imports a module found at the given path relative to a2827+ directory in a search path as if it were included in place. A2828+ ".jq" suffix will be added to the relative path string. The2829+ module's symbols are imported into the caller's namespace as2830+ if the module's content had been included directly.2831+2832+ The optional metadata must be a constant jq expression. It2833+ should be an object with keys like "homepage" and so on. At2834+ this time jq only uses the "search" key/value of the metadata.2835+ The metadata is also made available to users via the2836+ `modulemeta` builtin.2837+2838+ - title: "`import RelativePathString as $NAME [<metadata>];`"2839+ body: |2840+2841+ Imports a JSON file found at the given path relative to a2842+ directory in a search path. A ".json" suffix will be added to2843+ the relative path string. The file's data will be available2844+ as `$NAME::NAME`.2845+2846+ The optional metadata must be a constant jq expression. It2847+ should be an object with keys like "homepage" and so on. At2848+ this time jq only uses the "search" key/value of the metadata.2849+ The metadata is also made available to users via the2850+ `modulemeta` builtin.2851+2852+ The "search" key in the metadata, if present, should have a2853+ string or array value (array of strings); this is the search2854+ path to be prefixed to the top-level search path.2855+2856+ - title: "`module <metadata>;`"2857+ body: |2858+2859+ This directive is entirely optional. It's not required for2860+ proper operation. It serves only the purpose of providing2861+ metadata that can be read with the `modulemeta` builtin.2862+2863+ The metadata must be a constant jq expression. It should be2864+ an object with keys like "homepage". At this time jq doesn't2865+ use this metadata, but it is made available to users via the2866+ `modulemeta` builtin.2867+2868+ - title: "`modulemeta`"2869+ body: |2870+2871+ Takes a module name as input and outputs the module's metadata2872+ as an object, with the module's imports (including metadata)2873+ as an array value for the "deps" key.2874+2875+ Programs can use this to query a module's metadata, which they2876+ could then use to, for example, search for, download, and2877+ install missing dependencies.2878+modified:docs/content/3.manual/manual.yml+2 added-2 removed
1 unmodified line2 headline: jq Manual (development version)3 4 history: |5 6- *For released versions, see [jq 1.4](/jq/manual/v1.4) or7- [jq 1.3](/jq/manual/v1.3).*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 an2894 unmodified linesmodified:docs/content/index/index.yml+16 added-6 removed
22 unmodified lines23 shorter and simpler than you'd expect.24 25 tail: |26 27- Go read the [tutorial](tutorial/) for more, or the [manual](manual/)27+ Go read the [tutorial](/jq/tutorial/) for more, or the [manual](/jq/manual/)28 for *way* more.29 30 Ask questions on [stackoverflow](https://stackoverflow.com/) using the [jq31 tag](https://stackoverflow.com/questions/tagged/jq), or on the32 [#jq](http://irc.lc/freenode/%23jq/) channel on33 [Freenode](https://webchat.freenode.net/).34 35 news:36- - date: 2015-07-2636+ - date: 15 August 201537 body: |38 39+ jq 1.5 released, including new datetime, math, and regexp functions,40+ try/catch syntax, array and object destructuring, a streaming parser,41+ and a module system. See installation options on the42+ [download](/jq/download/) page, and the43+ [release notes](https://github.com/stedolan/jq/releases/tag/jq-1.5)44+ for details.45+46+ - date: 26 July 201547+ body: |48+49 jq 1.5rc2 is available. Get it on the50 [releases](https://github.com/stedolan/jq/releases) page.51 42- - date: 2015-01-0152+ - date: 01 January 201553 body: |54 55 jq 1.5rc1 is available. Get it on the56 [releases](https://github.com/stedolan/jq/releases) page.57 48- - date: 2014-06-0858+ - date: 09 June 201459 body: |60 51- jq 1.4 (finally) released! Get it on the [download](download/) page.61+ jq 1.4 (finally) released! Get it on the [download](/jq/download/) page.62 53- - date: 2013-05-1963+ - date: 19 May 201364 body: |65 66 jq 1.3 released.67 modified:docs/templates/index.liquid+5 added-10 removed
18 unmodified lines19 20 <div class="btn-toolbar" role="toolbar">21 <div class="btn-group" role="group">22 <a class="btn btn-primary dropdown-toggle" data-toggle="dropdown" href="#">23- Download jq-1.4 or 1.5rc223+ Download jq 1.524 <span class="caret"></span>25 </a>26 <ul class="dropdown-menu">27- <li><a href="https://github.com/stedolan/jq/releases/download/jq-1.5rc2/jq-linux-x86_64">jq-1.5rc2 Linux (64-bit)</a></li>28- <li><a href="https://github.com/stedolan/jq/releases/download/jq-1.5rc2/jq-osx-x86_64">jq-1.5rc2 OS X (64-bit)</a></li>29- <li><a href="https://github.com/stedolan/jq/releases/download/jq-1.5rc2/jq-win64.exe">jq-1.5rc2 Windows (64-bit)</a></li>30- <li><a href="https://github.com/stedolan/jq/releases/tag/jq-1.5rc2">jq-1.5rc2 Other platforms, older versions, and source</a></li>31- <li><a href="https://github.com/stedolan/jq/releases/download/jq-1.4/jq-linux-x86_64">jq-1.4 Linux (64-bit)</a></li>32- <li><a href="https://github.com/stedolan/jq/releases/download/jq-1.4/jq-osx-x86_64">jq-1.4 OS X (64-bit)</a></li>33- <li><a href="https://github.com/stedolan/jq/releases/download/jq-1.4/jq-win64.exe">jq-1.4 Windows (64-bit)</a></li>34- <li><a href="https://github.com/stedolan/jq/releases/tag/jq-1.4">jq-1.4 Other platforms, older versions, and source</a></li>27+ <li><a href="https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64">jq 1.5 Linux (64-bit)</a></li>28+ <li><a href="https://github.com/stedolan/jq/releases/download/jq-1.5/jq-win64.exe">jq 1.5 Windows (64-bit)</a></li>29+ <li><a href="/jq/download/">Other platforms, older versions, and source</a></li>30 </ul>31 </div>32 33 <div class="btn-group">23 unmodified lines57 <div id="news">58 <ul>59 {% for item in news %}60 <li>66- <span class="date">{{ item.date | date: '%m %B %Y' }}</span>61+ <span class="date">{{item.date}}</span>62 {{item.body | markdownify}}63 </li>64 {% endfor %}65 </ul>7 unmodified linesmodified:NEWS+5 added-4 removed
1 2 Release history3 4- * jq version 1.0 was released on Sun Oct 21 20125- * jq version 1.1 was released on Sun Oct 21 20126- * jq version 1.2 was released on Thu Dec 20 20127- * jq version 1.3 was released on Sun May 19 20134+ * jq version 1.5 was released on Sat Aug 15 20155 * jq version 1.4 was released on Mon Jun 9 20146+ * jq version 1.3 was released on Sun May 19 20137+ * jq version 1.2 was released on Thu Dec 20 20128+ * jq version 1.1 was released on Sun Oct 21 20129+ * jq version 1.0 was released on Sun Oct 21 201210 11 New features in 1.5 since 1.4:12 13 - regular expressions (with Oniguruma)76 unmodified linesmodified:sha1sum.txt+6 added
1 # SHA-1 checksums of release and pre-release binaries2 # Download from https://github.com/stedolan/jq/releases3 4+# jq 1.55+ded2716bafcee5f9fc9358c1e71b879e26674a5e jq-linux326+d8e36831c3c94bb58be34dd544f44a6c6cb88568 jq-linux647+7c27c5d941efa5c241750a89c4723d84a6d76025 jq-win32.exe8+2ee589c8821d562eca4e67c2b0e3e30f0c7c6136 jq-win64.exe9+10 # jq 1.5rc211 4975875ed6e758ef5f14ddb72026d430ff6b7b65 jq-linux-x8612 ec498ea174ab4e696d02016e2ad47fbdec2b3aa3 jq-linux-x86_6413 b5ac856d9f900bd65a56862685851bf86b2f4a19 jq-osx-x86_6425 unmodified lines