Remove ruby dependency from website build
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by William Langford · committed by Nico Williams · parent 76e72a3 · Browse files · 38 files·+13626 added−13301 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
38 files+13626 added−13301 removed
- other:+13626 added−13301 removed
Provenance
- Commit
c1f1185- Tree
d445f62- Author
William Langford <wlangfor@gmail.com>- Committer
Nico Williams <nico@cryptonector.com>- Parent
76e72a3
38 files changed+13626 added−13301 removed
deleted:docs/content/1.tutorial/default.yml-327 removed
1-headline: Tutorial2-body:3- - text: |4-5- GitHub has a JSON API, so let's play with that. This URL gets us the last6- 5 commits from the jq repo.7-8- - command: "curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5'"9- result: |10- [11- {12- "sha": "d25341478381063d1c76e81b3a52e0592a7c997f",13- "commit": {14- "author": {15- "name": "Stephen Dolan",16- "email": "mu@netsoc.tcd.ie",17- "date": "2013-06-22T16:30:59Z"18- },19- "committer": {20- "name": "Stephen Dolan",21- "email": "mu@netsoc.tcd.ie",22- "date": "2013-06-22T16:30:59Z"23- },24- "message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",25- "tree": {26- "sha": "6ab697a8dfb5a96e124666bf6d6213822599fb40",27- "url": "https://api.github.com/repos/stedolan/jq/git/trees/6ab697a8dfb5a96e124666bf6d6213822599fb40"28- },29- "url": "https://api.github.com/repos/stedolan/jq/git/commits/d25341478381063d1c76e81b3a52e0592a7c997f",30- "comment_count": 031- },32- "url": "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f",33- "html_url": "https://github.com/stedolan/jq/commit/d25341478381063d1c76e81b3a52e0592a7c997f",34- "comments_url": "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f/comments",35- "author": {36- "login": "stedolan",37- ...38-39- - text: |40-41- GitHub returns nicely formatted JSON. For servers that don't, it can be42- helpful to pipe the response through jq to pretty-print it. The simplest43- jq program is the expression `.`, which takes the input and produces it44- unchanged as output.45-46- - command: "curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jq '.'"47- result: |48- [49- {50- "sha": "d25341478381063d1c76e81b3a52e0592a7c997f",51- "commit": {52- "author": {53- "name": "Stephen Dolan",54- "email": "mu@netsoc.tcd.ie",55- "date": "2013-06-22T16:30:59Z"56- },57- "committer": {58- "name": "Stephen Dolan",59- "email": "mu@netsoc.tcd.ie",60- "date": "2013-06-22T16:30:59Z"61- },62- "message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",63- "tree": {64- "sha": "6ab697a8dfb5a96e124666bf6d6213822599fb40",65- "url": "https://api.github.com/repos/stedolan/jq/git/trees/6ab697a8dfb5a96e124666bf6d6213822599fb40"66- },67- "url": "https://api.github.com/repos/stedolan/jq/git/commits/d25341478381063d1c76e81b3a52e0592a7c997f",68- "comment_count": 069- },70- "url": "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f",71- "html_url": "https://github.com/stedolan/jq/commit/d25341478381063d1c76e81b3a52e0592a7c997f",72- "comments_url": "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f/comments",73- "author": {74- "login": "stedolan",75- ...76-77- - text: |78-79- We can use jq to extract just the first commit.80-81- - command: "curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jq '.[0]'"82- result: |83- {84- "sha": "d25341478381063d1c76e81b3a52e0592a7c997f",85- "commit": {86- "author": {87- "name": "Stephen Dolan",88- "email": "mu@netsoc.tcd.ie",89- "date": "2013-06-22T16:30:59Z"90- },91- "committer": {92- "name": "Stephen Dolan",93- "email": "mu@netsoc.tcd.ie",94- "date": "2013-06-22T16:30:59Z"95- },96- "message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",97- "tree": {98- "sha": "6ab697a8dfb5a96e124666bf6d6213822599fb40",99- "url": "https://api.github.com/repos/stedolan/jq/git/trees/6ab697a8dfb5a96e124666bf6d6213822599fb40"100- },101- "url": "https://api.github.com/repos/stedolan/jq/git/commits/d25341478381063d1c76e81b3a52e0592a7c997f",102- "comment_count": 0103- },104- "url": "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f",105- "html_url": "https://github.com/stedolan/jq/commit/d25341478381063d1c76e81b3a52e0592a7c997f",106- "comments_url": "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f/comments",107- "author": {108- "login": "stedolan",109- "id": 79765,110- "avatar_url": "https://avatars.githubusercontent.com/u/79765?v=3",111- "gravatar_id": "",112- "url": "https://api.github.com/users/stedolan",113- "html_url": "https://github.com/stedolan",114- "followers_url": "https://api.github.com/users/stedolan/followers",115- "following_url": "https://api.github.com/users/stedolan/following{/other_user}",116- "gists_url": "https://api.github.com/users/stedolan/gists{/gist_id}",117- "starred_url": "https://api.github.com/users/stedolan/starred{/owner}{/repo}",118- "subscriptions_url": "https://api.github.com/users/stedolan/subscriptions",119- "organizations_url": "https://api.github.com/users/stedolan/orgs",120- "repos_url": "https://api.github.com/users/stedolan/repos",121- "events_url": "https://api.github.com/users/stedolan/events{/privacy}",122- "received_events_url": "https://api.github.com/users/stedolan/received_events",123- "type": "User",124- "site_admin": false125- },126- "committer": {127- "login": "stedolan",128- "id": 79765,129- "avatar_url": "https://avatars.githubusercontent.com/u/79765?v=3",130- "gravatar_id": "",131- "url": "https://api.github.com/users/stedolan",132- "html_url": "https://github.com/stedolan",133- "followers_url": "https://api.github.com/users/stedolan/followers",134- "following_url": "https://api.github.com/users/stedolan/following{/other_user}",135- "gists_url": "https://api.github.com/users/stedolan/gists{/gist_id}",136- "starred_url": "https://api.github.com/users/stedolan/starred{/owner}{/repo}",137- "subscriptions_url": "https://api.github.com/users/stedolan/subscriptions",138- "organizations_url": "https://api.github.com/users/stedolan/orgs",139- "repos_url": "https://api.github.com/users/stedolan/repos",140- "events_url": "https://api.github.com/users/stedolan/events{/privacy}",141- "received_events_url": "https://api.github.com/users/stedolan/received_events",142- "type": "User",143- "site_admin": false144- },145- "parents": [146- {147- "sha": "54b9c9bdb225af5d886466d72f47eafc51acb4f7",148- "url": "https://api.github.com/repos/stedolan/jq/commits/54b9c9bdb225af5d886466d72f47eafc51acb4f7",149- "html_url": "https://github.com/stedolan/jq/commit/54b9c9bdb225af5d886466d72f47eafc51acb4f7"150- },151- {152- "sha": "8b1b503609c161fea4b003a7179b3fbb2dd4345a",153- "url": "https://api.github.com/repos/stedolan/jq/commits/8b1b503609c161fea4b003a7179b3fbb2dd4345a",154- "html_url": "https://github.com/stedolan/jq/commit/8b1b503609c161fea4b003a7179b3fbb2dd4345a"155- }156- ]157- }158-159- - text: |160-161- For the rest of the examples, I'll leave out the `curl` command - it's not162- going to change.163-164- There's a lot of info we don't care about there, so we'll restrict it down165- to the most interesting fields.166-167- - command: "jq '.[0] | {message: .commit.message, name: .commit.committer.name}'"168- result: |169- {170- "message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",171- "name": "Stephen Dolan"172- }173-174- - text: |175-176- The `|` operator in jq feeds the output of one filter (`.[0]` which gets177- the first element of the array in the response) into the input of another178- (`{...}` which builds an object out of those fields). You can access179- nested attributes, such as `.commit.message`.180-181- Now let's get the rest of the commits.182-183- - command: "jq '.[] | {message: .commit.message, name: .commit.committer.name}'"184- result: |185- {186- "message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",187- "name": "Stephen Dolan"188- }189- {190- "message": "Reject all overlong UTF8 sequences.",191- "name": "Stephen Dolan"192- }193- {194- "message": "Fix various UTF8 parsing bugs.\n\nIn particular, parse bad UTF8 by replacing the broken bits with U+FFFD\nand resychronise correctly after broken sequences.",195- "name": "Stephen Dolan"196- }197- {198- "message": "Fix example in manual for `floor`. See #155.",199- "name": "Stephen Dolan"200- }201- {202- "message": "Document floor",203- "name": "Nicolas Williams"204- }205-206- - text: |207-208- `.[]` returns each element of the array returned in the response, one at a209- time, which are all fed into210- `{message: .commit.message, name: .commit.committer.name}`.211-212- Data in jq is represented as streams of JSON values - every jq213- expression runs for each value in its input stream, and can214- produce any number of values to its output stream.215-216- Streams are serialised by just separating JSON values with217- whitespace. This is a `cat`-friendly format - you can just join218- two JSON streams together and get a valid JSON stream.219-220- If you want to get the output as a single array, you can tell jq to221- "collect" all of the answers by wrapping the filter in square222- brackets:223-224- - command: "jq '[.[] | {message: .commit.message, name: .commit.committer.name}]'"225- result: |226- [227- {228- "message": "Merge pull request #163 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",229- "name": "Stephen Dolan"230- },231- {232- "message": "Reject all overlong UTF8 sequences.",233- "name": "Stephen Dolan"234- },235- {236- "message": "Fix various UTF8 parsing bugs.\n\nIn particular, parse bad UTF8 by replacing the broken bits with U+FFFD\nand resychronise correctly after broken sequences.",237- "name": "Stephen Dolan"238- },239- {240- "message": "Fix example in manual for `floor`. See #155.",241- "name": "Stephen Dolan"242- },243- {244- "message": "Document floor",245- "name": "Nicolas Williams"246- }247- ]248-249- - text: |250-251- - - -252-253- Next, let's try getting the URLs of the parent commits out of the254- API results as well. In each commit, the GitHub API includes information255- about "parent" commits. There can be one or many.256-257- "parents": [258- {259- "sha": "54b9c9bdb225af5d886466d72f47eafc51acb4f7",260- "url": "https://api.github.com/repos/stedolan/jq/commits/54b9c9bdb225af5d886466d72f47eafc51acb4f7",261- "html_url": "https://github.com/stedolan/jq/commit/54b9c9bdb225af5d886466d72f47eafc51acb4f7"262- },263- {264- "sha": "8b1b503609c161fea4b003a7179b3fbb2dd4345a",265- "url": "https://api.github.com/repos/stedolan/jq/commits/8b1b503609c161fea4b003a7179b3fbb2dd4345a",266- "html_url": "https://github.com/stedolan/jq/commit/8b1b503609c161fea4b003a7179b3fbb2dd4345a"267- }268- ]269-270- We want to pull out all of the "html_url" fields inside that array of parent271- commits and make a simple list of strings to go along with the272- "message" and "author" fields we already have.273-274- - command: "jq '[.[] | {message: .commit.message, name: .commit.committer.name, parents: [.parents[].html_url]}]'"275- result: |276- [277- {278- "message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",279- "name": "Stephen Dolan",280- "parents": [281- "https://github.com/stedolan/jq/commit/54b9c9bdb225af5d886466d72f47eafc51acb4f7",282- "https://github.com/stedolan/jq/commit/8b1b503609c161fea4b003a7179b3fbb2dd4345a"283- ]284- },285- {286- "message": "Reject all overlong UTF8 sequences.",287- "name": "Stephen Dolan",288- "parents": [289- "https://github.com/stedolan/jq/commit/ff48bd6ec538b01d1057be8e93b94eef6914e9ef"290- ]291- },292- {293- "message": "Fix various UTF8 parsing bugs.\n\nIn particular, parse bad UTF8 by replacing the broken bits with U+FFFD\nand resychronise correctly after broken sequences.",294- "name": "Stephen Dolan",295- "parents": [296- "https://github.com/stedolan/jq/commit/54b9c9bdb225af5d886466d72f47eafc51acb4f7"297- ]298- },299- {300- "message": "Fix example in manual for `floor`. See #155.",301- "name": "Stephen Dolan",302- "parents": [303- "https://github.com/stedolan/jq/commit/3dcdc582ea993afea3f5503a78a77675967ecdfa"304- ]305- },306- {307- "message": "Document floor",308- "name": "Nicolas Williams",309- "parents": [310- "https://github.com/stedolan/jq/commit/7c4171d414f647ab08bcd20c76a4d8ed68d9c602"311- ]312- }313- ]314-315- - text: |316-317- Here we're making an object as before, but this time the `parents`318- field is being set to `[.parents[].html_url]`, which collects319- all of the parent commit URLs defined in the parents object.320-321- - text: |322-323- - - -324-325- Here endeth the tutorial! There's lots more to play with. Go326- read [the manual](../manual/) if you're interested, and [download327- jq](../download/) if you haven't already.deleted:docs/content/2.download/default.yml-193 removed
1-headline: Download jq2-body:3-4- - text: |5-6- jq is written in C and has no runtime dependencies, so it should be7- possible to build it for nearly any platform. Prebuilt binaries are8- available for Linux, OS X and Windows.9-10- The binaries should just run, but on OS X and Linux you may need11- to make them executable first using `chmod +x jq`.12-13- jq is licensed under the MIT license. For all of the gory14- details, read the file `COPYING` in the source distribution.15-16-17- ### Linux18-19- * jq 1.5 is in the official [Debian](https://packages.debian.org/jq) and20- [Ubuntu](http://packages.ubuntu.com/jq) repositories. Install using21- `sudo apt-get install jq`.22-23- * jq 1.5 is in the official24- [Fedora](http://pkgs.fedoraproject.org/cgit/jq.git/) repository.25- Install using `sudo dnf install jq`.26-27- * jq 1.4 is in the official [openSUSE](https://software.opensuse.org/package/jq)28- repository. Install using `sudo zypper install jq`.29-30- * jq 1.5 is in the official31- [Arch](https://www.archlinux.org/packages/?sort=&q=jq&maintainer=&flagged=)32- repository. Install using `sudo pacman -Sy jq`.33-34- * jq 1.6 binaries for35- [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64)36- or37- [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux32).38-39- * jq 1.5 binaries for40- [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64)41- or42- [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux32).43-44- * jq 1.4 binaries for45- [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-linux-x86_64)46- or47- [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-linux-x86).48-49- * jq 1.3 binaries for50- [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.3/jq-linux-x86_64)51- or52- [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.3/jq-linux-x86).53-54- ### OS X55-56- * Use [Homebrew](http://brew.sh/) to install jq 1.5 with57- `brew install jq`.58-59- * jq 1.6 binary for60- [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-osx-amd64).61-62- * jq 1.5 binary for63- [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-osx-amd64).64-65- * jq 1.4 binaries for66- [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-osx-x86_64)67- or68- [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-osx-x86).69-70- * jq 1.3 binaries for71- [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.3/jq-osx-x86_64)72- or73- [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.3/jq-osx-x86).74-75- ### FreeBSD76-77- * `pkg install jq` as root installs a pre-built78- [binary package](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/pkgng-intro.html).79-80- * `make -C /usr/ports/textproc/jq install clean` as root installs the81- [jq](https://www.freshports.org/textproc/jq/)82- [port](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/ports-using.html)83- from source.84-85- ### Solaris86-87- * `pkgutil -i jq` in [OpenCSW](https://www.opencsw.org/p/jq) for Solaris88- 10+, Sparc and x86.89-90- * jq 1.4 binaries for Solaris 1191- [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-solaris11-64)92- or93- [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-solaris11-32).94-95- ### Windows96-97- * Use [Chocolatey NuGet](https://chocolatey.org/) to install jq 1.5 with98- `chocolatey install jq`.99-100- * jq 1.6 executables for101- [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-win64.exe)102- or103- [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-win32.exe).104-105- * jq 1.5 executables for106- [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-win64.exe)107- or108- [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-win32.exe).109-110- * jq 1.4 executables for111- [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-win64.exe)112- or113- [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-win32.exe).114-115- * jq 1.3 executables for116- [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.3/jq-win64.exe)117- or118- [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.3/jq-win32.exe).119-120- ### Checksums and signatures121-122- SHA-256 checksums are provided for all release and pre-release binaries.123- They can be found under124- [sig/v1.x/sha256sum.txt](https://github.com/stedolan/jq/tree/master/sig).125- The checksums for jq 1.6 are in126- [sig/v1.6/sha256sum.txt](https://raw.githubusercontent.com/stedolan/jq/master/sig/v1.6/sha256sum.txt).127- The checksums for jq 1.5 are in128- [sig/v1.5/sha256sum.txt](https://raw.githubusercontent.com/stedolan/jq/master/sig/v1.5/sha256sum.txt).129-130- Additionally, all binaries are signed by the131- [jq Package Signing Key](https://raw.githubusercontent.com/stedolan/jq/master/sig/jq-release.key).132- The signatures can be found under133- [sig/v1.x/\*.asc](https://github.com/stedolan/jq/tree/master/sig).134- The signatures for jq 1.6 are in135- [sig/v1.5/\*.asc](https://github.com/stedolan/jq/tree/master/sig/v1.6).136- The signatures for jq 1.5 are in137- [sig/v1.5/\*.asc](https://github.com/stedolan/jq/tree/master/sig/v1.5).138- You can use [GnuPG](https://gnupg.org/) to verify a signature by downloading139- the signature and running `gpg --verify signature.asc`.140-141- ### From source on Linux, OS X, Cygwin, and other POSIX-like operating systems142-143- * [Source tarball for jq 1.6](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-1.6.tar.gz)144- * [Source tarball for jq 1.5](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-1.5.tar.gz)145-146- You can build it using the usual `./configure && make && sudo147- make install` rigmarole.148-149- If you're interested in using the lastest development version, try:150-151- git clone https://github.com/stedolan/jq.git152- cd jq153- autoreconf -i154- ./configure --disable-maintainer-mode155- make156- sudo make install157-158- To build it from a git clone, you'll need to install a few159- packages first:160-161- * [GCC](https://gcc.gnu.org)162- * [Make](https://www.gnu.org/software/make/)163- * [Autotools](https://www.gnu.org/software/automake/)164-165- For Linux systems, these will all be in your system's package166- manager, and if you do development on the machine they're most167- likely already installed.168-169- On OS X, these are all included in Apple's command line tools, which can170- be installed from [Xcode](https://developer.apple.com/xcode/). However,171- you may find that you need a newer version of Bison than the one provided172- by Apple. This can be found in [Homebrew](http://brew.sh) or173- [MacPorts](https://macports.org/).174-175- The `--disable-maintainer-mode` flag says to use the pre-generated lexer176- and parser that come with the code. To compile the lexer and parser also177- from source, leave out this flag. You will need to install178- [Flex](http://flex.sourceforge.net/) and179- [Bison](https://www.gnu.org/software/bison/).180-181- #### Building the documentation182-183- jq's documentation is compiled into static HTML using184- [Bonsai](http://www.tinytree.info). To view the documentation185- locally, run `rake serve` (or `bundle exec rake serve`) from the186- docs/ subdirectory. To build the docs just `rake build` from the187- docs subdirectory. You'll need a few Ruby dependencies, which can188- be installed by following the instructions in `docs/README.md`.189-190- The man page is built by `make jq.1`, or just `make`, also from191- the YAML docs, and you'll still need the Ruby dependencies to192- build the manpage.193-deleted:docs/content/3.manual/v1.3/manual.yml-1270 removed
1----2-headline: jq 1.3 Manual3-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 dividing the results.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- By default, `jq` reads a stream of JSON objects (whitespace51- separated) from `stdin`. One or more <files> may be specified, in52- which case `jq` will read input from those instead.53-54- The <options> are described in the [INVOKING JQ] section, they55- mostly concern input and output formatting. The <filter> is written56- in the jq language and specifies how to transform the input57- document.58-59- ## FILTERS60-61-manpage_epilogue: |62- ## BUGS63-64- Presumably. Report them or discuss them at:65-66- https://github.com/stedolan/jq/issues67-68- ## AUTHOR69-70- Stephen Dolan `<mu@netsoc.tcd.ie>`71-72-sections:73- - title: Invoking jq74- body: |75-76- jq filters run on a stream of JSON data. The input to jq is77- parsed as a sequence of whitespace-separated JSON values which78- are passed through the provided filter one at a time. The79- output(s) of the filter are written to standard out, again as a80- sequence of whitespace-separated JSON data.81-82- You can affect how jq reads and writes its input and output83- using some command-line options:84-85- * `--slurp`/`-s`:86-87- Instead of running the filter for each JSON object in the88- input, read the entire input stream into a large array and run89- the filter just once.90-91- * `--raw-input`/`-R`:92-93- Don't parse the input as JSON. Instead, each line of text is94- passed to the filter as a string. If combined with `--slurp`,95- then the entire input is passed to the filter as a single long96- string.97-98- * `--null-input`/`-n`:99-100- Don't read any input at all! Instead, the filter is run once101- using `null` as the input. This is useful when using jq as a102- simple calculator or to construct JSON data from scratch.103-104- * `--compact-output` / `-c`:105-106- By default, jq pretty-prints JSON output. Using this option107- will result in more compact output by instead putting each108- JSON object on a single line.109-110- * `--color-output` / `-C` and `--monochrome-output` / `-M`:111-112- By default, jq outputs colored JSON if writing to a113- terminal. You can force it to produce color even if writing to114- a pipe or a file using `-C`, and disable color with `-M`.115-116- * `--ascii-output` / `-a`:117-118- jq usually outputs non-ASCII Unicode codepoints as UTF-8, even119- if the input specified them as escape sequences (like120- "\u03bc"). Using this option, you can force jq to produce pure121- ASCII output with every non-ASCII character replaced with the122- equivalent escape sequence.123-124- * `--raw-output` / `-r`:125-126- With this option, if the filter's result is a string then it127- will be written directly to standard output rather than being128- formatted as a JSON string with quotes. This can be useful for129- making jq filters talk to non-JSON-based systems.130-131- * `--arg name value`:132-133- This option passes a value to the jq program as a predefined134- variable. If you run jq with `--arg foo bar`, then `$foo` is135- available in the program and has the value `"bar"`.136-137- - title: Basic filters138- entries:139- - title: "`.`"140- body: |141-142- The absolute simplest (and least interesting) filter143- is `.`. This is a filter that takes its input and144- produces it unchanged as output.145-146- Since jq by default pretty-prints all output, this trivial147- program can be a useful way of formatting JSON output from,148- say, `curl`.149-150- examples:151- - program: '.'152- input: '"Hello, world!"'153- output: ['"Hello, world!"']154-155- - title: "`.foo`"156- body: |157-158- The simplest *useful* filter is .foo. When given a159- JSON object (aka dictionary or hash) as input, it produces160- the value at the key "foo", or null if there's none present.161-162- examples:163- - program: '.foo'164- input: '{"foo": 42, "bar": "less interesting data"}'165- output: [42]166- - program: '.foo'167- input: '{"notfoo": true, "alsonotfoo": false}'168- output: ['null']169-170- - title: "`.[foo]`, `.[2]`, `.[10:15]`"171- body: |172-173- You can also look up fields of an object using syntax like174- `.["foo"]` (.foo above is a shorthand version of this). This175- one works for arrays as well, if the key is an176- integer. Arrays are zero-based (like javascript), so `.[2]`177- returns the third element of the array.178-179- The `.[10:15]` syntax can be used to return a subarray of an180- array. The array returned by `.[10:15]` will be of length 5,181- containing the elements from index 10 (inclusive) to index182- 15 (exclusive). Either index may be negative (in which case183- it counts backwards from the end of the array), or omitted184- (in which case it refers to the start or end of the array).185-186- examples:187- - program: '.[0]'188- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'189- output: ['{"name":"JSON", "good":true}']190-191- - program: '.[2]'192- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'193- output: ['null']194-195- - program: '.[2:4]'196- input: '["a","b","c","d","e"]'197- output: ['["c", "d"]']198-199- - program: '.[:3]'200- input: '["a","b","c","d","e"]'201- output: ['["a", "b", "c"]']202-203- - program: '.[-2:]'204- input: '["a","b","c","d","e"]'205- output: ['["d", "e"]']206-207- - title: "`.[]`"208- body: |209-210- If you use the `.[foo]` syntax, but omit the index211- entirely, it will return *all* of the elements of an212- array. Running `.[]` with the input `[1,2,3]` will produce the213- numbers as three separate results, rather than as a single214- array.215-216- You can also use this on an object, and it will return all217- the values of the object.218-219- examples:220- - program: '.[]'221- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'222- output:223- - '{"name":"JSON", "good":true}'224- - '{"name":"XML", "good":false}'225-226- - program: '.[]'227- input: '[]'228- output: []229-230- - program: '.[]'231- input: '{"a": 1, "b": 1}'232- output: ['1', '1']233-234- - title: "`,`"235- body: |236-237- If two filters are separated by a comma, then the238- input will be fed into both and there will be multiple239- outputs: first, all of the outputs produced by the left240- expression, and then all of the outputs produced by the241- right. For instance, filter `.foo, .bar`, produces242- both the "foo" fields and "bar" fields as separate outputs.243-244- examples:245- - program: '.foo, .bar'246- input: '{"foo": 42, "bar": "something else", "baz": true}'247- output: ['42', '"something else"']248-249- - program: ".user, .projects[]"250- input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'251- output: ['"stedolan"', '"jq"', '"wikiflow"']252-253- - program: '.[4,2]'254- input: '["a","b","c","d","e"]'255- output: ['"e"', '"c"']256-257- - title: "`|`"258- body: |259- The | operator combines two filters by feeding the output(s) of260- the one on the left into the input of the one on the right. It's261- pretty much the same as the Unix shell's pipe, if you're used to262- that.263-264- If the one on the left produces multiple results, the one on265- the right will be run for each of those results. So, the266- expression `.[] | .foo` retrieves the "foo" field of each267- element of the input array.268-269- examples:270- - program: '.[] | .name'271- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'272- output: ['"JSON"', '"XML"']273-274- - title: Types and Values275- body: |276-277- jq supports the same set of datatypes as JSON - numbers,278- strings, booleans, arrays, objects (which in JSON-speak are279- hashes with only string keys), and "null".280-281- Booleans, null, strings and numbers are written the same way as282- in javascript. Just like everything else in jq, these simple283- values take an input and produce an output - `42` is a valid jq284- expression that takes an input, ignores it, and returns 42285- instead.286-287- entries:288- - title: Array construction - `[]`289- body: |290-291- As in JSON, `[]` is used to construct arrays, as in292- `[1,2,3]`. The elements of the arrays can be any jq293- expression. All of the results produced by all of the294- expressions are collected into one big array. You can use it295- to construct an array out of a known quantity of values (as296- in `[.foo, .bar, .baz]`) or to "collect" all the results of a297- filter into an array (as in `[.items[].name]`)298-299- Once you understand the "," operator, you can look at jq's array300- syntax in a different light: the expression `[1,2,3]` is not using a301- built-in syntax for comma-separated arrays, but is instead applying302- the `[]` operator (collect results) to the expression 1,2,3 (which303- produces three different results).304-305- If you have a filter `X` that produces four results,306- then the expression `[X]` will produce a single result, an307- array of four elements.308-309- examples:310- - program: "[.user, .projects[]]"311- input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'312- output: ['["stedolan", "jq", "wikiflow"]']313- - title: Objects - `{}`314- body: |315-316- Like JSON, `{}` is for constructing objects (aka317- dictionaries or hashes), as in: `{"a": 42, "b": 17}`.318-319- If the keys are "sensible" (all alphabetic characters), then320- the quotes can be left off. The value can be any expression321- (although you may need to wrap it in parentheses if it's a322- complicated one), which gets applied to the {} expression's323- input (remember, all filters have an input and an324- output).325-326- {foo: .bar}327-328- will produce the JSON object `{"foo": 42}` if given the JSON329- object `{"bar":42, "baz":43}`. You can use this to select330- particular fields of an object: if the input is an object331- with "user", "title", "id", and "content" fields and you332- just want "user" and "title", you can write333-334- {user: .user, title: .title}335-336- Because that's so common, there's a shortcut syntax: `{user, title}`.337-338- If one of the expressions produces multiple results,339- multiple dictionaries will be produced. If the input's340-341- {"user":"stedolan","titles":["JQ Primer", "More JQ"]}342-343- then the expression344-345- {user, title: .titles[]}346-347- will produce two outputs:348-349- {"user":"stedolan", "title": "JQ Primer"}350- {"user":"stedolan", "title": "More JQ"}351-352- Putting parentheses around the key means it will be evaluated as an353- expression. With the same input as above,354-355- {(.user): .titles}356-357- produces358-359- {"stedolan": ["JQ Primer", "More JQ"]}360-361- examples:362- - program: '{user, title: .titles[]}'363- input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'364- output:365- - '{"user":"stedolan", "title": "JQ Primer"}'366- - '{"user":"stedolan", "title": "More JQ"}'367- - program: '{(.user): .titles}'368- input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'369- output: ['{"stedolan": ["JQ Primer", "More JQ"]}']370-371- - title: Builtin operators and functions372- body: |373-374- Some jq operator (for instance, `+`) do different things375- depending on the type of their arguments (arrays, numbers,376- etc.). However, jq never does implicit type conversions. If you377- try to add a string to an object you'll get an error message and378- no result.379-380- entries:381- - title: Addition - `+`382- body: |383-384- The operator `+` takes two filters, applies them both385- to the same input, and adds the results together. What386- "adding" means depends on the types involved:387-388- - **Numbers** are added by normal arithmetic.389-390- - **Arrays** are added by being concatenated into a larger array.391-392- - **Strings** are added by being joined into a larger string.393-394- - **Objects** are added by merging, that is, inserting all395- the key-value pairs from both objects into a single396- combined object. If both objects contain a value for the397- same key, the object on the right of the `+` wins.398-399- `null` can be added to any value, and returns the other400- value unchanged.401-402- examples:403- - program: '.a + 1'404- input: '{"a": 7}'405- output: ['8']406- - program: '.a + .b'407- input: '{"a": [1,2], "b": [3,4]}'408- output: ['[1,2,3,4]']409- - program: '.a + null'410- input: '{"a": 1}'411- output: ['1']412- - program: '.a + 1'413- input: '{}'414- output: ['1']415- - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'416- input: 'null'417- output: ['{"a": 42, "b": 2, "c": 3}']418-419- - title: Subtraction - `-`420- body: |421-422- As well as normal arithmetic subtraction on numbers, the `-`423- operator can be used on arrays to remove all occurences of424- the second array's elements from the first array.425-426- examples:427- - program: '4 - .a'428- input: '{"a":3}'429- output: ['1']430- - program: . - ["xml", "yaml"]431- input: '["xml", "yaml", "json"]'432- output: ['["json"]']433-434- - title: Multiplication, division - `*` and `/`435- body: |436-437- These operators only work on numbers, and do the expected.438-439- examples:440- - program: '10 / . * 3'441- input: 5442- output: [6]443-444- - title: `length`445- body: |446-447- The builtin function `length` gets the length of various448- different types of value:449-450- - The length of a **string** is the number of Unicode451- codepoints it contains (which will be the same as its452- JSON-encoded length in bytes if it's pure ASCII).453-454- - The length of an **array** is the number of elements.455-456- - The length of an **object** is the number of key-value pairs.457-458- - The length of **null** is zero.459-460- examples:461- - program: '.[] | length'462- input: '[[1,2], "string", {"a":2}, null]'463- output: [2, 6, 1, 0]464-465- - title: `keys`466- body: |467-468- The builtin function `keys`, when given an object, returns469- its keys in an array.470-471- The keys are sorted "alphabetically", by unicode codepoint472- order. This is not an order that makes particular sense in473- any particular language, but you can count on it being the474- same for any two objects with the same set of keys,475- regardless of locale settings.476-477- When `keys` is given an array, it returns the valid indices478- for that array: the integers from 0 to length-1.479-480- examples:481- - program: 'keys'482- input: '{"abc": 1, "abcd": 2, "Foo": 3}'483- output: ['["Foo", "abc", "abcd"]']484- - program: 'keys'485- input: '[42,3,35]'486- output: ['[0,1,2]']487-488- - title: `has`489- body: |490-491- The builtin function `has` returns whether the input object492- has the given key, or the input array has an element at the493- given index.494-495- `has($key)` has the same effect as checking whether `$key`496- is a member of the array returned by `keys`, although `has`497- will be faster.498-499- examples:500- - program: 'map(has("foo"))'501- input: '[{"foo": 42}, {}]'502- output: ['[true, false]']503- - program: 'map(has(2))'504- input: '[[0,1], ["a","b","c"]]'505- output: ['[false, true]']506-507- - title: `to_entries`, `from_entries`, `with_entries`508- body: |509-510- These functions convert between an object and an array of511- key-value pairs. If `to_entries` is passed an object, then512- for each `k: v` entry in the input, the output array513- includes `{"key": k, "value": v}`.514-515- `from_entries` does the opposite conversion, and516- `with_entries(foo)` is a shorthand for `to_entries |517- map(foo) | from_entries`, useful for doing some operation to518- all keys and values of an object.519-520- examples:521- - program: 'to_entries'522- input: '{"a": 1, "b": 2}'523- output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']524- - program: 'from_entries'525- input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'526- output: ['{"a": 1, "b": 2}']527- - program: 'with_entries(.key |= "KEY_" + .)'528- input: '{"a": 1, "b": 2}'529- output: ['{"KEY_a": 1, "KEY_b": 2}']530-531-532- - title: `select`533- body: |534-535- The function `select(foo)` produces its input unchanged if536- `foo` returns true for that input, and produces no output537- otherwise.538-539- It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`540- will give you `[3]`.541-542- examples:543- - program: 'map(select(. >= 2))'544- input: '[1,5,3,0,7]'545- output: ['[5,3,7]']546-547- - title: `empty`548- body: |549-550- `empty` returns no results. None at all. Not even `null`.551-552- It's useful on occasion. You'll know if you need it :)553-554- examples:555- - program: '1, empty, 2'556- input: 'null'557- output: [1, 2]558- - program: '[1,2,empty,3]'559- input: 'null'560- output: ['[1,2,3]']561-562- - title: `map(x)`563- body: |564-565- For any filter `x`, `map(x)` will run that filter for each566- element of the input array, and produce the outputs a new567- array. `map(.+1)` will increment each element of an array of numbers.568-569- `map(x)` is equivalent to `[.[] | x]`. In fact, this is how570- it's defined.571-572- examples:573- - program: 'map(.+1)'574- input: '[1,2,3]'575- output: ['[2,3,4]']576-577- - title: `add`578- body: |579-580- The filter `add` takes as input an array, and produces as581- output the elements of the array added together. This might582- mean summed, concatenated or merged depending on the types583- of the elements of the input array - the rules are the same584- as those for the `+` operator (described above).585-586- If the input is an empty array, `add` returns `null`.587-588- examples:589- - program: add590- input: '["a","b","c"]'591- output: ['"abc"']592- - program: add593- input: '[1, 2, 3]'594- output: [6]595- - program: add596- input: '[]'597- output: ["null"]598-599- - title: `range`600- body: |601-602- The `range` function produces a range of numbers. `range(4;10)`603- produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers604- are produced as separate outputs. Use `[range(4;10)]` to get a range as605- an array.606-607- examples:608- - program: 'range(2;4)'609- input: 'null'610- output: ['2', '3']611- - program: '[range(2;4)]'612- input: 'null'613- output: ['[2,3]']614-615- - title: `tonumber`616- body: |617-618- The `tonumber` function parses its input as a number. It619- will convert correctly-formatted strings to their numeric620- equivalent, leave numbers alone, and give an error on all other input.621-622- examples:623- - program: '.[] | tonumber'624- input: '[1, "1"]'625- output: [1, 1]626-627- - title: `tostring`628- body: |629-630- The `tostring` function prints its input as a631- string. Strings are left unchanged, and all other values are632- JSON-encoded.633-634- examples:635- - program: '.[] | tostring'636- input: '[1, "1", [1]]'637- output: ['"1"', '"1"', '"[1]"']638-639- - title: `type`640- body: |641-642- The `type` function returns the type of its argument as a643- string, which is one of null, boolean, number, string, array644- or object.645-646- examples:647- - program: 'map(type)'648- input: '[0, false, [], {}, null, "hello"]'649- output: ['["number", "boolean", "array", "object", "null", "string"]']650-651- - title: `sort, sort_by`652- body: |653-654- The `sort` functions sorts its input, which must be an655- array. Values are sorted in the following order:656-657- * `null`658- * `false`659- * `true`660- * numbers661- * strings, in alphabetical order (by unicode codepoint value)662- * arrays, in lexical order663- * objects664-665- The ordering for objects is a little complex: first they're666- compared by comparing their sets of keys (as arrays in667- sorted order), and if their keys are equal then the values668- are compared key by key.669-670- `sort_by` may be used to sort by a particular field of an671- object, or by applying any jq filter. `sort_by(foo)`672- compares two elements by comparing the result of `foo` on673- each element.674-675- examples:676- - program: 'sort'677- input: '[8,3,null,6]'678- output: ['[null,3,6,8]']679- - program: 'sort_by(.foo)'680- input: '[{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}]'681- output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']682-683- - title: `group_by`684- body: |685-686- `group_by(.foo)` takes as input an array, groups the687- elements having the same `.foo` field into separate arrays,688- and produces all of these arrays as elements of a larger689- array, sorted by the value of the `.foo` field.690-691- Any jq expression, not just a field access, may be used in692- place of `.foo`. The sorting order is the same as described693- in the `sort` function above.694-695- examples:696- - program: 'group_by(.foo)'697- input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'698- output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']699-700- - title: `min`, `max`, `min_by`, `max_by`701- body: |702-703- Find the minimum or maximum element of the input array. The704- `_by` versions allow you to specify a particular field or705- property to examine, e.g. `min_by(.foo)` finds the object706- with the smallest `foo` field.707-708- examples:709- - program: 'min'710- input: '[5,4,2,7]'711- output: ['2']712- - program: 'max_by(.foo)'713- input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'714- output: ['{"foo":2, "bar":3}']715-716- - title: `unique`717- body: |718-719- The `unique` function takes as input an array and produces720- an array of the same elements, in sorted order, with721- duplicates removed.722-723- examples:724- - program: 'unique'725- input: '[1,2,5,3,5,3,1,3]'726- output: ['[1,2,3,5]']727-728- - title: `reverse`729- body: |730-731- This function reverses an array.732-733- examples:734- - program: 'reverse'735- input: '[1,2,3,4]'736- output: ['[4,3,2,1]']737-738- - title: `contains`739- body: |740-741- The filter `contains(b)` will produce true if b is742- completely contained within the input. A string B is743- contained in a string A if B is a substring of A. An array B744- is contained in an array A is all elements in B are745- contained in any element in A. An object B is contained in746- object A if all of the values in B are contained in the747- value in A with the same key. All other types are assumed to748- be contained in each other if they are equal.749-750- examples:751- - program: 'contains("bar")'752- input: '"foobar"'753- output: ['true']754- - program: 'contains(["baz", "bar"])'755- input: '["foobar", "foobaz", "blarp"]'756- output: ['true']757- - program: 'contains(["bazzzzz", "bar"])'758- input: '["foobar", "foobaz", "blarp"]'759- output: ['false']760- - program: 'contains({foo: 12, bar: [{barp: 12}]})'761- input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'762- output: ['true']763- - program: 'contains({foo: 12, bar: [{barp: 15}]})'764- input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'765- output: ['false']766-767- - title: `recurse`768- body: |769-770- The `recurse` function allows you to search through a771- recursive structure, and extract interesting data from all772- levels. Suppose your input represents a filesystem:773-774- {"name": "/", "children": [775- {"name": "/bin", "children": [776- {"name": "/bin/ls", "children": []},777- {"name": "/bin/sh", "children": []}]},778- {"name": "/home", "children": [779- {"name": "/home/stephen", "children": [780- {"name": "/home/stephen/jq", "children": []}]}]}]}781-782- Now suppose you want to extract all of the filenames783- present. You need to retrieve `.name`, `.children[].name`,784- `.children[].children[].name`, and so on. You can do this785- with:786-787- recurse(.children[]) | .name788-789- examples:790- - program: 'recurse(.foo[])'791- input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'792- output:793- - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'794- - '{"foo":[]}'795- - '{"foo":[{"foo":[]}]}'796- - '{"foo":[]}'797-798-799- - title: "String interpolation - `\(foo)`"800- body: |801-802- Inside a string, you can put an expression inside parens803- after a backslash. Whatever the expression returns will be804- interpolated into the string.805-806- examples:807- - program: '"The input was \(.), which is one less than \(.+1)"'808- input: '42'809- output: ['"The input was 42, which is one less than 43"']810-811- - title: "Format strings and escaping"812- body: |813-814- The `@foo` syntax is used to format and escape strings,815- which is useful for building URLs, documents in a language816- like HTML or XML, and so forth. `@foo` can be used as a817- filter on its own, the possible escapings are:818-819- * `@text`:820-821- Calls `tostring`, see that function for details.822-823- * `@json`:824-825- Serialises the input as JSON.826-827- * `@html`:828-829- Applies HTML/XML escaping, by mapping the characters830- `<>&'"` to their entity equivalents `<`, `>`,831- `&`, `'`, `"`.832-833- * `@uri`:834-835- Applies percent-encoding, by mapping all reserved URI836- characters to a `%xx` sequence.837-838- * `@csv`:839-840- The input must be an array, and it is rendered as CSV841- with double quotes for strings, and quotes escaped by842- repetition.843-844- * `@sh`:845-846- The input is escaped suitable for use in a command-line847- for a POSIX shell. If the input is an array, the output848- will be a series of space-separated strings.849-850- * `@base64`:851-852- The input is converted to base64 as specified by RFC 4648.853-854- This syntax can be combined with string interpolation in a855- useful way. You can follow a `@foo` token with a string856- literal. The contents of the string literal will *not* be857- escaped. However, all interpolations made inside that string858- literal will be escaped. For instance,859-860- @uri "https://www.google.com/search?q=\(.search)"861-862- will produce the following output for the input863- `{"search":"jq!"}`:864-865- https://www.google.com/search?q=jq%21866-867- Note that the slashes, question mark, etc. in the URL are868- not escaped, as they were part of the string literal.869-870- examples:871- - program: '@html'872- input: '"This works if x < y"'873- output: ['"This works if x < y"']874-875-# - program: '@html "<span>Anonymous said: \(.)</span>"'876-# input: '"<script>alert(\"lol hax\");</script>"'877-# output: ["<span>Anonymous said: <script>alert("lol hax");</script></span>"]878-879- - program: '@sh "echo \(.)"'880- input: "\"O'Hara's Ale\""881- output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]882-883- - title: Conditionals and Comparisons884- entries:885- - title: `==`, `!=`886- body: |887-888- The expression 'a == b' will produce 'true' if the result of a and b889- are equal (that is, if they represent equivalent JSON documents) and890- 'false' otherwise. In particular, strings are never considered equal891- to numbers. If you're coming from Javascript, jq's == is like892- Javascript's === - considering values equal only when they have the893- same type as well as the same value.894-895- != is "not equal", and 'a != b' returns the opposite value of 'a == b'896-897- examples:898- - program: '.[] == 1'899- input: '[1, 1.0, "1", "banana"]'900- output: ['true', 'true', 'false', 'false']901- - title: if-then-else902- body: |903-904- `if A then B else C end` will act the same as `B` if `A`905- produces a value other than false or null, but act the same906- as `C` otherwise.907-908- Checking for false or null is a simpler notion of909- "truthiness" than is found in Javascript or Python, but it910- means that you'll sometimes have to be more explicit about911- the condition you want: you can't test whether, e.g. a912- string is empty using `if .name then A else B end`, you'll913- need something more like `if (.name | count) > 0 then A else914- B end` instead.915-916- If the condition `A` produces multiple results, then `B` is evaluated917- once for each result that is not false or null, and `C` is evaluated918- once for each false or null.919-920- More cases can be added to an if using `elif A then B` syntax.921-922- examples:923- - program: |-924- if . == 0 then925- "zero"926- elif . == 1 then927- "one"928- else929- "many"930- end931- input: 2932- output: ['"many"']933-934- - title: `>, >=, <=, <`935- body: |936-937- The comparison operators `>`, `>=`, `<=`, `<` return whether938- their left argument is greater than, greater than or equal939- to, less than or equal to or less than their right argument940- (respectively).941-942- The ordering is the same as that described for `sort`, above.943-944- examples:945- - program: '. < 5'946- input: 2947- output: ['true']948-949- - title: and/or/not950- body: |951-952- jq supports the normal Boolean operators and/or/not. They have the953- same standard of truth as if expressions - false and null are954- considered "false values", and anything else is a "true value".955-956- If an operand of one of these operators produces multiple957- results, the operator itself will produce a result for each input.958-959- `not` is in fact a builtin function rather than an operator,960- so it is called as a filter to which things can be piped961- rather than with special syntax, as in `.foo and .bar |962- not`.963-964- These three only produce the values "true" and "false", and965- so are only useful for genuine Boolean operations, rather966- than the common Perl/Python/Ruby idiom of967- "value_that_may_be_null or default". If you want to use this968- form of "or", picking between two values rather than969- evaluating a condition, see the "//" operator below.970-971- examples:972- - program: '42 and "a string"'973- input: 'null'974- output: ['true']975- - program: '(true, false) or false'976- input: 'null'977- output: ['true', 'false']978-# - program: '(true, false) and (true, false)'979-# input: 'null'980-# output: ['true', 'false', 'false', 'false']981- - program: '(true, true) and (true, false)'982- input: 'null'983- output: ['true', 'false', 'true', 'false']984- - program: '[true, false | not]'985- input: 'null'986- output: ['[false, true]']987-988- - title: Alternative operator - `//`989- body: |990-991- A filter of the form `a // b` produces the same992- results as `a`, if `a` produces results other than `false`993- and `null`. Otherwise, `a // b` produces the same results as `b`.994-995- This is useful for providing defaults: `.foo // 1` will996- evaluate to `1` if there's no `.foo` element in the997- input. It's similar to how `or` is sometimes used in Python998- (jq's `or` operator is reserved for strictly Boolean999- operations).1000-1001- examples:1002- - program: '.foo // 42'1003- input: '{"foo": 19}'1004- output: [19]1005- - program: '.foo // 42'1006- input: '{}'1007- output: [42]1008-1009- - title: Advanced features1010- body: |1011- Variables are an absolute necessity in most programming languages, but1012- they're relegated to an "advanced feature" in jq.1013-1014- In most languages, variables are the only means of passing around1015- data. If you calculate a value, and you want to use it more than once,1016- you'll need to store it in a variable. To pass a value to another part1017- of the program, you'll need that part of the program to define a1018- variable (as a function parameter, object member, or whatever) in1019- which to place the data.1020-1021- It is also possible to define functions in jq, although this is1022- is a feature whose biggest use is defining jq's standard library1023- (many jq functions such as `map` and `find` are in fact written1024- in jq).1025-1026- Finally, jq has a `reduce` operation, which is very powerful but a1027- bit tricky. Again, it's mostly used internally, to define some1028- useful bits of jq's standard library.1029-1030- entries:1031- - title: Variables1032- body: |1033-1034- In jq, all filters have an input and an output, so manual1035- plumbing is not necessary to pass a value from one part of a program1036- to the next. Many expressions, for instance `a + b`, pass their input1037- to two distinct subexpressions (here `a` and `b` are both passed the1038- same input), so variables aren't usually necessary in order to use a1039- value twice.1040-1041- For instance, calculating the average value of an array of numbers1042- requires a few variables in most languages - at least one to hold the1043- array, perhaps one for each element or for a loop counter. In jq, it's1044- simply `add / length` - the `add` expression is given the array and1045- produces its sum, and the `length` expression is given the array and1046- produces its length.1047-1048- So, there's generally a cleaner way to solve most problems in jq that1049- defining variables. Still, sometimes they do make things easier, so jq1050- lets you define variables using `expression as $variable`. All1051- variable names start with `$`. Here's a slightly uglier version of the1052- array-averaging example:1053-1054- length as $array_length | add / $array_length1055-1056- We'll need a more complicated problem to find a situation where using1057- variables actually makes our lives easier.1058-1059-1060- Suppose we have an array of blog posts, with "author" and "title"1061- fields, and another object which is used to map author usernames to1062- real names. Our input looks like:1063-1064- {"posts": [{"title": "Frist psot", "author": "anon"},1065- {"title": "A well-written article", "author": "person1"}],1066- "realnames": {"anon": "Anonymous Coward",1067- "person1": "Person McPherson"}}1068-1069- We want to produce the posts with the author field containing a real1070- name, as in:1071-1072- {"title": "Frist psot", "author": "Anonymous Coward"}1073- {"title": "A well-written article", "author": "Person McPherson"}1074-1075- We use a variable, $names, to store the realnames object, so that we1076- can refer to it later when looking up author usernames:1077-1078- .realnames as $names | .posts[] | {title, author: $names[.author]}1079-1080- The expression `exp as $x | ...` means: for each value of expression1081- `exp`, run the rest of the pipeline with the entire original input, and1082- with `$x` set to that value. Thus `as` functions as something of a1083- foreach loop.1084-1085- Variables are scoped over the rest of the expression that defines1086- them, so1087-1088- .realnames as $names | (.posts[] | {title, author: $names[.author]})1089-1090- will work, but1091-1092- (.realnames as $names | .posts[]) | {title, author: $names[.author]}1093-1094- won't.1095-1096- examples:1097- - program: '.bar as $x | .foo | . + $x'1098- input: '{"foo":10, "bar":200}'1099- output: ['210']1100-1101- - title: 'Defining Functions'1102- body: |1103-1104- You can give a filter a name using "def" syntax:1105-1106- def increment: . + 1;1107-1108- From then on, `increment` is usable as a filter just like a1109- builtin function (in fact, this is how some of the builtins1110- are defined). A function may take arguments:1111-1112- def map(f): [.[] | f];1113-1114- Arguments are passed as filters, not as values. The1115- same argument may be referenced multiple times with1116- different inputs (here `f` is run for each element of the1117- input array). Arguments to a function work more like1118- callbacks than like value arguments.1119-1120- If you want the value-argument behaviour for defining simple1121- functions, you can just use a variable:1122-1123- def addvalue(f): f as $value | map(. + $value);1124-1125- With that definition, `addvalue(.foo)` will add the current1126- input's `.foo` field to each element of the array.1127-1128- examples:1129- - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'1130- input: '[[1,2],[10,20]]'1131- output: ['[[1,2,1], [10,20,10]]']1132- - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'1133- input: '[[1,2],[10,20]]'1134- output: ['[[1,2,1,2], [10,20,1,2]]']1135-1136- - title: Reduce1137- body: |1138-1139- The `reduce` syntax in jq allows you to combine all of the1140- results of an expression by accumulating them into a single1141- answer. As an example, we'll pass `[3,2,1]` to this expression:1142-1143- reduce .[] as $item (0; . + $item)1144-1145- For each result that `.[]` produces, `. + $item` is run to1146- accumulate a running total, starting from 0. In this1147- example, `.[]` produces the results 3, 2, and 1, so the1148- effect is similar to running something like this:1149-1150- 0 | (3 as $item | . + $item) |1151- (2 as $item | . + $item) |1152- (1 as $item | . + $item)1153-1154- examples:1155- - program: 'reduce .[] as $item (0; . + $item)'1156- input: '[10,2,5,3]'1157- output: ['20']1158-1159-1160- - title: Assignment1161- body: |1162-1163- Assignment works a little differently in jq than in most1164- programming languages. jq doesn't distinguish between references1165- to and copies of something - two objects or arrays are either1166- equal or not equal, without any further notion of being "the1167- same object" or "not the same object".1168-1169- If an object has two fields which are arrays, `.foo` and `.bar`,1170- and you append something to `.foo`, then `.bar` will not get1171- bigger. Even if you've just set `.bar = .foo`. If you're used to1172- programming in languages like Python, Java, Ruby, Javascript,1173- etc. then you can think of it as though jq does a full deep copy1174- of every object before it does the assignment (for performance,1175- it doesn't actually do that, but that's the general idea).1176-1177- entries:1178- - title: "`=`"1179- body: |1180-1181- The filter `.foo = 1` will take as input an object1182- and produce as output an object with the "foo" field set to1183- 1. There is no notion of "modifying" or "changing" something1184- in jq - all jq values are immutable. For instance,1185-1186- .foo = .bar | .foo.baz = 11187-1188- will not have the side-effect of setting .bar.baz to be set1189- to 1, as the similar-looking program in Javascript, Python,1190- Ruby or other languages would. Unlike these languages (but1191- like Haskell and some other functional languages), there is1192- no notion of two arrays or objects being "the same array" or1193- "the same object". They can be equal, or not equal, but if1194- we change one of them in no circumstances will the other1195- change behind our backs.1196-1197- This means that it's impossible to build circular values in1198- jq (such as an array whose first element is itself). This is1199- quite intentional, and ensures that anything a jq program1200- can produce can be represented in JSON.1201-1202- - title: "`|=`"1203- body: |1204- As well as the assignment operator '=', jq provides the "update"1205- operator '|=', which takes a filter on the right-hand side and1206- works out the new value for the property being assigned to by running1207- the old value through this expression. For instance, .foo |= .+1 will1208- build an object with the "foo" field set to the input's "foo" plus 1.1209-1210- This example should show the difference between '=' and '|=':1211-1212- Provide input '{"a": {"b": 10}, "b": 20}' to the programs:1213-1214- .a = .b1215- .a |= .b1216-1217- The former will set the "a" field of the input to the "b" field of the1218- input, and produce the output {"a": 20}. The latter will set the "a"1219- field of the input to the "a" field's "b" field, producing {"a": 10}.1220-1221- - title: "`+=`, `-=`, `*=`, `/=`, `//=`"1222- body: |1223-1224- jq has a few operators of the form `a op= b`, which are all1225- equivalent to `a |= . op b`. So, `+= 1` can be used to increment values.1226-1227- examples:1228- - program: .foo += 11229- input: '{"foo": 42}'1230- output: ['{"foo": 43}']1231-1232- - title: Complex assignments1233- body: |1234- Lots more things are allowed on the left-hand side of a jq assignment1235- than in most langauges. We've already seen simple field accesses on1236- the left hand side, and it's no surprise that array accesses work just1237- as well:1238-1239- .posts[0].title = "JQ Manual"1240-1241- What may come as a surprise is that the expression on the left may1242- produce multiple results, referring to different points in the input1243- document:1244-1245- .posts[].comments |= . + ["this is great"]1246-1247- That example appends the string "this is great" to the "comments"1248- array of each post in the input (where the input is an object with a1249- field "posts" which is an array of posts).1250-1251- When jq encounters an assignment like 'a = b', it records the "path"1252- taken to select a part of the input document while executing a. This1253- path is then used to find which part of the input to change while1254- executing the assignment. Any filter may be used on the1255- left-hand side of an equals - whichever paths it selects from the1256- input will be where the assignment is performed.1257-1258- This is a very powerful operation. Suppose we wanted to add a comment1259- to blog posts, using the same "blog" input above. This time, we only1260- want to comment on the posts written by "stedolan". We can find those1261- posts using the "select" function described earlier:1262-1263- .posts[] | select(.author == "stedolan")1264-1265- The paths provided by this operation point to each of the posts that1266- "stedolan" wrote, and we can comment on each of them in the same way1267- that we did before:1268-1269- (.posts[] | select(.author == "stedolan") | .comments) |=1270- . + ["terrible."]deleted:docs/content/3.manual/v1.4/manual.yml-1672 removed
1----2-headline: jq 1.4 Manual3-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 dividing the results.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- By default, `jq` reads a stream of JSON objects (whitespace51- separated) from `stdin`. One or more <files> may be specified, in52- which case `jq` will read input from those instead.53-54- The <options> are described in the [INVOKING JQ] section, they55- mostly concern input and output formatting. The <filter> is written56- in the jq language and specifies how to transform the input57- document.58-59- ## FILTERS60-61-manpage_epilogue: |62- ## BUGS63-64- Presumably. Report them or discuss them at:65-66- https://github.com/stedolan/jq/issues67-68- ## AUTHOR69-70- Stephen Dolan `<mu@netsoc.tcd.ie>`71-72-sections:73- - title: Invoking jq74- body: |75-76- jq filters run on a stream of JSON data. The input to jq is77- parsed as a sequence of whitespace-separated JSON values which78- are passed through the provided filter one at a time. The79- output(s) of the filter are written to standard out, again as a80- sequence of whitespace-separated JSON data.81-82- Note: it is important to mind the shell's quoting rules. As a83- general rule it's best to always quote (with single-quote84- characters) the jq program, as too many characters with special85- meaning to jq are also shell meta-characters. For example, `jq86- "foo"` will fail on most Unix shells because that will be the same87- as `jq foo`, which will generally fail because `foo is not88- defined`. When using the Windows command shell (cmd.exe) it's89- best to use double quotes around your jq program when given on the90- command-line (instead of the `-f program-file` option), but then91- double-quotes in the jq program need backslash escaping.92-93- You can affect how jq reads and writes its input and output94- using some command-line options:95-96- * `--version`:97-98- Output the jq version and exit with zero.99-100- * `--slurp`/`-s`:101-102- Instead of running the filter for each JSON object in the103- input, read the entire input stream into a large array and run104- the filter just once.105-106- * `--online-input`/`-I`:107-108- When the top-level input value is an array produce its elements109- instead of the array. This allows on-line processing of110- potentially very large top-level arrays' elements.111-112- * `--raw-input`/`-R`:113-114- Don't parse the input as JSON. Instead, each line of text is115- passed to the filter as a string. If combined with `--slurp`,116- then the entire input is passed to the filter as a single long117- string.118-119- * `--null-input`/`-n`:120-121- Don't read any input at all! Instead, the filter is run once122- using `null` as the input. This is useful when using jq as a123- simple calculator or to construct JSON data from scratch.124-125- * `--compact-output` / `-c`:126-127- By default, jq pretty-prints JSON output. Using this option128- will result in more compact output by instead putting each129- JSON object on a single line.130-131- * `--color-output` / `-C` and `--monochrome-output` / `-M`:132-133- By default, jq outputs colored JSON if writing to a134- terminal. You can force it to produce color even if writing to135- a pipe or a file using `-C`, and disable color with `-M`.136-137- * `--ascii-output` / `-a`:138-139- jq usually outputs non-ASCII Unicode codepoints as UTF-8, even140- if the input specified them as escape sequences (like141- "\u03bc"). Using this option, you can force jq to produce pure142- ASCII output with every non-ASCII character replaced with the143- equivalent escape sequence.144-145- * `--unbuffered`146-147- Flush the output after each JSON object is printed (useful if148- you're piping a slow data source into jq and piping jq's149- output elsewhere).150-151- * `--sort-keys` / `-S`:152-153- Output the fields of each object with the keys in sorted order.154-155- * `--raw-output` / `-r`:156-157- With this option, if the filter's result is a string then it158- will be written directly to standard output rather than being159- formatted as a JSON string with quotes. This can be useful for160- making jq filters talk to non-JSON-based systems.161-162- * `-f filename` / `--from-file filename`:163-164- Read filter from the file rather than from a command line, like165- awk's -f option. You can also use '#' to make comments.166-167- * `-e` / `--exit-status`:168-169- Sets the exit status of jq to 0 if the last output values was170- neither `false` nor `null`, 1 if the last output value was171- either `false` or `null`, or 4 if no valid result was ever172- produced. Normally jq exits with 2 if there was any usage173- problem or system error, 3 if there was a jq program compile174- error, or 0 if the jq program ran.175-176- * `--arg name value`:177-178- This option passes a value to the jq program as a predefined179- variable. If you run jq with `--arg foo bar`, then `$foo` is180- available in the program and has the value `"bar"`.181-182- * `--argfile name filename`:183-184- This option passes the first value from the named file as a185- value to the jq program as a predefined variable. If you run jq186- with `--argfile foo bar`, then `$foo` is available in the187- program and has the value resulting from parsing the content of188- the file named `bar`.189-190- - title: Basic filters191- entries:192- - title: "`.`"193- body: |194-195- The absolute simplest (and least interesting) filter196- is `.`. This is a filter that takes its input and197- produces it unchanged as output.198-199- Since jq by default pretty-prints all output, this trivial200- program can be a useful way of formatting JSON output from,201- say, `curl`.202-203- examples:204- - program: '.'205- input: '"Hello, world!"'206- output: ['"Hello, world!"']207-208- - title: "`.foo`, `.foo.bar`"209- body: |210-211- The simplest *useful* filter is `.foo`. When given a212- JSON object (aka dictionary or hash) as input, it produces213- the value at the key "foo", or null if there's none present.214-215- If the key contains special characters, you need to surround216- it with double quotes like this: `."foo$"`.217-218- A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.219-220- examples:221- - program: '.foo'222- input: '{"foo": 42, "bar": "less interesting data"}'223- output: [42]224- - program: '.foo'225- input: '{"notfoo": true, "alsonotfoo": false}'226- output: ['null']227- - program: '.["foo"]'228- input: '{"foo": 42}'229- output: [42]230-231- - title: "`.foo?`"232- body: |233-234- Just like `.foo`, but does not output even an error when `.`235- is not an array or an object.236-237- examples:238- - program: '.foo?'239- input: '{"foo": 42, "bar": "less interesting data"}'240- output: [42]241- - program: '.foo?'242- input: '{"notfoo": true, "alsonotfoo": false}'243- output: ['null']244- - program: '.["foo"]?'245- input: '{"foo": 42}'246- output: [42]247- - program: '[.foo?]'248- input: '[1,2]'249- output: ['[]']250-251- - title: "`.[<string>]`, `.[2]`, `.[10:15]`"252- body: |253-254- You can also look up fields of an object using syntax like255- `.["foo"]` (.foo above is a shorthand version of this). This256- one works for arrays as well, if the key is an257- integer. Arrays are zero-based (like javascript), so `.[2]`258- returns the third element of the array.259-260- The `.[10:15]` syntax can be used to return a subarray of an261- array or substring of a string. The array returned by262- `.[10:15]` will be of length 5, containing the elements from263- index 10 (inclusive) to index 15 (exclusive). Either index may264- be negative (in which case it counts backwards from the end of265- the array), or omitted (in which case it refers to the start266- or end of the array).267-268- The `?` "operator" can also be used with the slice operator,269- as in `.[10:15]?`, which outputs values where the inputs are270- slice-able.271-272- examples:273- - program: '.[0]'274- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'275- output: ['{"name":"JSON", "good":true}']276-277- - program: '.[2]'278- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'279- output: ['null']280-281- - program: '.[2:4]'282- input: '["a","b","c","d","e"]'283- output: ['["c", "d"]']284-285- - program: '.[2:4]'286- input: '"abcdefghi"'287- output: ['"cd"']288-289- - program: '.[:3]'290- input: '["a","b","c","d","e"]'291- output: ['["a", "b", "c"]']292-293- - program: '.[-2:]'294- input: '["a","b","c","d","e"]'295- output: ['["d", "e"]']296-297- - title: "`.[]`"298- body: |299-300- If you use the `.[index]` syntax, but omit the index301- entirely, it will return *all* of the elements of an302- array. Running `.[]` with the input `[1,2,3]` will produce the303- numbers as three separate results, rather than as a single304- array.305-306- You can also use this on an object, and it will return all307- the values of the object.308-309- examples:310- - program: '.[]'311- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'312- output:313- - '{"name":"JSON", "good":true}'314- - '{"name":"XML", "good":false}'315-316- - program: '.[]'317- input: '[]'318- output: []319-320- - program: '.[]'321- input: '{"a": 1, "b": 1}'322- output: ['1', '1']323-324- - title: "`.[]?`"325- body: |326-327- Like `.[]`, but no errors will be output if . is not an array328- or object.329-330- - title: "`,`"331- body: |332-333- If two filters are separated by a comma, then the334- input will be fed into both and there will be multiple335- outputs: first, all of the outputs produced by the left336- expression, and then all of the outputs produced by the337- right. For instance, filter `.foo, .bar`, produces338- both the "foo" fields and "bar" fields as separate outputs.339-340- examples:341- - program: '.foo, .bar'342- input: '{"foo": 42, "bar": "something else", "baz": true}'343- output: ['42', '"something else"']344-345- - program: ".user, .projects[]"346- input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'347- output: ['"stedolan"', '"jq"', '"wikiflow"']348-349- - program: '.[4,2]'350- input: '["a","b","c","d","e"]'351- output: ['"e"', '"c"']352-353- - title: "`|`"354- body: |355- The | operator combines two filters by feeding the output(s) of356- the one on the left into the input of the one on the right. It's357- pretty much the same as the Unix shell's pipe, if you're used to358- that.359-360- If the one on the left produces multiple results, the one on361- the right will be run for each of those results. So, the362- expression `.[] | .foo` retrieves the "foo" field of each363- element of the input array.364-365- examples:366- - program: '.[] | .name'367- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'368- output: ['"JSON"', '"XML"']369-370- - title: Types and Values371- body: |372-373- jq supports the same set of datatypes as JSON - numbers,374- strings, booleans, arrays, objects (which in JSON-speak are375- hashes with only string keys), and "null".376-377- Booleans, null, strings and numbers are written the same way as378- in javascript. Just like everything else in jq, these simple379- values take an input and produce an output - `42` is a valid jq380- expression that takes an input, ignores it, and returns 42381- instead.382-383- entries:384- - title: Array construction - `[]`385- body: |386-387- As in JSON, `[]` is used to construct arrays, as in388- `[1,2,3]`. The elements of the arrays can be any jq389- expression. All of the results produced by all of the390- expressions are collected into one big array. You can use it391- to construct an array out of a known quantity of values (as392- in `[.foo, .bar, .baz]`) or to "collect" all the results of a393- filter into an array (as in `[.items[].name]`)394-395- Once you understand the "," operator, you can look at jq's array396- syntax in a different light: the expression `[1,2,3]` is not using a397- built-in syntax for comma-separated arrays, but is instead applying398- the `[]` operator (collect results) to the expression 1,2,3 (which399- produces three different results).400-401- If you have a filter `X` that produces four results,402- then the expression `[X]` will produce a single result, an403- array of four elements.404-405- examples:406- - program: "[.user, .projects[]]"407- input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'408- output: ['["stedolan", "jq", "wikiflow"]']409- - title: Objects - `{}`410- body: |411-412- Like JSON, `{}` is for constructing objects (aka413- dictionaries or hashes), as in: `{"a": 42, "b": 17}`.414-415- If the keys are "sensible" (all alphabetic characters), then416- the quotes can be left off. The value can be any expression417- (although you may need to wrap it in parentheses if it's a418- complicated one), which gets applied to the {} expression's419- input (remember, all filters have an input and an420- output).421-422- {foo: .bar}423-424- will produce the JSON object `{"foo": 42}` if given the JSON425- object `{"bar":42, "baz":43}`. You can use this to select426- particular fields of an object: if the input is an object427- with "user", "title", "id", and "content" fields and you428- just want "user" and "title", you can write429-430- {user: .user, title: .title}431-432- Because that's so common, there's a shortcut syntax: `{user, title}`.433-434- If one of the expressions produces multiple results,435- multiple dictionaries will be produced. If the input's436-437- {"user":"stedolan","titles":["JQ Primer", "More JQ"]}438-439- then the expression440-441- {user, title: .titles[]}442-443- will produce two outputs:444-445- {"user":"stedolan", "title": "JQ Primer"}446- {"user":"stedolan", "title": "More JQ"}447-448- Putting parentheses around the key means it will be evaluated as an449- expression. With the same input as above,450-451- {(.user): .titles}452-453- produces454-455- {"stedolan": ["JQ Primer", "More JQ"]}456-457- examples:458- - program: '{user, title: .titles[]}'459- input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'460- output:461- - '{"user":"stedolan", "title": "JQ Primer"}'462- - '{"user":"stedolan", "title": "More JQ"}'463- - program: '{(.user): .titles}'464- input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'465- output: ['{"stedolan": ["JQ Primer", "More JQ"]}']466-467- - title: Builtin operators and functions468- body: |469-470- Some jq operator (for instance, `+`) do different things471- depending on the type of their arguments (arrays, numbers,472- etc.). However, jq never does implicit type conversions. If you473- try to add a string to an object you'll get an error message and474- no result.475-476- entries:477- - title: Addition - `+`478- body: |479-480- The operator `+` takes two filters, applies them both481- to the same input, and adds the results together. What482- "adding" means depends on the types involved:483-484- - **Numbers** are added by normal arithmetic.485-486- - **Arrays** are added by being concatenated into a larger array.487-488- - **Strings** are added by being joined into a larger string.489-490- - **Objects** are added by merging, that is, inserting all491- the key-value pairs from both objects into a single492- combined object. If both objects contain a value for the493- same key, the object on the right of the `+` wins. (For494- recursive merge use the `*` operator.)495-496- `null` can be added to any value, and returns the other497- value unchanged.498-499- examples:500- - program: '.a + 1'501- input: '{"a": 7}'502- output: ['8']503- - program: '.a + .b'504- input: '{"a": [1,2], "b": [3,4]}'505- output: ['[1,2,3,4]']506- - program: '.a + null'507- input: '{"a": 1}'508- output: ['1']509- - program: '.a + 1'510- input: '{}'511- output: ['1']512- - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'513- input: 'null'514- output: ['{"a": 42, "b": 2, "c": 3}']515-516- - title: Subtraction - `-`517- body: |518-519- As well as normal arithmetic subtraction on numbers, the `-`520- operator can be used on arrays to remove all occurences of521- the second array's elements from the first array.522-523- examples:524- - program: '4 - .a'525- input: '{"a":3}'526- output: ['1']527- - program: . - ["xml", "yaml"]528- input: '["xml", "yaml", "json"]'529- output: ['["json"]']530-531- - title: Multiplication, division, modulo - `*`, `/`, and `%`532- body: |533-534- These operators only work on numbers, and do the expected.535-536- Multiplying a string by a number produces the concatenation of537- that string that many times.538-539- Dividing a string by another splits the first using the second540- as separators.541-542- Multiplying two objects will merge them recursively: this works543- like addition but if both objects contain a value for the544- same key, and the values are objects, the two are merged with545- the same strategy.546-547- examples:548- - program: '10 / . * 3'549- input: 5550- output: [6]551- - program: '. / ", "'552- input: '"a, b,c,d, e"'553- output: ['["a","b,c,d","e"]']554- - program: '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'555- input: 'null'556- output: ['{"k": {"a": 0, "b": 2, "c": 3}}']557-558- - title: "`length`"559- body: |560-561- The builtin function `length` gets the length of various562- different types of value:563-564- - The length of a **string** is the number of Unicode565- codepoints it contains (which will be the same as its566- JSON-encoded length in bytes if it's pure ASCII).567-568- - The length of an **array** is the number of elements.569-570- - The length of an **object** is the number of key-value pairs.571-572- - The length of **null** is zero.573-574- examples:575- - program: '.[] | length'576- input: '[[1,2], "string", {"a":2}, null]'577- output: [2, 6, 1, 0]578-579- - title: "`keys`"580- body: |581-582- The builtin function `keys`, when given an object, returns583- its keys in an array.584-585- The keys are sorted "alphabetically", by unicode codepoint586- order. This is not an order that makes particular sense in587- any particular language, but you can count on it being the588- same for any two objects with the same set of keys,589- regardless of locale settings.590-591- When `keys` is given an array, it returns the valid indices592- for that array: the integers from 0 to length-1.593-594- examples:595- - program: 'keys'596- input: '{"abc": 1, "abcd": 2, "Foo": 3}'597- output: ['["Foo", "abc", "abcd"]']598- - program: 'keys'599- input: '[42,3,35]'600- output: ['[0,1,2]']601-602- - title: "`has`"603- body: |604-605- The builtin function `has` returns whether the input object606- has the given key, or the input array has an element at the607- given index.608-609- `has($key)` has the same effect as checking whether `$key`610- is a member of the array returned by `keys`, although `has`611- will be faster.612-613- examples:614- - program: 'map(has("foo"))'615- input: '[{"foo": 42}, {}]'616- output: ['[true, false]']617- - program: 'map(has(2))'618- input: '[[0,1], ["a","b","c"]]'619- output: ['[false, true]']620-621- - title: "`del`"622- body: |623-624- The builtin function `del` removes a key and its corresponding625- value from an object.626-627- examples:628- - program: 'del(.foo)'629- input: '{"foo": 42, "bar": 9001, "baz": 42}'630- output: ['{"bar": 9001, "baz": 42}']631- - program: 'del(.[1, 2])'632- input: '["foo", "bar", "baz"]'633- output: ['["foo"]']634-635- - title: "`to_entries`, `from_entries`, `with_entries`"636- body: |637-638- These functions convert between an object and an array of639- key-value pairs. If `to_entries` is passed an object, then640- for each `k: v` entry in the input, the output array641- includes `{"key": k, "value": v}`.642-643- `from_entries` does the opposite conversion, and644- `with_entries(foo)` is a shorthand for `to_entries |645- map(foo) | from_entries`, useful for doing some operation to646- all keys and values of an object.647-648- examples:649- - program: 'to_entries'650- input: '{"a": 1, "b": 2}'651- output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']652- - program: 'from_entries'653- input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'654- output: ['{"a": 1, "b": 2}']655- - program: 'with_entries(.key |= "KEY_" + .)'656- input: '{"a": 1, "b": 2}'657- output: ['{"KEY_a": 1, "KEY_b": 2}']658-659-660- - title: "`select`"661- body: |662-663- The function `select(foo)` produces its input unchanged if664- `foo` returns true for that input, and produces no output665- otherwise.666-667- It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`668- will give you `[2,3]`.669-670- examples:671- - program: 'map(select(. >= 2))'672- input: '[1,5,3,0,7]'673- output: ['[5,3,7]']674-675-676- - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `strings`, `nulls`, `values`, `scalars`"677- body: |678-679- These built-ins select only inputs that are arrays, objects,680- iterables (arrays or objects), booleans, numbers, strings,681- null, non-null values, and non-iterables, respectively.682-683- examples:684- - program: '.[]|numbers'685- input: '[[],{},1,"foo",null,true,false]'686- output: ['1']687-688- - title: "`empty`"689- body: |690-691- `empty` returns no results. None at all. Not even `null`.692-693- It's useful on occasion. You'll know if you need it :)694-695- examples:696- - program: '1, empty, 2'697- input: 'null'698- output: [1, 2]699- - program: '[1,2,empty,3]'700- input: 'null'701- output: ['[1,2,3]']702-703- - title: "`map(x)`"704- body: |705-706- For any filter `x`, `map(x)` will run that filter for each707- element of the input array, and produce the outputs a new708- array. `map(.+1)` will increment each element of an array of numbers.709-710- `map(x)` is equivalent to `[.[] | x]`. In fact, this is how711- it's defined.712-713- examples:714- - program: 'map(.+1)'715- input: '[1,2,3]'716- output: ['[2,3,4]']717-718- - title: "`paths`"719- body: |720-721- Outputs the paths to all the elements in its input (except it722- does not output the empty list, representing . itself).723-724- `paths` is equivalent to725-726- def paths: path(recurse(if (type|. == "array" or . == "object") then .[] else empty end))|select(length > 0);727-728- examples:729- - program: '[paths]'730- input: '[1,[[],{"a":2}]]'731- output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']732-733- - title: "`leaf_paths`"734- body: |735-736- Outputs the paths to all the leaves (non-array, non-object737- elements) in its input.738-739- examples:740- - program: '[leaf_paths]'741- input: '[1,[[],{"a":2}]]'742- output: ['[[0],[1,1,"a"]]']743-744- - title: "`add`"745- body: |746-747- The filter `add` takes as input an array, and produces as748- output the elements of the array added together. This might749- mean summed, concatenated or merged depending on the types750- of the elements of the input array - the rules are the same751- as those for the `+` operator (described above).752-753- If the input is an empty array, `add` returns `null`.754-755- examples:756- - program: add757- input: '["a","b","c"]'758- output: ['"abc"']759- - program: add760- input: '[1, 2, 3]'761- output: [6]762- - program: add763- input: '[]'764- output: ["null"]765-766- - title: "`any`"767- body: |768-769- The filter `any` takes as input an array of boolean values,770- and produces `true` as output if any of the elements of771- the array are `true`.772-773- If the input is an empty array, `any` returns `false`.774-775- examples:776- - program: any777- input: '[true, false]'778- output: ["true"]779- - program: any780- input: '[false, false]'781- output: ["false"]782- - program: any783- input: '[]'784- output: ["false"]785-786- - title: "`all`"787- body: |788-789- The filter `all` takes as input an array of boolean values,790- and produces `true` as output if all of the elements of791- the array are `true`.792-793- If the input is an empty array, `all` returns `true`.794-795- examples:796- - program: all797- input: '[true, false]'798- output: ["false"]799- - program: all800- input: '[true, true]'801- output: ["true"]802- - program: all803- input: '[]'804- output: ["true"]805-806- - title: "`range`"807- body: |808-809- The `range` function produces a range of numbers. `range(4;10)`810- produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers811- are produced as separate outputs. Use `[range(4;10)]` to get a range as812- an array.813-814- examples:815- - program: 'range(2;4)'816- input: 'null'817- output: ['2', '3']818- - program: '[range(2;4)]'819- input: 'null'820- output: ['[2,3]']821-822- - title: "`floor`"823- body: |824-825- The `floor` function returns the floor of its numeric input.826-827- examples:828- - program: 'floor'829- input: '3.14159'830- output: ['3']831-832- - title: "`sqrt`"833- body: |834-835- The `sqrt` function returns the square root of its numeric input.836-837- examples:838- - program: 'sqrt'839- input: '9'840- output: ['3']841-842- - title: "`tonumber`"843- body: |844-845- The `tonumber` function parses its input as a number. It846- will convert correctly-formatted strings to their numeric847- equivalent, leave numbers alone, and give an error on all other input.848-849- examples:850- - program: '.[] | tonumber'851- input: '[1, "1"]'852- output: [1, 1]853-854- - title: "`tostring`"855- body: |856-857- The `tostring` function prints its input as a858- string. Strings are left unchanged, and all other values are859- JSON-encoded.860-861- examples:862- - program: '.[] | tostring'863- input: '[1, "1", [1]]'864- output: ['"1"', '"1"', '"[1]"']865-866- - title: "`type`"867- body: |868-869- The `type` function returns the type of its argument as a870- string, which is one of null, boolean, number, string, array871- or object.872-873- examples:874- - program: 'map(type)'875- input: '[0, false, [], {}, null, "hello"]'876- output: ['["number", "boolean", "array", "object", "null", "string"]']877-878- - title: "`sort, sort_by`"879- body: |880-881- The `sort` functions sorts its input, which must be an882- array. Values are sorted in the following order:883-884- * `null`885- * `false`886- * `true`887- * numbers888- * strings, in alphabetical order (by unicode codepoint value)889- * arrays, in lexical order890- * objects891-892- The ordering for objects is a little complex: first they're893- compared by comparing their sets of keys (as arrays in894- sorted order), and if their keys are equal then the values895- are compared key by key.896-897- `sort_by` may be used to sort by a particular field of an898- object, or by applying any jq filter. `sort_by(foo)`899- compares two elements by comparing the result of `foo` on900- each element.901-902- examples:903- - program: 'sort'904- input: '[8,3,null,6]'905- output: ['[null,3,6,8]']906- - program: 'sort_by(.foo)'907- input: '[{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}]'908- output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']909-910- - title: "`group_by`"911- body: |912-913- `group_by(.foo)` takes as input an array, groups the914- elements having the same `.foo` field into separate arrays,915- and produces all of these arrays as elements of a larger916- array, sorted by the value of the `.foo` field.917-918- Any jq expression, not just a field access, may be used in919- place of `.foo`. The sorting order is the same as described920- in the `sort` function above.921-922- examples:923- - program: 'group_by(.foo)'924- input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'925- output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']926-927- - title: "`min`, `max`, `min_by`, `max_by`"928- body: |929-930- Find the minimum or maximum element of the input array. The931- `_by` versions allow you to specify a particular field or932- property to examine, e.g. `min_by(.foo)` finds the object933- with the smallest `foo` field.934-935- examples:936- - program: 'min'937- input: '[5,4,2,7]'938- output: ['2']939- - program: 'max_by(.foo)'940- input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'941- output: ['{"foo":2, "bar":3}']942-943- - title: "`unique`"944- body: |945-946- The `unique` function takes as input an array and produces947- an array of the same elements, in sorted order, with948- duplicates removed.949-950- examples:951- - program: 'unique'952- input: '[1,2,5,3,5,3,1,3]'953- output: ['[1,2,3,5]']954-955- - title: "`unique_by`"956- body: |957-958- The `unique_by(.foo)` function takes as input an array and produces959- an array of the same elements, in sorted order, with960- elqements with a duplicate `.foo` field removed. Think of it as making961- an array by taking one element out of every group produced by962- `group_by`.963-964- examples:965- - program: 'unique_by(.foo)'966- input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'967- output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']968- - program: 'unique_by(length)'969- input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'970- output: ['["bacon", "chunky", "asparagus"]']971-972-973- - title: "`reverse`"974- body: |975-976- This function reverses an array.977-978- examples:979- - program: 'reverse'980- input: '[1,2,3,4]'981- output: ['[4,3,2,1]']982-983- - title: "`contains`"984- body: |985-986- The filter `contains(b)` will produce true if b is987- completely contained within the input. A string B is988- contained in a string A if B is a substring of A. An array B989- is contained in an array A is all elements in B are990- contained in any element in A. An object B is contained in991- object A if all of the values in B are contained in the992- value in A with the same key. All other types are assumed to993- be contained in each other if they are equal.994-995- examples:996- - program: 'contains("bar")'997- input: '"foobar"'998- output: ['true']999- - program: 'contains(["baz", "bar"])'1000- input: '["foobar", "foobaz", "blarp"]'1001- output: ['true']1002- - program: 'contains(["bazzzzz", "bar"])'1003- input: '["foobar", "foobaz", "blarp"]'1004- output: ['false']1005- - program: 'contains({foo: 12, bar: [{barp: 12}]})'1006- input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1007- output: ['true']1008- - program: 'contains({foo: 12, bar: [{barp: 15}]})'1009- input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1010- output: ['false']1011-1012- - title: "`indices(s)`"1013- body: |1014-1015- Outputs an array containing the indices in `.` where `s`1016- occurs. The input may be an array, in which case if `s` is an1017- array then the indices output will be those where all elements1018- in `.` match those of `s`.1019-1020- examples:1021- - program: 'indices(", ")'1022- input: '"a,b, cd, efg, hijk"'1023- output: ['[3,7,12]']1024- - program: 'indices(1)'1025- input: '[0,1,2,1,3,1,4]'1026- output: ['[1,3,5]']1027- - program: 'indices([1,2])'1028- input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1029- output: ['[1,8]']1030-1031- - title: "`index(s)`, `rindex(s)`"1032- body: |1033-1034- Outputs the index of the first (`index`) or last (`rindex`)1035- occurrence of `s` in the input.1036-1037- examples:1038- - program: 'index(", ")'1039- input: '"a,b, cd, efg, hijk"'1040- output: ['3']1041- - program: 'rindex(", ")'1042- input: '"a,b, cd, efg, hijk"'1043- output: ['12']1044-1045- - title: "`startswith`"1046- body: |1047-1048- Outputs `true` if . starts with the given string argument.1049-1050- examples:1051- - program: '[.[]|startswith("foo")]'1052- input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1053- output: ['[false, true, false, true, false]']1054-1055- - title: "`endswith`"1056- body: |1057-1058- Outputs `true` if . ends with the given string argument.1059-1060- examples:1061- - program: '[.[]|endswith("foo")]'1062- input: '["foobar", "barfoo"]'1063- output: ['[false, true]']1064-1065- - title: "`ltrimstr`"1066- body: |1067-1068- Outputs its input with the given prefix string removed, if it1069- starts with it.1070-1071- examples:1072- - program: '[.[]|ltrimstr("foo")]'1073- input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1074- output: ['["fo","","barfoo","bar","afoo"]']1075-1076- - title: "`rtrimstr`"1077- body: |1078-1079- Outputs its input with the given suffix string removed, if it1080- starts with it.1081-1082- examples:1083- - program: '[.[]|rtrimstr("foo")]'1084- input: '["fo", "foo", "barfoo", "foobar", "foob"]'1085- output: ['["fo","","bar","foobar","foob"]']1086-1087- - title: "`explode`"1088- body: |1089-1090- Converts an input string into an array of the string's1091- codepoint numbers.1092-1093- examples:1094- - program: 'explode'1095- input: '"foobar"'1096- output: ['[102,111,111,98,97,114]']1097-1098- - title: "`implode`"1099- body: |1100-1101- The inverse of explode.1102-1103- examples:1104- - program: 'implode'1105- input: '[65, 66, 67]'1106- output: ['"ABC"']1107-1108- - title: "`split`"1109- body: |1110-1111- Splits an input string on the separator argument.1112-1113- examples:1114- - program: 'split(", ")'1115- input: '"a, b,c,d, e"'1116- output: ['["a","b,c,d","e"]']1117-1118- - title: "`join`"1119- body: |1120-1121- Joins the array of elements given as input, using the1122- argument as separator. It is the inverse of `split`: that is,1123- running `split("foo") | join("foo")` over any input string1124- returns said input string.1125-1126- examples:1127- - program: 'join(", ")'1128- input: '["a","b,c,d","e"]'1129- output: ['"a, b,c,d, e"']1130-1131-1132- - title: "`recurse`"1133- body: |1134-1135- The `recurse` function allows you to search through a1136- recursive structure, and extract interesting data from all1137- levels. Suppose your input represents a filesystem:1138-1139- {"name": "/", "children": [1140- {"name": "/bin", "children": [1141- {"name": "/bin/ls", "children": []},1142- {"name": "/bin/sh", "children": []}]},1143- {"name": "/home", "children": [1144- {"name": "/home/stephen", "children": [1145- {"name": "/home/stephen/jq", "children": []}]}]}]}1146-1147- Now suppose you want to extract all of the filenames1148- present. You need to retrieve `.name`, `.children[].name`,1149- `.children[].children[].name`, and so on. You can do this1150- with:1151-1152- recurse(.children[]) | .name1153-1154- examples:1155- - program: 'recurse(.foo[])'1156- input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'1157- output:1158- - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'1159- - '{"foo":[]}'1160- - '{"foo":[{"foo":[]}]}'1161- - '{"foo":[]}'1162-1163- - title: "`recurse_down`"1164- body: |1165-1166- A quieter version of `recurse(.[])`, equivalent to:1167-1168- def recurse_down: recurse(.[]?);1169-1170- - title: "`..`"1171- body: |1172-1173- Short-hand for `recurse_down`. This is intended to resemble1174- the XPath `//` operator. Note that `..a` does not work; use1175- `..|a` instead.1176-1177- examples:1178- - program: '..|.a?'1179- input: '[[{"a":1}]]'1180- output: ['1']1181-1182- - title: "String interpolation - `\\(foo)`"1183- body: |1184-1185- Inside a string, you can put an expression inside parens1186- after a backslash. Whatever the expression returns will be1187- interpolated into the string.1188-1189- examples:1190- - program: '"The input was \(.), which is one less than \(.+1)"'1191- input: '42'1192- output: ['"The input was 42, which is one less than 43"']1193-1194- - title: "Convert to/from JSON"1195- body: |1196-1197- The `tojson` and `fromjson` builtins dump values as JSON texts1198- or parse JSON texts into values, respectively. The tojson1199- builtin differs from tostring in that tostring returns strings1200- unmodified, while tojson encodes strings as JSON strings.1201-1202- examples:1203- - program: '[.[]|tostring]'1204- input: '[1, "foo", ["foo"]]'1205- output: ['["1","foo","[\"foo\"]"]']1206- - program: '[.[]|tojson]'1207- input: '[1, "foo", ["foo"]]'1208- output: ['["1","\"foo\"","[\"foo\"]"]']1209- - program: '[.[]|tojson|fromjson]'1210- input: '[1, "foo", ["foo"]]'1211- output: ['[1,"foo",["foo"]]']1212-1213- - title: "Format strings and escaping"1214- body: |1215-1216- The `@foo` syntax is used to format and escape strings,1217- which is useful for building URLs, documents in a language1218- like HTML or XML, and so forth. `@foo` can be used as a1219- filter on its own, the possible escapings are:1220-1221- * `@text`:1222-1223- Calls `tostring`, see that function for details.1224-1225- * `@json`:1226-1227- Serialises the input as JSON.1228-1229- * `@html`:1230-1231- Applies HTML/XML escaping, by mapping the characters1232- `<>&'"` to their entity equivalents `<`, `>`,1233- `&`, `'`, `"`.1234-1235- * `@uri`:1236-1237- Applies percent-encoding, by mapping all reserved URI1238- characters to a `%xx` sequence.1239-1240- * `@csv`:1241-1242- The input must be an array, and it is rendered as CSV1243- with double quotes for strings, and quotes escaped by1244- repetition.1245-1246- * `@sh`:1247-1248- The input is escaped suitable for use in a command-line1249- for a POSIX shell. If the input is an array, the output1250- will be a series of space-separated strings.1251-1252- * `@base64`:1253-1254- The input is converted to base64 as specified by RFC 4648.1255-1256- This syntax can be combined with string interpolation in a1257- useful way. You can follow a `@foo` token with a string1258- literal. The contents of the string literal will *not* be1259- escaped. However, all interpolations made inside that string1260- literal will be escaped. For instance,1261-1262- @uri "https://www.google.com/search?q=\(.search)"1263-1264- will produce the following output for the input1265- `{"search":"what is jq?"}`:1266-1267- "https://www.google.com/search?q=what%20is%20jq%3f"1268-1269- Note that the slashes, question mark, etc. in the URL are1270- not escaped, as they were part of the string literal.1271-1272- examples:1273- - program: '@html'1274- input: '"This works if x < y"'1275- output: ['"This works if x < y"']1276-1277-# - program: '@html "<span>Anonymous said: \(.)</span>"'1278-# input: '"<script>alert(\"lol hax\");</script>"'1279-# output: ["<span>Anonymous said: <script>alert("lol hax");</script></span>"]1280-1281- - program: '@sh "echo \(.)"'1282- input: "\"O'Hara's Ale\""1283- output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]1284-1285- - title: Conditionals and Comparisons1286- entries:1287- - title: "`==`, `!=`"1288- body: |1289-1290- The expression 'a == b' will produce 'true' if the result of a and b1291- are equal (that is, if they represent equivalent JSON documents) and1292- 'false' otherwise. In particular, strings are never considered equal1293- to numbers. If you're coming from Javascript, jq's == is like1294- Javascript's === - considering values equal only when they have the1295- same type as well as the same value.1296-1297- != is "not equal", and 'a != b' returns the opposite value of 'a == b'1298-1299- examples:1300- - program: '.[] == 1'1301- input: '[1, 1.0, "1", "banana"]'1302- output: ['true', 'true', 'false', 'false']1303- - title: if-then-else1304- body: |1305-1306- `if A then B else C end` will act the same as `B` if `A`1307- produces a value other than false or null, but act the same1308- as `C` otherwise.1309-1310- Checking for false or null is a simpler notion of1311- "truthiness" than is found in Javascript or Python, but it1312- means that you'll sometimes have to be more explicit about1313- the condition you want: you can't test whether, e.g. a1314- string is empty using `if .name then A else B end`, you'll1315- need something more like `if (.name | length) > 0 then A else1316- B end` instead.1317-1318- If the condition `A` produces multiple results, then `B` is evaluated1319- once for each result that is not false or null, and `C` is evaluated1320- once for each false or null.1321-1322- More cases can be added to an if using `elif A then B` syntax.1323-1324- examples:1325- - program: |-1326- if . == 0 then1327- "zero"1328- elif . == 1 then1329- "one"1330- else1331- "many"1332- end1333- input: 21334- output: ['"many"']1335-1336- - title: "`>, >=, <=, <`"1337- body: |1338-1339- The comparison operators `>`, `>=`, `<=`, `<` return whether1340- their left argument is greater than, greater than or equal1341- to, less than or equal to or less than their right argument1342- (respectively).1343-1344- The ordering is the same as that described for `sort`, above.1345-1346- examples:1347- - program: '. < 5'1348- input: 21349- output: ['true']1350-1351- - title: and/or/not1352- body: |1353-1354- jq supports the normal Boolean operators and/or/not. They have the1355- same standard of truth as if expressions - false and null are1356- considered "false values", and anything else is a "true value".1357-1358- If an operand of one of these operators produces multiple1359- results, the operator itself will produce a result for each input.1360-1361- `not` is in fact a builtin function rather than an operator,1362- so it is called as a filter to which things can be piped1363- rather than with special syntax, as in `.foo and .bar |1364- not`.1365-1366- These three only produce the values "true" and "false", and1367- so are only useful for genuine Boolean operations, rather1368- than the common Perl/Python/Ruby idiom of1369- "value_that_may_be_null or default". If you want to use this1370- form of "or", picking between two values rather than1371- evaluating a condition, see the "//" operator below.1372-1373- examples:1374- - program: '42 and "a string"'1375- input: 'null'1376- output: ['true']1377- - program: '(true, false) or false'1378- input: 'null'1379- output: ['true', 'false']1380-# - program: '(true, false) and (true, false)'1381-# input: 'null'1382-# output: ['true', 'false', 'false', 'false']1383- - program: '(true, true) and (true, false)'1384- input: 'null'1385- output: ['true', 'false', 'true', 'false']1386- - program: '[true, false | not]'1387- input: 'null'1388- output: ['[false, true]']1389-1390- - title: Alternative operator - `//`1391- body: |1392-1393- A filter of the form `a // b` produces the same1394- results as `a`, if `a` produces results other than `false`1395- and `null`. Otherwise, `a // b` produces the same results as `b`.1396-1397- This is useful for providing defaults: `.foo // 1` will1398- evaluate to `1` if there's no `.foo` element in the1399- input. It's similar to how `or` is sometimes used in Python1400- (jq's `or` operator is reserved for strictly Boolean1401- operations).1402-1403- examples:1404- - program: '.foo // 42'1405- input: '{"foo": 19}'1406- output: [19]1407- - program: '.foo // 42'1408- input: '{}'1409- output: [42]1410-1411- - title: Advanced features1412- body: |1413- Variables are an absolute necessity in most programming languages, but1414- they're relegated to an "advanced feature" in jq.1415-1416- In most languages, variables are the only means of passing around1417- data. If you calculate a value, and you want to use it more than once,1418- you'll need to store it in a variable. To pass a value to another part1419- of the program, you'll need that part of the program to define a1420- variable (as a function parameter, object member, or whatever) in1421- which to place the data.1422-1423- It is also possible to define functions in jq, although this is1424- is a feature whose biggest use is defining jq's standard library1425- (many jq functions such as `map` and `find` are in fact written1426- in jq).1427-1428- Finally, jq has a `reduce` operation, which is very powerful but a1429- bit tricky. Again, it's mostly used internally, to define some1430- useful bits of jq's standard library.1431-1432- entries:1433- - title: Variables1434- body: |1435-1436- In jq, all filters have an input and an output, so manual1437- plumbing is not necessary to pass a value from one part of a program1438- to the next. Many expressions, for instance `a + b`, pass their input1439- to two distinct subexpressions (here `a` and `b` are both passed the1440- same input), so variables aren't usually necessary in order to use a1441- value twice.1442-1443- For instance, calculating the average value of an array of numbers1444- requires a few variables in most languages - at least one to hold the1445- array, perhaps one for each element or for a loop counter. In jq, it's1446- simply `add / length` - the `add` expression is given the array and1447- produces its sum, and the `length` expression is given the array and1448- produces its length.1449-1450- So, there's generally a cleaner way to solve most problems in jq than1451- defining variables. Still, sometimes they do make things easier, so jq1452- lets you define variables using `expression as $variable`. All1453- variable names start with `$`. Here's a slightly uglier version of the1454- array-averaging example:1455-1456- length as $array_length | add / $array_length1457-1458- We'll need a more complicated problem to find a situation where using1459- variables actually makes our lives easier.1460-1461-1462- Suppose we have an array of blog posts, with "author" and "title"1463- fields, and another object which is used to map author usernames to1464- real names. Our input looks like:1465-1466- {"posts": [{"title": "Frist psot", "author": "anon"},1467- {"title": "A well-written article", "author": "person1"}],1468- "realnames": {"anon": "Anonymous Coward",1469- "person1": "Person McPherson"}}1470-1471- We want to produce the posts with the author field containing a real1472- name, as in:1473-1474- {"title": "Frist psot", "author": "Anonymous Coward"}1475- {"title": "A well-written article", "author": "Person McPherson"}1476-1477- We use a variable, $names, to store the realnames object, so that we1478- can refer to it later when looking up author usernames:1479-1480- .realnames as $names | .posts[] | {title, author: $names[.author]}1481-1482- The expression `exp as $x | ...` means: for each value of expression1483- `exp`, run the rest of the pipeline with the entire original input, and1484- with `$x` set to that value. Thus `as` functions as something of a1485- foreach loop.1486-1487- Variables are scoped over the rest of the expression that defines1488- them, so1489-1490- .realnames as $names | (.posts[] | {title, author: $names[.author]})1491-1492- will work, but1493-1494- (.realnames as $names | .posts[]) | {title, author: $names[.author]}1495-1496- won't.1497-1498- examples:1499- - program: '.bar as $x | .foo | . + $x'1500- input: '{"foo":10, "bar":200}'1501- output: ['210']1502-1503- - title: 'Defining Functions'1504- body: |1505-1506- You can give a filter a name using "def" syntax:1507-1508- def increment: . + 1;1509-1510- From then on, `increment` is usable as a filter just like a1511- builtin function (in fact, this is how some of the builtins1512- are defined). A function may take arguments:1513-1514- def map(f): [.[] | f];1515-1516- Arguments are passed as filters, not as values. The1517- same argument may be referenced multiple times with1518- different inputs (here `f` is run for each element of the1519- input array). Arguments to a function work more like1520- callbacks than like value arguments.1521-1522- If you want the value-argument behaviour for defining simple1523- functions, you can just use a variable:1524-1525- def addvalue(f): f as $value | map(. + $value);1526-1527- With that definition, `addvalue(.foo)` will add the current1528- input's `.foo` field to each element of the array.1529-1530- examples:1531- - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'1532- input: '[[1,2],[10,20]]'1533- output: ['[[1,2,1], [10,20,10]]']1534- - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'1535- input: '[[1,2],[10,20]]'1536- output: ['[[1,2,1,2], [10,20,1,2]]']1537-1538- - title: Reduce1539- body: |1540-1541- The `reduce` syntax in jq allows you to combine all of the1542- results of an expression by accumulating them into a single1543- answer. As an example, we'll pass `[3,2,1]` to this expression:1544-1545- reduce .[] as $item (0; . + $item)1546-1547- For each result that `.[]` produces, `. + $item` is run to1548- accumulate a running total, starting from 0. In this1549- example, `.[]` produces the results 3, 2, and 1, so the1550- effect is similar to running something like this:1551-1552- 0 | (3 as $item | . + $item) |1553- (2 as $item | . + $item) |1554- (1 as $item | . + $item)1555-1556- examples:1557- - program: 'reduce .[] as $item (0; . + $item)'1558- input: '[10,2,5,3]'1559- output: ['20']1560-1561-1562- - title: Assignment1563- body: |1564-1565- Assignment works a little differently in jq than in most1566- programming languages. jq doesn't distinguish between references1567- to and copies of something - two objects or arrays are either1568- equal or not equal, without any further notion of being "the1569- same object" or "not the same object".1570-1571- If an object has two fields which are arrays, `.foo` and `.bar`,1572- and you append something to `.foo`, then `.bar` will not get1573- bigger. Even if you've just set `.bar = .foo`. If you're used to1574- programming in languages like Python, Java, Ruby, Javascript,1575- etc. then you can think of it as though jq does a full deep copy1576- of every object before it does the assignment (for performance,1577- it doesn't actually do that, but that's the general idea).1578-1579- entries:1580- - title: "`=`"1581- body: |1582-1583- The filter `.foo = 1` will take as input an object1584- and produce as output an object with the "foo" field set to1585- 1. There is no notion of "modifying" or "changing" something1586- in jq - all jq values are immutable. For instance,1587-1588- .foo = .bar | .foo.baz = 11589-1590- will not have the side-effect of setting .bar.baz to be set1591- to 1, as the similar-looking program in Javascript, Python,1592- Ruby or other languages would. Unlike these languages (but1593- like Haskell and some other functional languages), there is1594- no notion of two arrays or objects being "the same array" or1595- "the same object". They can be equal, or not equal, but if1596- we change one of them in no circumstances will the other1597- change behind our backs.1598-1599- This means that it's impossible to build circular values in1600- jq (such as an array whose first element is itself). This is1601- quite intentional, and ensures that anything a jq program1602- can produce can be represented in JSON.1603-1604- - title: "`|=`"1605- body: |1606- As well as the assignment operator '=', jq provides the "update"1607- operator '|=', which takes a filter on the right-hand side and1608- works out the new value for the property being assigned to by running1609- the old value through this expression. For instance, .foo |= .+1 will1610- build an object with the "foo" field set to the input's "foo" plus 1.1611-1612- This example should show the difference between '=' and '|=':1613-1614- Provide input '{"a": {"b": 10}, "b": 20}' to the programs:1615-1616- .a = .b1617- .a |= .b1618-1619- The former will set the "a" field of the input to the "b" field of the1620- input, and produce the output {"a": 20}. The latter will set the "a"1621- field of the input to the "a" field's "b" field, producing {"a": 10}.1622-1623- - title: "`+=`, `-=`, `*=`, `/=`, `%=`, `//=`"1624- body: |1625-1626- jq has a few operators of the form `a op= b`, which are all1627- equivalent to `a |= . op b`. So, `+= 1` can be used to increment values.1628-1629- examples:1630- - program: .foo += 11631- input: '{"foo": 42}'1632- output: ['{"foo": 43}']1633-1634- - title: Complex assignments1635- body: |1636- Lots more things are allowed on the left-hand side of a jq assignment1637- than in most langauges. We've already seen simple field accesses on1638- the left hand side, and it's no surprise that array accesses work just1639- as well:1640-1641- .posts[0].title = "JQ Manual"1642-1643- What may come as a surprise is that the expression on the left may1644- produce multiple results, referring to different points in the input1645- document:1646-1647- .posts[].comments |= . + ["this is great"]1648-1649- That example appends the string "this is great" to the "comments"1650- array of each post in the input (where the input is an object with a1651- field "posts" which is an array of posts).1652-1653- When jq encounters an assignment like 'a = b', it records the "path"1654- taken to select a part of the input document while executing a. This1655- path is then used to find which part of the input to change while1656- executing the assignment. Any filter may be used on the1657- left-hand side of an equals - whichever paths it selects from the1658- input will be where the assignment is performed.1659-1660- This is a very powerful operation. Suppose we wanted to add a comment1661- to blog posts, using the same "blog" input above. This time, we only1662- want to comment on the posts written by "stedolan". We can find those1663- posts using the "select" function described earlier:1664-1665- .posts[] | select(.author == "stedolan")1666-1667- The paths provided by this operation point to each of the posts that1668- "stedolan" wrote, and we can comment on each of them in the same way1669- that we did before:1670-1671- (.posts[] | select(.author == "stedolan") | .comments) |=1672- . + ["terrible."]deleted:docs/content/3.manual/v1.5/manual.yml-2878 removed
1----2-headline: jq 1.5 Manual3-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 simple 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 whether or not 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 (object keys)732- 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 return the outputs in 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 elements of936- the array are `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 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: "`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, then `B` is evaluated1798- once for each result that is not false or null, and `C` is evaluated1799- once for each false or null.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: "`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: "`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: "`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: "`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: "`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: "`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: "`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 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-deleted:docs/content/3.manual/v1.6/manual.yml-3287 removed
1----2-headline: jq 1.6 Manual3-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 mode also parses the output of jq without the `--seq`111- option.112-113- * `--stream`:114-115- Parse the input in streaming fashion, outputing arrays of path116- and leaf values (scalars and empty arrays or empty objects).117- For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]`118- becomes `[[0],[]]`, `[[1],"a"]`, and `[[1,0],"b"]`.119-120- This is useful for processing very large inputs. Use this in121- conjunction with filtering and the `reduce` and `foreach` syntax122- to reduce large inputs incrementally.123-124- * `--slurp`/`-s`:125-126- Instead of running the filter for each JSON object in the127- input, read the entire input stream into a large array and run128- the filter just once.129-130- * `--raw-input`/`-R`:131-132- Don't parse the input as JSON. Instead, each line of text is133- passed to the filter as a string. If combined with `--slurp`,134- then the entire input is passed to the filter as a single long135- string.136-137- * `--null-input`/`-n`:138-139- Don't read any input at all! Instead, the filter is run once140- using `null` as the input. This is useful when using jq as a141- simple calculator or to construct JSON data from scratch.142-143- * `--compact-output` / `-c`:144-145- By default, jq pretty-prints JSON output. Using this option146- will result in more compact output by instead putting each147- JSON object on a single line.148-149- * `--tab`:150-151- Use a tab for each indentation level instead of two spaces.152-153- * `--indent n`:154-155- Use the given number of spaces (no more than 8) for indentation.156-157- * `--color-output` / `-C` and `--monochrome-output` / `-M`:158-159- By default, jq outputs colored JSON if writing to a160- terminal. You can force it to produce color even if writing to161- a pipe or a file using `-C`, and disable color with `-M`.162-163- Colors can be configured with the `JQ_COLORS` environment164- variable (see below).165-166- * `--ascii-output` / `-a`:167-168- jq usually outputs non-ASCII Unicode codepoints as UTF-8, even169- if the input specified them as escape sequences (like170- "\u03bc"). Using this option, you can force jq to produce pure171- ASCII output with every non-ASCII character replaced with the172- equivalent escape sequence.173-174- * `--unbuffered`175-176- Flush the output after each JSON object is printed (useful if177- you're piping a slow data source into jq and piping jq's178- output elsewhere).179-180- * `--sort-keys` / `-S`:181-182- Output the fields of each object with the keys in sorted order.183-184- * `--raw-output` / `-r`:185-186- With this option, if the filter's result is a string then it187- will be written directly to standard output rather than being188- formatted as a JSON string with quotes. This can be useful for189- making jq filters talk to non-JSON-based systems.190-191- * `--join-output` / `-j`:192-193- Like `-r` but jq won't print a newline after each output.194-195- * `-f filename` / `--from-file filename`:196-197- Read filter from the file rather than from a command line, like198- awk's -f option. You can also use '#' to make comments.199-200- * `-Ldirectory` / `-L directory`:201-202- Prepend `directory` to the search list for modules. If this203- option is used then no builtin search list is used. See the204- section on modules below.205-206- * `-e` / `--exit-status`:207-208- Sets the exit status of jq to 0 if the last output values was209- neither `false` nor `null`, 1 if the last output value was210- either `false` or `null`, or 4 if no valid result was ever211- produced. Normally jq exits with 2 if there was any usage212- problem or system error, 3 if there was a jq program compile213- error, or 0 if the jq program ran.214-215- Another way to set the exit status is with the `halt_error`216- builtin function.217-218- * `--arg name value`:219-220- This option passes a value to the jq program as a predefined221- variable. If you run jq with `--arg foo bar`, then `$foo` is222- available in the program and has the value `"bar"`. Note that223- `value` will be treated as a string, so `--arg foo 123` will224- bind `$foo` to `"123"`.225-226- Named arguments are also available to the jq program as227- `$ARGS.named`.228-229- * `--argjson name JSON-text`:230-231- This option passes a JSON-encoded value to the jq program as a232- predefined variable. If you run jq with `--argjson foo 123`, then233- `$foo` is available in the program and has the value `123`.234-235- * `--slurpfile variable-name filename`:236-237- This option reads all the JSON texts in the named file and binds238- an array of the parsed JSON values to the given global variable.239- If you run jq with `--slurpfile foo bar`, then `$foo` is available240- in the program and has an array whose elements correspond to the241- texts in the file named `bar`.242-243- * `--rawfile variable-name filename`:244-245- This option reads in the named file and binds its contents to the given246- global variable. If you run jq with `--rawfile foo bar`, then `$foo` is247- available in the program and has a string whose contents are to the texs248- in the file named `bar`.249-250- * `--argfile variable-name filename`:251-252- Do not use. Use `--slurpfile` instead.253-254- (This option is like `--slurpfile`, but when the file has just255- one text, then that is used, else an array of texts is used as256- in `--slurpfile`.)257-258- * `--args`:259-260- Remaining arguments are positional string arguments. These are261- available to the jq program as `$ARGS.positional[]`.262-263- * `--jsonargs`:264-265- Remaining arguments are positional JSON text arguments. These266- are available to the jq program as `$ARGS.positional[]`.267-268- * `--run-tests [filename]`:269-270- Runs the tests in the given file or standard input. This must271- be the last option given and does not honor all preceding272- options. The input consists of comment lines, empty lines, and273- program lines followed by one input line, as many lines of274- output as are expected (one per output), and a terminating empty275- line. Compilation failure tests start with a line containing276- only "%%FAIL", then a line containing the program to compile,277- then a line containing an error message to compare to the278- actual.279-280- Be warned that this option can change backwards-incompatibly.281-282- - title: Basic filters283- entries:284- - title: "Identity: `.`"285- body: |286-287- The absolute simplest filter is `.` . This is a filter that288- takes its input and produces it unchanged as output. That is,289- this is the identity operator.290-291- Since jq by default pretty-prints all output, this trivial292- program can be a useful way of formatting JSON output from,293- say, `curl`.294-295- examples:296- - program: '.'297- input: '"Hello, world!"'298- output: ['"Hello, world!"']299-300- - title: "Object Identifier-Index: `.foo`, `.foo.bar`"301- body: |302-303- The simplest *useful* filter is `.foo`. When given a304- JSON object (aka dictionary or hash) as input, it produces305- the value at the key "foo", or null if there's none present.306-307- A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.308-309- This syntax only works for simple, identifier-like keys, that310- is, keys that are all made of alphanumeric characters and311- underscore, and which do not start with a digit.312-313- If the key contains special characters, you need to surround314- it with double quotes like this: `."foo$"`, or else `.["foo$"]`.315-316- For example `.["foo::bar"]` and `.["foo.bar"]` work while317- `.foo::bar` does not, and `.foo.bar` means `.["foo"].["bar"]`.318-319- examples:320- - program: '.foo'321- input: '{"foo": 42, "bar": "less interesting data"}'322- output: [42]323- - program: '.foo'324- input: '{"notfoo": true, "alsonotfoo": false}'325- output: ['null']326- - program: '.["foo"]'327- input: '{"foo": 42}'328- output: [42]329-330- - title: "Optional Object Identifier-Index: `.foo?`"331- body: |332-333- Just like `.foo`, but does not output even an error when `.`334- is not an array or an object.335-336- examples:337- - program: '.foo?'338- input: '{"foo": 42, "bar": "less interesting data"}'339- output: [42]340- - program: '.foo?'341- input: '{"notfoo": true, "alsonotfoo": false}'342- output: ['null']343- - program: '.["foo"]?'344- input: '{"foo": 42}'345- output: [42]346- - program: '[.foo?]'347- input: '[1,2]'348- output: ['[]']349-350- - title: "Generic Object Index: `.[<string>]`"351- body: |352-353- You can also look up fields of an object using syntax like354- `.["foo"]` (.foo above is a shorthand version of this, but355- only for identifier-like strings).356-357- - title: "Array Index: `.[2]`"358- body: |359-360- When the index value is an integer, `.[<value>]` can index361- arrays. Arrays are zero-based, so `.[2]` returns the third362- element.363-364- Negative indices are allowed, with -1 referring to the last365- element, -2 referring to the next to last element, and so on.366-367- examples:368- - program: '.[0]'369- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'370- output: ['{"name":"JSON", "good":true}']371-372- - program: '.[2]'373- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'374- output: ['null']375-376- - program: '.[-2]'377- input: '[1,2,3]'378- output: ['2']379-380- - title: "Array/String Slice: `.[10:15]`"381- body: |382-383- The `.[10:15]` syntax can be used to return a subarray of an384- array or substring of a string. The array returned by385- `.[10:15]` will be of length 5, containing the elements from386- index 10 (inclusive) to index 15 (exclusive). Either index may387- be negative (in which case it counts backwards from the end of388- the array), or omitted (in which case it refers to the start389- or end of the array).390-391- examples:392- - program: '.[2:4]'393- input: '["a","b","c","d","e"]'394- output: ['["c", "d"]']395-396- - program: '.[2:4]'397- input: '"abcdefghi"'398- output: ['"cd"']399-400- - program: '.[:3]'401- input: '["a","b","c","d","e"]'402- output: ['["a", "b", "c"]']403-404- - program: '.[-2:]'405- input: '["a","b","c","d","e"]'406- output: ['["d", "e"]']407-408- - title: "Array/Object Value Iterator: `.[]`"409- body: |410-411- If you use the `.[index]` syntax, but omit the index412- entirely, it will return *all* of the elements of an413- array. Running `.[]` with the input `[1,2,3]` will produce the414- numbers as three separate results, rather than as a single415- array.416-417- You can also use this on an object, and it will return all418- the values of the object.419-420- examples:421- - program: '.[]'422- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'423- output:424- - '{"name":"JSON", "good":true}'425- - '{"name":"XML", "good":false}'426-427- - program: '.[]'428- input: '[]'429- output: []430-431- - program: '.[]'432- input: '{"a": 1, "b": 1}'433- output: ['1', '1']434-435- - title: "`.[]?`"436- body: |437-438- Like `.[]`, but no errors will be output if . is not an array439- or object.440-441- - title: "Comma: `,`"442- body: |443-444- If two filters are separated by a comma, then the445- same input will be fed into both and the two filters' output446- value streams will be concatenated in order: first, all of the447- outputs produced by the left expression, and then all of the448- outputs produced by the right. For instance, filter `.foo,449- .bar`, produces both the "foo" fields and "bar" fields as450- separate outputs.451-452- examples:453- - program: '.foo, .bar'454- input: '{"foo": 42, "bar": "something else", "baz": true}'455- output: ['42', '"something else"']456-457- - program: ".user, .projects[]"458- input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'459- output: ['"stedolan"', '"jq"', '"wikiflow"']460-461- - program: '.[4,2]'462- input: '["a","b","c","d","e"]'463- output: ['"e"', '"c"']464-465- - title: "Pipe: `|`"466- body: |467-468- The | operator combines two filters by feeding the output(s) of469- the one on the left into the input of the one on the right. It's470- pretty much the same as the Unix shell's pipe, if you're used to471- that.472-473- If the one on the left produces multiple results, the one on474- the right will be run for each of those results. So, the475- expression `.[] | .foo` retrieves the "foo" field of each476- element of the input array.477-478- Note that `.a.b.c` is the same as `.a | .b | .c`.479-480- Note too that `.` is the input value at the particular stage481- in a "pipeline", specifically: where the `.` expression appears.482- Thus `.a | . | .b` is the same as `.a.b`, as the `.` in the483- middle refers to whatever value `.a` produced.484-485- examples:486- - program: '.[] | .name'487- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'488- output: ['"JSON"', '"XML"']489-490- - title: "Parenthesis"491- body: |492-493- Parenthesis work as a grouping operator just as in any typical494- programming language.495-496- examples:497- - program: '(. + 2) * 5'498- input: '1'499- output: [15]500-501- - title: Types and Values502- body: |503-504- jq supports the same set of datatypes as JSON - numbers,505- strings, booleans, arrays, objects (which in JSON-speak are506- hashes with only string keys), and "null".507-508- Booleans, null, strings and numbers are written the same way as509- in javascript. Just like everything else in jq, these simple510- values take an input and produce an output - `42` is a valid jq511- expression that takes an input, ignores it, and returns 42512- instead.513-514- entries:515- - title: "Array construction: `[]`"516- body: |517-518- As in JSON, `[]` is used to construct arrays, as in519- `[1,2,3]`. The elements of the arrays can be any jq520- expression, including a pipeline. All of the results produced521- by all of the expressions are collected into one big array.522- You can use it to construct an array out of a known quantity523- of values (as in `[.foo, .bar, .baz]`) or to "collect" all the524- results of a filter into an array (as in `[.items[].name]`)525-526- Once you understand the "," operator, you can look at jq's array527- syntax in a different light: the expression `[1,2,3]` is not using a528- built-in syntax for comma-separated arrays, but is instead applying529- the `[]` operator (collect results) to the expression 1,2,3 (which530- produces three different results).531-532- If you have a filter `X` that produces four results,533- then the expression `[X]` will produce a single result, an534- array of four elements.535-536- examples:537- - program: "[.user, .projects[]]"538- input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'539- output: ['["stedolan", "jq", "wikiflow"]']540- - program: "[ .[] | . * 2]"541- input: '[1, 2, 3]'542- output: ['[2, 4, 6]']543-544- - title: "Object Construction: `{}`"545- body: |546-547- Like JSON, `{}` is for constructing objects (aka548- dictionaries or hashes), as in: `{"a": 42, "b": 17}`.549-550- If the keys are "identifier-like", then the quotes can be left551- off, as in `{a:42, b:17}`. Keys generated by expressions need552- to be parenthesized, e.g., `{("a"+"b"):59}`.553-554- The value can be any expression (although you may need to555- wrap it in parentheses if it's a complicated one), which gets556- applied to the {} expression's input (remember, all filters557- have an input and an output).558-559- {foo: .bar}560-561- will produce the JSON object `{"foo": 42}` if given the JSON562- object `{"bar":42, "baz":43}` as its input. You can use this563- to select particular fields of an object: if the input is an564- object with "user", "title", "id", and "content" fields and565- you just want "user" and "title", you can write566-567- {user: .user, title: .title}568-569- Because that is so common, there's a shortcut syntax for it:570- `{user, title}`.571-572- If one of the expressions produces multiple results,573- multiple dictionaries will be produced. If the input's574-575- {"user":"stedolan","titles":["JQ Primer", "More JQ"]}576-577- then the expression578-579- {user, title: .titles[]}580-581- will produce two outputs:582-583- {"user":"stedolan", "title": "JQ Primer"}584- {"user":"stedolan", "title": "More JQ"}585-586- Putting parentheses around the key means it will be evaluated as an587- expression. With the same input as above,588-589- {(.user): .titles}590-591- produces592-593- {"stedolan": ["JQ Primer", "More JQ"]}594-595- examples:596- - program: '{user, title: .titles[]}'597- input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'598- output:599- - '{"user":"stedolan", "title": "JQ Primer"}'600- - '{"user":"stedolan", "title": "More JQ"}'601- - program: '{(.user): .titles}'602- input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'603- output: ['{"stedolan": ["JQ Primer", "More JQ"]}']604-605- - title: "Recursive Descent: `..`"606- body: |607-608- Recursively descends `.`, producing every value. This is the609- same as the zero-argument `recurse` builtin (see below). This610- is intended to resemble the XPath `//` operator. Note that611- `..a` does not work; use `..|.a` instead. In the example612- below we use `..|.a?` to find all the values of object keys613- "a" in any object found "below" `.`.614-615- This is particularly useful in conjunction with `path(EXP)`616- (also see below) and the `?` operator.617-618- examples:619- - program: '..|.a?'620- input: '[[{"a":1}]]'621- output: ['1']622-623- - title: Builtin operators and functions624- body: |625-626- Some jq operators (for instance, `+`) do different things627- depending on the type of their arguments (arrays, numbers,628- etc.). However, jq never does implicit type conversions. If you629- try to add a string to an object you'll get an error message and630- no result.631-632- entries:633- - title: "Addition: `+`"634- body: |635-636- The operator `+` takes two filters, applies them both637- to the same input, and adds the results together. What638- "adding" means depends on the types involved:639-640- - **Numbers** are added by normal arithmetic.641-642- - **Arrays** are added by being concatenated into a larger array.643-644- - **Strings** are added by being joined into a larger string.645-646- - **Objects** are added by merging, that is, inserting all647- the key-value pairs from both objects into a single648- combined object. If both objects contain a value for the649- same key, the object on the right of the `+` wins. (For650- recursive merge use the `*` operator.)651-652- `null` can be added to any value, and returns the other653- value unchanged.654-655- examples:656- - program: '.a + 1'657- input: '{"a": 7}'658- output: ['8']659- - program: '.a + .b'660- input: '{"a": [1,2], "b": [3,4]}'661- output: ['[1,2,3,4]']662- - program: '.a + null'663- input: '{"a": 1}'664- output: ['1']665- - program: '.a + 1'666- input: '{}'667- output: ['1']668- - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'669- input: 'null'670- output: ['{"a": 42, "b": 2, "c": 3}']671-672- - title: "Subtraction: `-`"673- body: |674-675- As well as normal arithmetic subtraction on numbers, the `-`676- operator can be used on arrays to remove all occurrences of677- the second array's elements from the first array.678-679- examples:680- - program: '4 - .a'681- input: '{"a":3}'682- output: ['1']683- - program: . - ["xml", "yaml"]684- input: '["xml", "yaml", "json"]'685- output: ['["json"]']686-687- - title: "Multiplication, division, modulo: `*`, `/`, and `%`"688- body: |689-690- These infix operators behave as expected when given two numbers.691- Division by zero raises an error. `x % y` computes x modulo y.692-693- Multiplying a string by a number produces the concatenation of694- that string that many times. `"x" * 0` produces **null**.695-696- Dividing a string by another splits the first using the second697- as separators.698-699- Multiplying two objects will merge them recursively: this works700- like addition but if both objects contain a value for the701- same key, and the values are objects, the two are merged with702- the same strategy.703-704- examples:705- - program: '10 / . * 3'706- input: 5707- output: [6]708- - program: '. / ", "'709- input: '"a, b,c,d, e"'710- output: ['["a","b,c,d","e"]']711- - program: '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'712- input: 'null'713- output: ['{"k": {"a": 0, "b": 2, "c": 3}}']714- - program: '.[] | (1 / .)?'715- input: '[1,0,-1]'716- output: ['1', '-1']717-718-719- - title: "`length`"720- body: |721-722- The builtin function `length` gets the length of various723- different types of value:724-725- - The length of a **string** is the number of Unicode726- codepoints it contains (which will be the same as its727- JSON-encoded length in bytes if it's pure ASCII).728-729- - The length of an **array** is the number of elements.730-731- - The length of an **object** is the number of key-value pairs.732-733- - The length of **null** is zero.734-735- examples:736- - program: '.[] | length'737- input: '[[1,2], "string", {"a":2}, null]'738- output: [2, 6, 1, 0]739-740-741- - title: "`utf8bytelength`"742- body: |743-744- The builtin function `utf8bytelength` outputs the number of745- bytes used to encode a string in UTF-8.746-747- examples:748- - program: 'utf8bytelength'749- input: '"\u03bc"'750- output: [2]751-752- - title: "`keys`, `keys_unsorted`"753- body: |754-755- The builtin function `keys`, when given an object, returns756- its keys in an array.757-758- The keys are sorted "alphabetically", by unicode codepoint759- order. This is not an order that makes particular sense in760- any particular language, but you can count on it being the761- same for any two objects with the same set of keys,762- regardless of locale settings.763-764- When `keys` is given an array, it returns the valid indices765- for that array: the integers from 0 to length-1.766-767- The `keys_unsorted` function is just like `keys`, but if768- the input is an object then the keys will not be sorted,769- instead the keys will roughly be in insertion order.770-771- examples:772- - program: 'keys'773- input: '{"abc": 1, "abcd": 2, "Foo": 3}'774- output: ['["Foo", "abc", "abcd"]']775- - program: 'keys'776- input: '[42,3,35]'777- output: ['[0,1,2]']778-779- - title: "`has(key)`"780- body: |781-782- The builtin function `has` returns whether the input object783- has the given key, or the input array has an element at the784- given index.785-786- `has($key)` has the same effect as checking whether `$key`787- is a member of the array returned by `keys`, although `has`788- will be faster.789-790- examples:791- - program: 'map(has("foo"))'792- input: '[{"foo": 42}, {}]'793- output: ['[true, false]']794- - program: 'map(has(2))'795- input: '[[0,1], ["a","b","c"]]'796- output: ['[false, true]']797-798- - title: "`in`"799- body: |800-801- The builtin function `in` returns whether or not the input key is in the802- given object, or the input index corresponds to an element803- in the given array. It is, essentially, an inversed version804- of `has`.805-806- examples:807- - program: '.[] | in({"foo": 42})'808- input: '["foo", "bar"]'809- output: ['true', 'false']810- - program: 'map(in([0,1]))'811- input: '[2, 0]'812- output: ['[false, true]']813-814- - title: "`map(x)`, `map_values(x)`"815- body: |816-817- For any filter `x`, `map(x)` will run that filter for each818- element of the input array, and return the outputs in a new819- array. `map(.+1)` will increment each element of an array of numbers.820-821- Similarly, `map_values(x)` will run that filter for each element,822- but it will return an object when an object is passed.823-824- `map(x)` is equivalent to `[.[] | x]`. In fact, this is how825- it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`.826-827- examples:828- - program: 'map(.+1)'829- input: '[1,2,3]'830- output: ['[2,3,4]']831-832- - program: 'map_values(.+1)'833- input: '{"a": 1, "b": 2, "c": 3}'834- output: ['{"a": 2, "b": 3, "c": 4}']835-836- - title: "`path(path_expression)`"837- body: |838-839- Outputs array representations of the given path expression840- in `.`. The outputs are arrays of strings (object keys)841- and/or numbers (array indices).842-843- Path expressions are jq expressions like `.a`, but also `.[]`.844- There are two types of path expressions: ones that can match845- exactly, and ones that cannot. For example, `.a.b.c` is an846- exact match path expression, while `.a[].b` is not.847-848- `path(exact_path_expression)` will produce the array849- representation of the path expression even if it does not850- exist in `.`, if `.` is `null` or an array or an object.851-852- `path(pattern)` will produce array representations of the853- paths matching `pattern` if the paths exist in `.`.854-855- Note that the path expressions are not different from normal856- expressions. The expression857- `path(..|select(type=="boolean"))` outputs all the paths to858- boolean values in `.`, and only those paths.859-860- examples:861- - program: 'path(.a[0].b)'862- input: 'null'863- output: ['["a",0,"b"]']864- - program: '[path(..)]'865- input: '{"a":[{"b":1}]}'866- output: ['[[],["a"],["a",0],["a",0,"b"]]']867-868- - title: "`del(path_expression)`"869- body: |870-871- The builtin function `del` removes a key and its corresponding872- value from an object.873-874- examples:875- - program: 'del(.foo)'876- input: '{"foo": 42, "bar": 9001, "baz": 42}'877- output: ['{"bar": 9001, "baz": 42}']878- - program: 'del(.[1, 2])'879- input: '["foo", "bar", "baz"]'880- output: ['["foo"]']881-882- - title: "`getpath(PATHS)`"883- body: |884-885- The builtin function `getpath` outputs the values in `.` found886- at each path in `PATHS`.887-888- examples:889- - program: 'getpath(["a","b"])'890- input: 'null'891- output: ['null']892- - program: '[getpath(["a","b"], ["a","c"])]'893- input: '{"a":{"b":0, "c":1}}'894- output: ['[0, 1]']895-896- - title: "`setpath(PATHS; VALUE)`"897- body: |898-899- The builtin function `setpath` sets the `PATHS` in `.` to `VALUE`.900-901- examples:902- - program: 'setpath(["a","b"]; 1)'903- input: 'null'904- output: ['{"a": {"b": 1}}']905- - program: 'setpath(["a","b"]; 1)'906- input: '{"a":{"b":0}}'907- output: ['{"a": {"b": 1}}']908- - program: 'setpath([0,"a"]; 1)'909- input: 'null'910- output: ['[{"a":1}]']911-912- - title: "`delpaths(PATHS)`"913- body: |914-915- The builtin function `delpaths` sets the `PATHS` in `.`.916- `PATHS` must be an array of paths, where each path is an array917- of strings and numbers.918-919- examples:920- - program: 'delpaths([["a","b"]])'921- input: '{"a":{"b":1},"x":{"y":2}}'922- output: ['{"a":{},"x":{"y":2}}']923-924- - title: "`to_entries`, `from_entries`, `with_entries`"925- body: |926-927- These functions convert between an object and an array of928- key-value pairs. If `to_entries` is passed an object, then929- for each `k: v` entry in the input, the output array930- includes `{"key": k, "value": v}`.931-932- `from_entries` does the opposite conversion, and933- `with_entries(foo)` is a shorthand for `to_entries |934- map(foo) | from_entries`, useful for doing some operation to935- all keys and values of an object. `from_entries` accepts key, Key,936- name, Name, value and Value as keys.937-938- examples:939- - program: 'to_entries'940- input: '{"a": 1, "b": 2}'941- output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']942- - program: 'from_entries'943- input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'944- output: ['{"a": 1, "b": 2}']945- - program: 'with_entries(.key |= "KEY_" + .)'946- input: '{"a": 1, "b": 2}'947- output: ['{"KEY_a": 1, "KEY_b": 2}']948-949-950- - title: "`select(boolean_expression)`"951- body: |952-953- The function `select(foo)` produces its input unchanged if954- `foo` returns true for that input, and produces no output955- otherwise.956-957- It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`958- will give you `[2,3]`.959-960- examples:961- - program: 'map(select(. >= 2))'962- input: '[1,5,3,0,7]'963- output: ['[5,3,7]']964- - program: '.[] | select(.id == "second")'965- input: '[{"id": "first", "val": 1}, {"id": "second", "val": 2}]'966- output: ['{"id": "second", "val": 2}']967-968-969- - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"970- body: |971-972- These built-ins select only inputs that are arrays, objects,973- iterables (arrays or objects), booleans, numbers, normal974- numbers, finite numbers, strings, null, non-null values, and975- non-iterables, respectively.976-977- examples:978- - program: '.[]|numbers'979- input: '[[],{},1,"foo",null,true,false]'980- output: ['1']981-982- - title: "`empty`"983- body: |984-985- `empty` returns no results. None at all. Not even `null`.986-987- It's useful on occasion. You'll know if you need it :)988-989- examples:990- - program: '1, empty, 2'991- input: 'null'992- output: [1, 2]993- - program: '[1,2,empty,3]'994- input: 'null'995- output: ['[1,2,3]']996-997- - title: "`error(message)`"998- body: |999-1000- Produces an error, just like `.a` applied to values other than1001- null and objects would, but with the given message as the1002- error's value. Errors can be caught with try/catch; see below.1003-1004- - title: "`halt`"1005- body: |1006-1007- Stops the jq program with no further outputs. jq will exit1008- with exit status `0`.1009-1010- - title: "`halt_error`, `halt_error(exit_code)`"1011- body: |1012-1013- Stops the jq program with no further outputs. The input will1014- be printed on `stderr` as raw output (i.e., strings will not1015- have double quotes) with no decoration, not even a newline.1016-1017- The given `exit_code` (defaulting to `5`) will be jq's exit1018- status.1019-1020- For example, `"Error: somthing went wrong\n"|halt_error(1)`.1021-1022- - title: "`$__loc__`"1023- body: |1024-1025- Produces an object with a "file" key and a "line" key, with1026- the filename and line number where `$__loc__` occurs, as1027- values.1028-1029- examples:1030- - program: 'try error("\($__loc__)") catch .'1031- input: 'null'1032- output: ['"{\"file\":\"<top-level>\",\"line\":1}"']1033-1034- - title: "`paths`, `paths(node_filter)`, `leaf_paths`"1035- body: |1036-1037- `paths` outputs the paths to all the elements in its input1038- (except it does not output the empty list, representing .1039- itself).1040-1041- `paths(f)` outputs the paths to any values for which `f` is true.1042- That is, `paths(numbers)` outputs the paths to all numeric1043- values.1044-1045- `leaf_paths` is an alias of `paths(scalars)`; `leaf_paths` is1046- *deprecated* and will be removed in the next major release.1047-1048- examples:1049- - program: '[paths]'1050- input: '[1,[[],{"a":2}]]'1051- output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']1052- - program: '[paths(scalars)]'1053- input: '[1,[[],{"a":2}]]'1054- output: ['[[0],[1,1,"a"]]']1055-1056- - title: "`add`"1057- body: |1058-1059- The filter `add` takes as input an array, and produces as1060- output the elements of the array added together. This might1061- mean summed, concatenated or merged depending on the types1062- of the elements of the input array - the rules are the same1063- as those for the `+` operator (described above).1064-1065- If the input is an empty array, `add` returns `null`.1066-1067- examples:1068- - program: add1069- input: '["a","b","c"]'1070- output: ['"abc"']1071- - program: add1072- input: '[1, 2, 3]'1073- output: [6]1074- - program: add1075- input: '[]'1076- output: ["null"]1077-1078- - title: "`any`, `any(condition)`, `any(generator; condition)`"1079- body: |1080-1081- The filter `any` takes as input an array of boolean values,1082- and produces `true` as output if any of the elements of1083- the array are `true`.1084-1085- If the input is an empty array, `any` returns `false`.1086-1087- The `any(condition)` form applies the given condition to the1088- elements of the input array.1089-1090- The `any(generator; condition)` form applies the given1091- condition to all the outputs of the given generator.1092-1093- examples:1094- - program: any1095- input: '[true, false]'1096- output: ["true"]1097- - program: any1098- input: '[false, false]'1099- output: ["false"]1100- - program: any1101- input: '[]'1102- output: ["false"]1103-1104- - title: "`all`, `all(condition)`, `all(generator; condition)`"1105- body: |1106-1107- The filter `all` takes as input an array of boolean values,1108- and produces `true` as output if all of the elements of1109- the array are `true`.1110-1111- The `all(condition)` form applies the given condition to the1112- elements of the input array.1113-1114- The `all(generator; condition)` form applies the given1115- condition to all the outputs of the given generator.1116-1117- If the input is an empty array, `all` returns `true`.1118-1119- examples:1120- - program: all1121- input: '[true, false]'1122- output: ["false"]1123- - program: all1124- input: '[true, true]'1125- output: ["true"]1126- - program: all1127- input: '[]'1128- output: ["true"]1129-1130- - title: "`flatten`, `flatten(depth)`"1131- body: |1132-1133- The filter `flatten` takes as input an array of nested arrays,1134- and produces a flat array in which all arrays inside the original1135- array have been recursively replaced by their values. You can pass1136- an argument to it to specify how many levels of nesting to flatten.1137-1138- `flatten(2)` is like `flatten`, but going only up to two1139- levels deep.1140-1141- examples:1142- - program: flatten1143- input: '[1, [2], [[3]]]'1144- output: ["[1, 2, 3]"]1145- - program: flatten(1)1146- input: '[1, [2], [[3]]]'1147- output: ["[1, 2, [3]]"]1148- - program: flatten1149- input: '[[]]'1150- output: ["[]"]1151- - program: flatten1152- input: '[{"foo": "bar"}, [{"foo": "baz"}]]'1153- output: ['[{"foo": "bar"}, {"foo": "baz"}]']1154-1155- - title: "`range(upto)`, `range(from;upto)` `range(from;upto;by)`"1156- body: |1157-1158- The `range` function produces a range of numbers. `range(4;10)`1159- produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers1160- are produced as separate outputs. Use `[range(4;10)]` to get a range as1161- an array.1162-1163- The one argument form generates numbers from 0 to the given1164- number, with an increment of 1.1165-1166- The two argument form generates numbers from `from` to `upto`1167- with an increment of 1.1168-1169- The three argument form generates numbers `from` to `upto`1170- with an increment of `by`.1171-1172- examples:1173- - program: 'range(2;4)'1174- input: 'null'1175- output: ['2', '3']1176- - program: '[range(2;4)]'1177- input: 'null'1178- output: ['[2,3]']1179- - program: '[range(4)]'1180- input: 'null'1181- output: ['[0,1,2,3]']1182- - program: '[range(0;10;3)]'1183- input: 'null'1184- output: ['[0,3,6,9]']1185- - program: '[range(0;10;-1)]'1186- input: 'null'1187- output: ['[]']1188- - program: '[range(0;-5;-1)]'1189- input: 'null'1190- output: ['[0,-1,-2,-3,-4]']1191-1192- - title: "`floor`"1193- body: |1194-1195- The `floor` function returns the floor of its numeric input.1196-1197- examples:1198- - program: 'floor'1199- input: '3.14159'1200- output: ['3']1201-1202- - title: "`sqrt`"1203- body: |1204-1205- The `sqrt` function returns the square root of its numeric input.1206-1207- examples:1208- - program: 'sqrt'1209- input: '9'1210- output: ['3']1211-1212- - title: "`tonumber`"1213- body: |1214-1215- The `tonumber` function parses its input as a number. It1216- will convert correctly-formatted strings to their numeric1217- equivalent, leave numbers alone, and give an error on all other input.1218-1219- examples:1220- - program: '.[] | tonumber'1221- input: '[1, "1"]'1222- output: [1, 1]1223-1224- - title: "`tostring`"1225- body: |1226-1227- The `tostring` function prints its input as a1228- string. Strings are left unchanged, and all other values are1229- JSON-encoded.1230-1231- examples:1232- - program: '.[] | tostring'1233- input: '[1, "1", [1]]'1234- output: ['"1"', '"1"', '"[1]"']1235-1236- - title: "`type`"1237- body: |1238-1239- The `type` function returns the type of its argument as a1240- string, which is one of null, boolean, number, string, array1241- or object.1242-1243- examples:1244- - program: 'map(type)'1245- input: '[0, false, [], {}, null, "hello"]'1246- output: ['["number", "boolean", "array", "object", "null", "string"]']1247-1248- - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1249- body: |1250-1251- Some arithmetic operations can yield infinities and "not a1252- number" (NaN) values. The `isinfinite` builtin returns `true`1253- if its input is infinite. The `isnan` builtin returns `true`1254- if its input is a NaN. The `infinite` builtin returns a1255- positive infinite value. The `nan` builtin returns a NaN.1256- The `isnormal` builtin returns true if its input is a normal1257- number.1258-1259- Note that division by zero raises an error.1260-1261- Currently most arithmetic operations operating on infinities,1262- NaNs, and sub-normals do not raise errors.1263-1264- examples:1265- - program: '.[] | (infinite * .) < 0'1266- input: '[-1, 1]'1267- output: ['true', 'false']1268- - program: 'infinite, nan | type'1269- input: 'null'1270- output: ['"number"', '"number"']1271-1272- - title: "`sort, sort_by(path_expression)`"1273- body: |1274-1275- The `sort` functions sorts its input, which must be an1276- array. Values are sorted in the following order:1277-1278- * `null`1279- * `false`1280- * `true`1281- * numbers1282- * strings, in alphabetical order (by unicode codepoint value)1283- * arrays, in lexical order1284- * objects1285-1286- The ordering for objects is a little complex: first they're1287- compared by comparing their sets of keys (as arrays in1288- sorted order), and if their keys are equal then the values1289- are compared key by key.1290-1291- `sort` may be used to sort by a particular field of an1292- object, or by applying any jq filter.1293-1294- `sort_by(foo)` compares two elements by comparing the result of1295- `foo` on each element.1296-1297- examples:1298- - program: 'sort'1299- input: '[8,3,null,6]'1300- output: ['[null,3,6,8]']1301- - program: 'sort_by(.foo)'1302- input: '[{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}]'1303- output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']1304-1305- - title: "`group_by(path_expression)`"1306- body: |1307-1308- `group_by(.foo)` takes as input an array, groups the1309- elements having the same `.foo` field into separate arrays,1310- and produces all of these arrays as elements of a larger1311- array, sorted by the value of the `.foo` field.1312-1313- Any jq expression, not just a field access, may be used in1314- place of `.foo`. The sorting order is the same as described1315- in the `sort` function above.1316-1317- examples:1318- - program: 'group_by(.foo)'1319- input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'1320- output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']1321-1322- - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1323- body: |1324-1325- Find the minimum or maximum element of the input array.1326-1327- The `min_by(path_exp)` and `max_by(path_exp)` functions allow1328- you to specify a particular field or property to examine, e.g.1329- `min_by(.foo)` finds the object with the smallest `foo` field.1330-1331- examples:1332- - program: 'min'1333- input: '[5,4,2,7]'1334- output: ['2']1335- - program: 'max_by(.foo)'1336- input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'1337- output: ['{"foo":2, "bar":3}']1338-1339- - title: "`unique`, `unique_by(path_exp)`"1340- body: |1341-1342- The `unique` function takes as input an array and produces1343- an array of the same elements, in sorted order, with1344- duplicates removed.1345-1346- The `unique_by(path_exp)` function will keep only one element1347- for each value obtained by applying the argument. Think of it1348- as making an array by taking one element out of every group1349- produced by `group`.1350-1351- examples:1352- - program: 'unique'1353- input: '[1,2,5,3,5,3,1,3]'1354- output: ['[1,2,3,5]']1355- - program: 'unique_by(.foo)'1356- input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'1357- output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']1358- - program: 'unique_by(length)'1359- input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'1360- output: ['["bacon", "chunky", "asparagus"]']1361-1362- - title: "`reverse`"1363- body: |1364-1365- This function reverses an array.1366-1367- examples:1368- - program: 'reverse'1369- input: '[1,2,3,4]'1370- output: ['[4,3,2,1]']1371-1372- - title: "`contains(element)`"1373- body: |1374-1375- The filter `contains(b)` will produce true if b is1376- completely contained within the input. A string B is1377- contained in a string A if B is a substring of A. An array B1378- is contained in an array A if all elements in B are1379- contained in any element in A. An object B is contained in1380- object A if all of the values in B are contained in the1381- value in A with the same key. All other types are assumed to1382- be contained in each other if they are equal.1383-1384- examples:1385- - program: 'contains("bar")'1386- input: '"foobar"'1387- output: ['true']1388- - program: 'contains(["baz", "bar"])'1389- input: '["foobar", "foobaz", "blarp"]'1390- output: ['true']1391- - program: 'contains(["bazzzzz", "bar"])'1392- input: '["foobar", "foobaz", "blarp"]'1393- output: ['false']1394- - program: 'contains({foo: 12, bar: [{barp: 12}]})'1395- input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1396- output: ['true']1397- - program: 'contains({foo: 12, bar: [{barp: 15}]})'1398- input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1399- output: ['false']1400-1401- - title: "`indices(s)`"1402- body: |1403-1404- Outputs an array containing the indices in `.` where `s`1405- occurs. The input may be an array, in which case if `s` is an1406- array then the indices output will be those where all elements1407- in `.` match those of `s`.1408-1409- examples:1410- - program: 'indices(", ")'1411- input: '"a,b, cd, efg, hijk"'1412- output: ['[3,7,12]']1413- - program: 'indices(1)'1414- input: '[0,1,2,1,3,1,4]'1415- output: ['[1,3,5]']1416- - program: 'indices([1,2])'1417- input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1418- output: ['[1,8]']1419-1420- - title: "`index(s)`, `rindex(s)`"1421- body: |1422-1423- Outputs the index of the first (`index`) or last (`rindex`)1424- occurrence of `s` in the input.1425-1426- examples:1427- - program: 'index(", ")'1428- input: '"a,b, cd, efg, hijk"'1429- output: ['3']1430- - program: 'rindex(", ")'1431- input: '"a,b, cd, efg, hijk"'1432- output: ['12']1433-1434- - title: "`inside`"1435- body: |1436-1437- The filter `inside(b)` will produce true if the input is1438- completely contained within b. It is, essentially, an1439- inversed version of `contains`.1440-1441- examples:1442- - program: 'inside("foobar")'1443- input: '"bar"'1444- output: ['true']1445- - program: 'inside(["foobar", "foobaz", "blarp"])'1446- input: '["baz", "bar"]'1447- output: ['true']1448- - program: 'inside(["foobar", "foobaz", "blarp"])'1449- input: '["bazzzzz", "bar"]'1450- output: ['false']1451- - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1452- input: '{"foo": 12, "bar": [{"barp": 12}]}'1453- output: ['true']1454- - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1455- input: '{"foo": 12, "bar": [{"barp": 15}]}'1456- output: ['false']1457-1458- - title: "`startswith(str)`"1459- body: |1460-1461- Outputs `true` if . starts with the given string argument.1462-1463- examples:1464- - program: '[.[]|startswith("foo")]'1465- input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1466- output: ['[false, true, false, true, false]']1467-1468- - title: "`endswith(str)`"1469- body: |1470-1471- Outputs `true` if . ends with the given string argument.1472-1473- examples:1474- - program: '[.[]|endswith("foo")]'1475- input: '["foobar", "barfoo"]'1476- output: ['[false, true]']1477-1478- - title: "`combinations`, `combinations(n)`"1479- body: |1480-1481- Outputs all combinations of the elements of the arrays in the1482- input array. If given an argument `n`, it outputs all combinations1483- of `n` repetitions of the input array.1484-1485- examples:1486- - program: 'combinations'1487- input: '[[1,2], [3, 4]]'1488- output: ['[1, 3]', '[1, 4]', '[2, 3]', '[2, 4]']1489- - program: 'combinations(2)'1490- input: '[0, 1]'1491- output: ['[0, 0]', '[0, 1]', '[1, 0]', '[1, 1]']1492-1493- - title: "`ltrimstr(str)`"1494- body: |1495-1496- Outputs its input with the given prefix string removed, if it1497- starts with it.1498-1499- examples:1500- - program: '[.[]|ltrimstr("foo")]'1501- input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1502- output: ['["fo","","barfoo","bar","afoo"]']1503-1504- - title: "`rtrimstr(str)`"1505- body: |1506-1507- Outputs its input with the given suffix string removed, if it1508- ends with it.1509-1510- examples:1511- - program: '[.[]|rtrimstr("foo")]'1512- input: '["fo", "foo", "barfoo", "foobar", "foob"]'1513- output: ['["fo","","bar","foobar","foob"]']1514-1515- - title: "`explode`"1516- body: |1517-1518- Converts an input string into an array of the string's1519- codepoint numbers.1520-1521- examples:1522- - program: 'explode'1523- input: '"foobar"'1524- output: ['[102,111,111,98,97,114]']1525-1526- - title: "`implode`"1527- body: |1528-1529- The inverse of explode.1530-1531- examples:1532- - program: 'implode'1533- input: '[65, 66, 67]'1534- output: ['"ABC"']1535-1536- - title: "`split(str)`"1537- body: |1538-1539- Splits an input string on the separator argument.1540-1541- examples:1542- - program: 'split(", ")'1543- input: '"a, b,c,d, e, "'1544- output: ['["a","b,c,d","e",""]']1545-1546- - title: "`join(str)`"1547- body: |1548-1549- Joins the array of elements given as input, using the1550- argument as separator. It is the inverse of `split`: that is,1551- running `split("foo") | join("foo")` over any input string1552- returns said input string.1553-1554- Numbers and booleans in the input are converted to strings.1555- Null values are treated as empty strings. Arrays and objects1556- in the input are not supported.1557-1558- examples:1559- - program: 'join(", ")'1560- input: '["a","b,c,d","e"]'1561- output: ['"a, b,c,d, e"']1562- - program: 'join(" ")'1563- input: '["a",1,2.3,true,null,false]'1564- output: ['"a 1 2.3 true false"']1565-1566- - title: "`ascii_downcase`, `ascii_upcase`"1567- body: |1568-1569- Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1570- converted to the specified case.1571-1572- example:1573- - program: 'ascii_upcase'1574- input: '"useful but not for é"'1575- output: '"USEFUL BUT NOT FOR é"'1576-1577- - title: "`while(cond; update)`"1578- body: |1579-1580- The `while(cond; update)` function allows you to repeatedly1581- apply an update to `.` until `cond` is false.1582-1583- Note that `while(cond; update)` is internally defined as a1584- recursive jq function. Recursive calls within `while` will1585- not consume additional memory if `update` produces at most one1586- output for each input. See advanced topics below.1587-1588- examples:1589- - program: '[while(.<100; .*2)]'1590- input: '1'1591- output: ['[1,2,4,8,16,32,64]']1592-1593- - title: "`until(cond; next)`"1594- body: |1595-1596- The `until(cond; next)` function allows you to repeatedly1597- apply the expression `next`, initially to `.` then to its own1598- output, until `cond` is true. For example, this can be used1599- to implement a factorial function (see below).1600-1601- Note that `until(cond; next)` is internally defined as a1602- recursive jq function. Recursive calls within `until()` will1603- not consume additional memory if `next` produces at most one1604- output for each input. See advanced topics below.1605-1606- examples:1607- - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1608- input: '4'1609- output: ['24']1610-1611-1612- - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`, `recurse_down`"1613- body: |1614-1615- The `recurse(f)` function allows you to search through a1616- recursive structure, and extract interesting data from all1617- levels. Suppose your input represents a filesystem:1618-1619- {"name": "/", "children": [1620- {"name": "/bin", "children": [1621- {"name": "/bin/ls", "children": []},1622- {"name": "/bin/sh", "children": []}]},1623- {"name": "/home", "children": [1624- {"name": "/home/stephen", "children": [1625- {"name": "/home/stephen/jq", "children": []}]}]}]}1626-1627- Now suppose you want to extract all of the filenames1628- present. You need to retrieve `.name`, `.children[].name`,1629- `.children[].children[].name`, and so on. You can do this1630- with:1631-1632- recurse(.children[]) | .name1633-1634- When called without an argument, `recurse` is equivalent to1635- `recurse(.[]?)`.1636-1637- `recurse(f)` is identical to `recurse(f; . != null)` and can be1638- used without concerns about recursion depth.1639-1640- `recurse(f; condition)` is a generator which begins by1641- emitting . and then emits in turn .|f, .|f|f, .|f|f|f, ... so long1642- as the computed value satisfies the condition. For example,1643- to generate all the integers, at least in principle, one1644- could write `recurse(.+1; true)`.1645-1646- For legacy reasons, `recurse_down` exists as an alias to1647- calling `recurse` without arguments. This alias is considered1648- *deprecated* and will be removed in the next major release.1649-1650- The recursive calls in `recurse` will not consume additional1651- memory whenever `f` produces at most a single output for each1652- input.1653-1654- examples:1655- - program: 'recurse(.foo[])'1656- input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'1657- output:1658- - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'1659- - '{"foo":[]}'1660- - '{"foo":[{"foo":[]}]}'1661- - '{"foo":[]}'1662-1663- - program: 'recurse'1664- input: '{"a":0,"b":[1]}'1665- output:1666- - '{"a":0,"b":[1]}'1667- - '0'1668- - '[1]'1669- - '1'1670-1671- - program: 'recurse(. * .; . < 20)'1672- input: 21673- output:1674- - 21675- - 41676- - 161677-1678- - title: "`walk(f)`"1679- body: |1680-1681- The `walk(f)` function applies f recursively to every1682- component of the input entity. When an array is1683- encountered, f is first applied to its elements and then to1684- the array itself; when an object is encountered, f is first1685- applied to all the values and then to the object. In1686- practice, f will usually test the type of its input, as1687- illustrated in the following examples. The first example1688- highlights the usefulness of processing the elements of an1689- array of arrays before processing the array itself. The second1690- example shows how all the keys of all the objects within the1691- input can be considered for alteration.1692-1693- examples:1694- - program: 'walk(if type == "array" then sort else . end)'1695- input: '[[4, 1, 7], [8, 5, 2], [3, 6, 9]]'1696- output:1697- - '[[1,4,7],[2,5,8],[3,6,9]]'1698-1699- - program: 'walk( if type == "object" then with_entries( .key |= sub( "^_+"; "") ) else . end )'1700- input: '[ { "_a": { "__b": 2 } } ]'1701- output:1702- - '[{"a":{"b":2}}]'1703-1704- - title: "`$ENV`, `env`"1705- body: |1706-1707- `$ENV` is an object representing the environment variables as1708- set when the jq program started.1709-1710- `env` outputs an object representing jq's current environment.1711-1712- At the moment there is no builtin for setting environment1713- variables.1714-1715- examples:1716- - program: '$ENV.PAGER'1717- input: 'null'1718- output: ['"less"']1719-1720- - program: 'env.PAGER'1721- input: 'null'1722- output: ['"less"']1723-1724- - title: "`transpose`"1725- body: |1726-1727- Transpose a possibly jagged matrix (an array of arrays).1728- Rows are padded with nulls so the result is always rectangular.1729-1730- examples:1731- - program: 'transpose'1732- input: '[[1], [2,3]]'1733- output: ['[[1,2],[null,3]]']1734-1735- - title: "`bsearch(x)`"1736- body: |1737-1738- bsearch(x) conducts a binary search for x in the input1739- array. If the input is sorted and contains x, then1740- bsearch(x) will return its index in the array; otherwise, if1741- the array is sorted, it will return (-1 - ix) where ix is an1742- insertion point such that the array would still be sorted1743- after the insertion of x at ix. If the array is not sorted,1744- bsearch(x) will return an integer that is probably of no1745- interest.1746-1747- examples:1748- - program: 'bsearch(0)'1749- input: '[0,1]'1750- output: ['0']1751- - program: 'bsearch(0)'1752- input: '[1,2,3]'1753- output: ['-1']1754- - program: 'bsearch(4) as $ix | if $ix < 0 then .[-(1+$ix)] = 4 else . end'1755- input: '[1,2,3]'1756- output: ['[1,2,3,4]']1757-1758- - title: "String interpolation - `\\(foo)`"1759- body: |1760-1761- Inside a string, you can put an expression inside parens1762- after a backslash. Whatever the expression returns will be1763- interpolated into the string.1764-1765- examples:1766- - program: '"The input was \(.), which is one less than \(.+1)"'1767- input: '42'1768- output: ['"The input was 42, which is one less than 43"']1769-1770- - title: "Convert to/from JSON"1771- body: |1772-1773- The `tojson` and `fromjson` builtins dump values as JSON texts1774- or parse JSON texts into values, respectively. The tojson1775- builtin differs from tostring in that tostring returns strings1776- unmodified, while tojson encodes strings as JSON strings.1777-1778- examples:1779- - program: '[.[]|tostring]'1780- input: '[1, "foo", ["foo"]]'1781- output: ['["1","foo","[\"foo\"]"]']1782- - program: '[.[]|tojson]'1783- input: '[1, "foo", ["foo"]]'1784- output: ['["1","\"foo\"","[\"foo\"]"]']1785- - program: '[.[]|tojson|fromjson]'1786- input: '[1, "foo", ["foo"]]'1787- output: ['[1,"foo",["foo"]]']1788-1789- - title: "Format strings and escaping"1790- body: |1791-1792- The `@foo` syntax is used to format and escape strings,1793- which is useful for building URLs, documents in a language1794- like HTML or XML, and so forth. `@foo` can be used as a1795- filter on its own, the possible escapings are:1796-1797- * `@text`:1798-1799- Calls `tostring`, see that function for details.1800-1801- * `@json`:1802-1803- Serializes the input as JSON.1804-1805- * `@html`:1806-1807- Applies HTML/XML escaping, by mapping the characters1808- `<>&'"` to their entity equivalents `<`, `>`,1809- `&`, `'`, `"`.1810-1811- * `@uri`:1812-1813- Applies percent-encoding, by mapping all reserved URI1814- characters to a `%XX` sequence.1815-1816- * `@csv`:1817-1818- The input must be an array, and it is rendered as CSV1819- with double quotes for strings, and quotes escaped by1820- repetition.1821-1822- * `@tsv`:1823-1824- The input must be an array, and it is rendered as TSV1825- (tab-separated values). Each input array will be printed as1826- a single line. Fields are separated by a single1827- tab (ascii `0x09`). Input characters line-feed (ascii `0x0a`),1828- carriage-return (ascii `0x0d`), tab (ascii `0x09`) and1829- backslash (ascii `0x5c`) will be output as escape sequences1830- `\n`, `\r`, `\t`, `\\` respectively.1831-1832- * `@sh`:1833-1834- The input is escaped suitable for use in a command-line1835- for a POSIX shell. If the input is an array, the output1836- will be a series of space-separated strings.1837-1838- * `@base64`:1839-1840- The input is converted to base64 as specified by RFC 4648.1841-1842- * `@base64d`:1843-1844- The inverse of `@base64`, input is decoded as specified by RFC 4648.1845- Note\: If the decoded string is not UTF-8, the results are undefined.1846-1847- This syntax can be combined with string interpolation in a1848- useful way. You can follow a `@foo` token with a string1849- literal. The contents of the string literal will *not* be1850- escaped. However, all interpolations made inside that string1851- literal will be escaped. For instance,1852-1853- @uri "https://www.google.com/search?q=\(.search)"1854-1855- will produce the following output for the input1856- `{"search":"what is jq?"}`:1857-1858- "https://www.google.com/search?q=what%20is%20jq%3F"1859-1860- Note that the slashes, question mark, etc. in the URL are1861- not escaped, as they were part of the string literal.1862-1863- examples:1864- - program: '@html'1865- input: '"This works if x < y"'1866- output: ['"This works if x < y"']1867-1868-# - program: '@html "<span>Anonymous said: \(.)</span>"'1869-# input: '"<script>alert(\"lol hax\");</script>"'1870-# output: ["<span>Anonymous said: <script>alert("lol hax");</script></span>"]1871-1872- - program: '@sh "echo \(.)"'1873- input: "\"O'Hara's Ale\""1874- output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]1875-1876- - program: '@base64'1877- input: '"This is a message"'1878- output: ['"VGhpcyBpcyBhIG1lc3NhZ2U="']1879-1880- - program: '@base64d'1881- input: '"VGhpcyBpcyBhIG1lc3NhZ2U="'1882- output: ['"This is a message"']1883-1884- - title: "Dates"1885- body: |1886-1887- jq provides some basic date handling functionality, with some1888- high-level and low-level builtins. In all cases these1889- builtins deal exclusively with time in UTC.1890-1891- The `fromdateiso8601` builtin parses datetimes in the ISO 86011892- format to a number of seconds since the Unix epoch1893- (1970-01-01T00:00:00Z). The `todateiso8601` builtin does the1894- inverse.1895-1896- The `fromdate` builtin parses datetime strings. Currently1897- `fromdate` only supports ISO 8601 datetime strings, but in the1898- future it will attempt to parse datetime strings in more1899- formats.1900-1901- The `todate` builtin is an alias for `todateiso8601`.1902-1903- The `now` builtin outputs the current time, in seconds since1904- the Unix epoch.1905-1906- Low-level jq interfaces to the C-library time functions are1907- also provided: `strptime`, `strftime`, `strflocaltime`,1908- `mktime`, `gmtime`, and `localtime`. Refer to your host1909- operating system's documentation for the format strings used1910- by `strptime` and `strftime`. Note: these are not necessarily1911- stable interfaces in jq, particularly as to their localization1912- functionality.1913-1914- The `gmtime` builtin consumes a number of seconds since the1915- Unix epoch and outputs a "broken down time" representation of1916- Greenwhich Meridian time as an array of numbers representing1917- (in this order): the year, the month (zero-based), the day of1918- the month (one-based), the hour of the day, the minute of the1919- hour, the second of the minute, the day of the week, and the1920- day of the year -- all one-based unless otherwise stated. The1921- day of the week number may be wrong on some systems for dates1922- before March 1st 1900, or after December 31 2099.1923-1924- The `localtime` builtin works like the `gmtime` builtin, but1925- using the local timezone setting.1926-1927- The `mktime` builtin consumes "broken down time"1928- representations of time output by `gmtime` and `strptime`.1929-1930- The `strptime(fmt)` builtin parses input strings matching the1931- `fmt` argument. The output is in the "broken down time"1932- representation consumed by `gmtime` and output by `mktime`.1933-1934- The `strftime(fmt)` builtin formats a time (GMT) with the1935- given format. The `strflocaltime` does the same, but using1936- the local timezone setting.1937-1938- The format strings for `strptime` and `strftime` are described1939- in typical C library documentation. The format string for ISO1940- 8601 datetime is `"%Y-%m-%dT%H:%M:%SZ"`.1941-1942- jq may not support some or all of this date functionality on1943- some systems. In particular, the `%u` and `%j` specifiers for1944- `strptime(fmt)` are not supported on macOS.1945-1946- examples:1947- - program: 'fromdate'1948- input: '"2015-03-05T23:51:47Z"'1949- output: ['1425599507']1950-1951- - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")'1952- input: '"2015-03-05T23:51:47Z"'1953- output: ['[2015,2,5,23,51,47,4,63]']1954-1955- - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'1956- input: '"2015-03-05T23:51:47Z"'1957- output: ['1425599507']1958-1959- - title: "SQL-Style Operators"1960- body: |1961-1962- jq provides a few SQL-style operators.1963-1964- * INDEX(stream; index_expression):1965-1966- This builtin produces an object whose keys are computed by1967- the given index expression applied to each value from the1968- given stream.1969-1970- * JOIN($idx; stream; idx_expr; join_expr):1971-1972- This builtin joins the values from the given stream to the1973- given index. The index's keys are computed by applying the1974- given index expression to each value from the given stream.1975- An array of the value in the stream and the corresponding1976- value from the index is fed to the given join expression to1977- produce each result.1978-1979- * JOIN($idx; stream; idx_expr):1980-1981- Same as `JOIN($idx; stream; idx_expr; .)`.1982-1983- * JOIN($idx; idx_expr):1984-1985- This builtin joins the input `.` to the given index, applying1986- the given index expression to `.` to compute the index key.1987- The join operation is as described above.1988-1989- * IN(s):1990-1991- This builtin outputs `true` if `.` appears in the given1992- stream, otherwise it outputs `false`.1993-1994- * IN(source; s):1995-1996- This builtin outputs `true` if any value in the source stream1997- appears in the second stream, otherwise it outputs `false`.1998-1999- - title: "`builtins`"2000- body: |2001-2002- Returns a list of all builtin functions in the format `name/arity`.2003- Since functions with the same name but different arities are considered2004- separate functions, `all/0`, `all/1`, and `all/2` would all be present2005- in the list.2006-2007- - title: Conditionals and Comparisons2008- entries:2009- - title: "`==`, `!=`"2010- body: |2011-2012- The expression 'a == b' will produce 'true' if the result of a and b2013- are equal (that is, if they represent equivalent JSON documents) and2014- 'false' otherwise. In particular, strings are never considered equal2015- to numbers. If you're coming from Javascript, jq's == is like2016- Javascript's === - considering values equal only when they have the2017- same type as well as the same value.2018-2019- != is "not equal", and 'a != b' returns the opposite value of 'a == b'2020-2021- examples:2022- - program: '.[] == 1'2023- input: '[1, 1.0, "1", "banana"]'2024- output: ['true', 'true', 'false', 'false']2025-2026- - title: if-then-else2027- body: |2028-2029- `if A then B else C end` will act the same as `B` if `A`2030- produces a value other than false or null, but act the same2031- as `C` otherwise.2032-2033- Checking for false or null is a simpler notion of2034- "truthiness" than is found in Javascript or Python, but it2035- means that you'll sometimes have to be more explicit about2036- the condition you want: you can't test whether, e.g. a2037- string is empty using `if .name then A else B end`, you'll2038- need something more like `if (.name | length) > 0 then A else2039- B end` instead.2040-2041- If the condition `A` produces multiple results, then `B` is evaluated2042- once for each result that is not false or null, and `C` is evaluated2043- once for each false or null.2044-2045- More cases can be added to an if using `elif A then B` syntax.2046-2047- examples:2048- - program: |-2049- if . == 0 then2050- "zero"2051- elif . == 1 then2052- "one"2053- else2054- "many"2055- end2056- input: 22057- output: ['"many"']2058-2059- - title: "`>, >=, <=, <`"2060- body: |2061-2062- The comparison operators `>`, `>=`, `<=`, `<` return whether2063- their left argument is greater than, greater than or equal2064- to, less than or equal to or less than their right argument2065- (respectively).2066-2067- The ordering is the same as that described for `sort`, above.2068-2069- examples:2070- - program: '. < 5'2071- input: 22072- output: ['true']2073-2074- - title: and/or/not2075- body: |2076-2077- jq supports the normal Boolean operators and/or/not. They have the2078- same standard of truth as if expressions - false and null are2079- considered "false values", and anything else is a "true value".2080-2081- If an operand of one of these operators produces multiple2082- results, the operator itself will produce a result for each input.2083-2084- `not` is in fact a builtin function rather than an operator,2085- so it is called as a filter to which things can be piped2086- rather than with special syntax, as in `.foo and .bar |2087- not`.2088-2089- These three only produce the values "true" and "false", and2090- so are only useful for genuine Boolean operations, rather2091- than the common Perl/Python/Ruby idiom of2092- "value_that_may_be_null or default". If you want to use this2093- form of "or", picking between two values rather than2094- evaluating a condition, see the "//" operator below.2095-2096- examples:2097- - program: '42 and "a string"'2098- input: 'null'2099- output: ['true']2100- - program: '(true, false) or false'2101- input: 'null'2102- output: ['true', 'false']2103-# - program: '(true, false) and (true, false)'2104-# input: 'null'2105-# output: ['true', 'false', 'false', 'false']2106- - program: '(true, true) and (true, false)'2107- input: 'null'2108- output: ['true', 'false', 'true', 'false']2109- - program: '[true, false | not]'2110- input: 'null'2111- output: ['[false, true]']2112-2113- - title: "Alternative operator: `//`"2114- body: |2115-2116- A filter of the form `a // b` produces the same2117- results as `a`, if `a` produces results other than `false`2118- and `null`. Otherwise, `a // b` produces the same results as `b`.2119-2120- This is useful for providing defaults: `.foo // 1` will2121- evaluate to `1` if there's no `.foo` element in the2122- input. It's similar to how `or` is sometimes used in Python2123- (jq's `or` operator is reserved for strictly Boolean2124- operations).2125-2126- examples:2127- - program: '.foo // 42'2128- input: '{"foo": 19}'2129- output: [19]2130- - program: '.foo // 42'2131- input: '{}'2132- output: [42]2133-2134- - title: try-catch2135- body: |2136-2137- Errors can be caught by using `try EXP catch EXP`. The first2138- expression is executed, and if it fails then the second is2139- executed with the error message. The output of the handler,2140- if any, is output as if it had been the output of the2141- expression to try.2142-2143- The `try EXP` form uses `empty` as the exception handler.2144-2145- examples:2146- - program: 'try .a catch ". is not an object"'2147- input: 'true'2148- output: ['". is not an object"']2149- - program: '[.[]|try .a]'2150- input: '[{}, true, {"a":1}]'2151- output: ['[null, 1]']2152- - program: 'try error("some exception") catch .'2153- input: 'true'2154- output: ['"some exception"']2155-2156- - title: Breaking out of control structures2157- body: |2158-2159- A convenient use of try/catch is to break out of control2160- structures like `reduce`, `foreach`, `while`, and so on.2161-2162- For example:2163-2164- # Repeat an expression until it raises "break" as an2165- # error, then stop repeating without re-raising the error.2166- # But if the error caught is not "break" then re-raise it.2167- try repeat(exp) catch .=="break" then empty else error;2168-2169- jq has a syntax for named lexical labels to "break" or "go (back) to":2170-2171- label $out | ... break $out ...2172-2173- The `break $label_name` expression will cause the program to2174- to act as though the nearest (to the left) `label $label_name`2175- produced `empty`.2176-2177- The relationship between the `break` and corresponding `label`2178- is lexical: the label has to be "visible" from the break.2179-2180- To break out of a `reduce`, for example:2181-2182- label $out | reduce .[] as $item (null; if .==false then break $out else ... end)2183-2184- The following jq program produces a syntax error:2185-2186- break $out2187-2188- because no label `$out` is visible.2189-2190- - title: "Error Suppression / Optional Operator: `?`"2191- body: |2192-2193- The `?` operator, used as `EXP?`, is shorthand for `try EXP`.2194-2195- examples:2196- - program: '[.[]|(.a)?]'2197- input: '[{}, true, {"a":1}]'2198- output: ['[null, 1]']2199-2200-2201- - title: Regular expressions (PCRE)2202- body: |2203-2204- jq uses the Oniguruma regular expression library, as do php,2205- ruby, TextMate, Sublime Text, etc, so the description here2206- will focus on jq specifics.2207-2208- The jq regex filters are defined so that they can be used using2209- one of these patterns:2210-2211- STRING | FILTER( REGEX )2212- STRING | FILTER( REGEX; FLAGS )2213- STRING | FILTER( [REGEX] )2214- STRING | FILTER( [REGEX, FLAGS] )2215-2216- where:2217- * STRING, REGEX and FLAGS are jq strings and subject to jq string interpolation;2218- * REGEX, after string interpolation, should be a valid PCRE regex;2219- * FILTER is one of `test`, `match`, or `capture`, as described below.2220-2221- FLAGS is a string consisting of one of more of the supported flags:2222-2223- * `g` - Global search (find all matches, not just the first)2224- * `i` - Case insensitive search2225- * `m` - Multi line mode ('.' will match newlines)2226- * `n` - Ignore empty matches2227- * `p` - Both s and m modes are enabled2228- * `s` - Single line mode ('^' -> '\A', '$' -> '\Z')2229- * `l` - Find longest possible matches2230- * `x` - Extended regex format (ignore whitespace and comments)2231-2232- To match whitespace in an x pattern use an escape such as \s, e.g.2233-2234- * test( "a\\sb", "x" ).2235-2236- Note that certain flags may also be specified within REGEX, e.g.2237-2238- * jq -n '("test", "TEst", "teST", "TEST") | test( "(?i)te(?-i)st" )'2239-2240- evaluates to: true, true, false, false.2241-2242- entries:2243- - title: "`test(val)`, `test(regex; flags)`"2244- body: |2245-2246- Like `match`, but does not return match objects, only `true` or `false`2247- for whether or not the regex matches the input.2248-2249- examples:2250- - program: 'test("foo")'2251- input: '"foo"'2252- output: ['true']2253- - program: '.[] | test("a b c # spaces are ignored"; "ix")'2254- input: '["xabcd", "ABC"]'2255- output: ['true', 'true']2256-2257- - title: "`match(val)`, `match(regex; flags)`"2258- body: |2259-2260- **match** outputs an object for each match it finds. Matches have2261- the following fields:2262-2263- * `offset` - offset in UTF-8 codepoints from the beginning of the input2264- * `length` - length in UTF-8 codepoints of the match2265- * `string` - the string that it matched2266- * `captures` - an array of objects representing capturing groups.2267-2268- Capturing group objects have the following fields:2269-2270- * `offset` - offset in UTF-8 codepoints from the beginning of the input2271- * `length` - length in UTF-8 codepoints of this capturing group2272- * `string` - the string that was captured2273- * `name` - the name of the capturing group (or `null` if it was unnamed)2274-2275- Capturing groups that did not match anything return an offset of -12276-2277- examples:2278- - program: 'match("(abc)+"; "g")'2279- input: '"abc abc"'2280- output:2281- - '{"offset": 0, "length": 3, "string": "abc", "captures": [{"offset": 0, "length": 3, "string": "abc", "name": null}]}'2282- - '{"offset": 4, "length": 3, "string": "abc", "captures": [{"offset": 4, "length": 3, "string": "abc", "name": null}]}'2283- - program: 'match("foo")'2284- input: '"foo bar foo"'2285- output: ['{"offset": 0, "length": 3, "string": "foo", "captures": []}']2286- - program: 'match(["foo", "ig"])'2287- input: '"foo bar FOO"'2288- output:2289- - '{"offset": 0, "length": 3, "string": "foo", "captures": []}'2290- - '{"offset": 8, "length": 3, "string": "FOO", "captures": []}'2291- - program: 'match("foo (?<bar123>bar)? foo"; "ig")'2292- input: '"foo bar foo foo foo"'2293- output:2294- - '{"offset": 0, "length": 11, "string": "foo bar foo", "captures": [{"offset": 4, "length": 3, "string": "bar", "name": "bar123"}]}'2295- - '{"offset": 12, "length": 8, "string": "foo foo", "captures": [{"offset": -1, "length": 0, "string": null, "name": "bar123"}]}'2296-2297- - program: '[ match("."; "g")] | length'2298- input: '"abc"'2299- output: [3]2300-2301-2302- - title: "`capture(val)`, `capture(regex; flags)`"2303- body: |2304-2305- Collects the named captures in a JSON object, with the name2306- of each capture as the key, and the matched string as the2307- corresponding value.2308-2309- examples:2310- - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2311- input: '"xyzzy-14"'2312- output: ['{ "a": "xyzzy", "n": "14" }']2313-2314- - title: "`scan(regex)`, `scan(regex; flags)`"2315- body: |2316-2317- Emit a stream of the non-overlapping substrings of the input2318- that match the regex in accordance with the flags, if any2319- have been specified. If there is no match, the stream is empty.2320- To capture all the matches for each input string, use the idiom2321- `[ expr ]`, e.g. `[ scan(regex) ]`.2322-2323- example:2324- - program: 'scan("c")'2325- input: '"abcdefabc"'2326- output: ['"c"', '"c"']2327-2328- - program: 'scan("b")'2329- input: ("", "")2330- output: ['[]', '[]']2331-2332- - title: "`split(regex; flags)`"2333- body: |2334-2335- For backwards compatibility, `split` splits on a string, not a regex.2336-2337- example:2338- - program: 'split(", *"; null)'2339- input: '"ab,cd, ef"'2340- output: ['"ab","cd","ef"']2341-2342-2343- - title: "`splits(regex)`, `splits(regex; flags)`"2344- body: |2345-2346- These provide the same results as their `split` counterparts,2347- but as a stream instead of an array.2348-2349- example:2350- - program: 'splits(", *")'2351- input: '("ab,cd", "ef, gh")'2352- output: ['"ab"', '"cd"', '"ef"', '"gh"']2353-2354- - title: "`sub(regex; tostring)` `sub(regex; string; flags)`"2355- body: |2356-2357- Emit the string obtained by replacing the first match of regex in the2358- input string with `tostring`, after interpolation. `tostring` should2359- be a jq string, and may contain references to named captures. The2360- named captures are, in effect, presented as a JSON object (as2361- constructed by `capture`) to `tostring`, so a reference to a captured2362- variable named "x" would take the form: "\(.x)".2363-2364- example:2365- - program: 'sub("^[^a-z]*(?<x>[a-z]*).*")'2366- input: '"123abc456"'2367- output: '"ZabcZabc"'2368-2369-2370- - title: "`gsub(regex; string)`, `gsub(regex; string; flags)`"2371- body: |2372-2373- `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2374- replaced by the string, after interpolation.2375-2376- example:2377- - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2378- input: '"Abcabc"'2379- output: '"+A-+a-"'2380-2381-2382- - title: Advanced features2383- body: |2384- Variables are an absolute necessity in most programming languages, but2385- they're relegated to an "advanced feature" in jq.2386-2387- In most languages, variables are the only means of passing around2388- data. If you calculate a value, and you want to use it more than once,2389- you'll need to store it in a variable. To pass a value to another part2390- of the program, you'll need that part of the program to define a2391- variable (as a function parameter, object member, or whatever) in2392- which to place the data.2393-2394- It is also possible to define functions in jq, although this is2395- is a feature whose biggest use is defining jq's standard library2396- (many jq functions such as `map` and `find` are in fact written2397- in jq).2398-2399- jq has reduction operators, which are very powerful but a bit2400- tricky. Again, these are mostly used internally, to define some2401- useful bits of jq's standard library.2402-2403- It may not be obvious at first, but jq is all about generators2404- (yes, as often found in other languages). Some utilities are2405- provided to help deal with generators.2406-2407- Some minimal I/O support (besides reading JSON from standard2408- input, and writing JSON to standard output) is available.2409-2410- Finally, there is a module/library system.2411-2412- entries:2413- - title: "Variable / Symbolic Binding Operator: `... as $identifier | ...`"2414- body: |2415-2416- In jq, all filters have an input and an output, so manual2417- plumbing is not necessary to pass a value from one part of a program2418- to the next. Many expressions, for instance `a + b`, pass their input2419- to two distinct subexpressions (here `a` and `b` are both passed the2420- same input), so variables aren't usually necessary in order to use a2421- value twice.2422-2423- For instance, calculating the average value of an array of numbers2424- requires a few variables in most languages - at least one to hold the2425- array, perhaps one for each element or for a loop counter. In jq, it's2426- simply `add / length` - the `add` expression is given the array and2427- produces its sum, and the `length` expression is given the array and2428- produces its length.2429-2430- So, there's generally a cleaner way to solve most problems in jq than2431- defining variables. Still, sometimes they do make things easier, so jq2432- lets you define variables using `expression as $variable`. All2433- variable names start with `$`. Here's a slightly uglier version of the2434- array-averaging example:2435-2436- length as $array_length | add / $array_length2437-2438- We'll need a more complicated problem to find a situation where using2439- variables actually makes our lives easier.2440-2441-2442- Suppose we have an array of blog posts, with "author" and "title"2443- fields, and another object which is used to map author usernames to2444- real names. Our input looks like:2445-2446- {"posts": [{"title": "Frist psot", "author": "anon"},2447- {"title": "A well-written article", "author": "person1"}],2448- "realnames": {"anon": "Anonymous Coward",2449- "person1": "Person McPherson"}}2450-2451- We want to produce the posts with the author field containing a real2452- name, as in:2453-2454- {"title": "Frist psot", "author": "Anonymous Coward"}2455- {"title": "A well-written article", "author": "Person McPherson"}2456-2457- We use a variable, $names, to store the realnames object, so that we2458- can refer to it later when looking up author usernames:2459-2460- .realnames as $names | .posts[] | {title, author: $names[.author]}2461-2462- The expression `exp as $x | ...` means: for each value of expression2463- `exp`, run the rest of the pipeline with the entire original input, and2464- with `$x` set to that value. Thus `as` functions as something of a2465- foreach loop.2466-2467- Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2468- `{$foo}` is a handy way of writing `{foo:$foo}`.2469-2470- Multiple variables may be declared using a single `as` expression by2471- providing a pattern that matches the structure of the input2472- (this is known as "destructuring"):2473-2474- . as {realnames: $names, posts: [$first, $second]} | ...2475-2476- The variable declarations in array patterns (e.g., `. as2477- [$first, $second]`) bind to the elements of the array in from2478- the element at index zero on up, in order. When there is no2479- value at the index for an array pattern element, `null` is2480- bound to that variable.2481-2482- Variables are scoped over the rest of the expression that defines2483- them, so2484-2485- .realnames as $names | (.posts[] | {title, author: $names[.author]})2486-2487- will work, but2488-2489- (.realnames as $names | .posts[]) | {title, author: $names[.author]}2490-2491- won't.2492-2493- For programming language theorists, it's more accurate to2494- say that jq variables are lexically-scoped bindings. In2495- particular there's no way to change the value of a binding;2496- one can only setup a new binding with the same name, but which2497- will not be visible where the old one was.2498-2499- examples:2500- - program: '.bar as $x | .foo | . + $x'2501- input: '{"foo":10, "bar":200}'2502- output: ['210']2503- - program: '. as $i|[(.*2|. as $i| $i), $i]'2504- input: '5'2505- output: ['[10,5]']2506- - program: '. as [$a, $b, {c: $c}] | $a + $b + $c'2507- input: '[2, 3, {"c": 4, "d": 5}]'2508- output: ['9']2509- - program: '.[] as [$a, $b] | {a: $a, b: $b}'2510- input: '[[0], [0, 1], [2, 1, 0]]'2511- output: ['{"a":0,"b":null}', '{"a":0,"b":1}', '{"a":2,"b":1}']2512-2513- - title: 'Destructuring Alternative Operator: `?//`'2514- body: |2515- 2516- The destructuring alternative operator provides a concise mechanism2517- for destructuring an input that can take one of several forms.2518-2519- Suppose we have an API that returns a list of resources and events2520- associated with them, and we want to get the user_id and timestamp of2521- the first event for each resource. The API (having been clumsily2522- converted from XML) will only wrap the events in an array if the resource2523- has multiple events:2524- 2525- {"resources": [{"id": 1, "kind": "widget", "events": {"action": "create", "user_id": 1, "ts": 13}},2526- {"id": 2, "kind": "widget", "events": [{"action": "create", "user_id": 1, "ts": 14}, {"action": "destroy", "user_id": 1, "ts": 15}]}]}2527- 2528- We can use the destructuring alternative operator to handle this structural change simply:2529-2530- .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$user_id, $ts}]} | {$user_id, $kind, $id, $ts}2531-2532- Or, if we aren't sure if the input is an array of values or an object:2533-2534- .[] as [$id, $kind, $user_id, $ts] ?// {$id, $kind, $user_id, $ts} | ...2535-2536- Each alternative need not define all of the same variables, but all named2537- variables will be available to the subsequent expression. Variables not2538- matched in the alternative that succeeded will be `null`:2539-2540- .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$first_user_id, $first_ts}]} | {$user_id, $first_user_id, $kind, $id, $ts, $first_ts}2541-2542- Additionally, if the subsequent expression returns an error, the2543- alternative operator will attempt to try the next binding. Errors2544- that occur during the final alternative are passed through.2545-2546- [[3]] | .[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end2547-2548- examples:2549- - program: '.[] as {$a, $b, c: {$d, $e}} ?// {$a, $b, c: [{$d, $e}]} | {$a, $b, $d, $e}'2550- input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2551- output: ['{"a":1,"b":2,"d":3,"e":4}', '{"a":1,"b":2,"d":3,"e":4}']2552- - program: '.[] as {$a, $b, c: {$d}} ?// {$a, $b, c: [{$e}]} | {$a, $b, $d, $e}'2553- input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2554- output: ['{"a":1,"b":2,"d":3,"e":null}', '{"a":1,"b":2,"d":null,"e":4}']2555- - program: '.[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end'2556- input: '[[3]]'2557- output: ['{"a":null,"b":3}']2558-2559- - title: 'Defining Functions'2560- body: |2561-2562- You can give a filter a name using "def" syntax:2563-2564- def increment: . + 1;2565-2566- From then on, `increment` is usable as a filter just like a2567- builtin function (in fact, this is how many of the builtins2568- are defined). A function may take arguments:2569-2570- def map(f): [.[] | f];2571-2572- Arguments are passed as _filters_ (functions with no2573- arguments), _not_ as values. The same argument may be2574- referenced multiple times with different inputs (here `f` is2575- run for each element of the input array). Arguments to a2576- function work more like callbacks than like value arguments.2577- This is important to understand. Consider:2578-2579- def foo(f): f|f;2580- 5|foo(.*2)2581-2582- The result will be 20 because `f` is `.*2`, and during the2583- first invocation of `f` `.` will be 5, and the second time it2584- will be 10 (5 * 2), so the result will be 20. Function2585- arguments are filters, and filters expect an input when2586- invoked.2587-2588- If you want the value-argument behaviour for defining simple2589- functions, you can just use a variable:2590-2591- def addvalue(f): f as $f | map(. + $f);2592-2593- Or use the short-hand:2594-2595- def addvalue($f): ...;2596-2597- With either definition, `addvalue(.foo)` will add the current2598- input's `.foo` field to each element of the array. Do note2599- that calling `addvalue(.[])` will cause the `map(. + $f)` part2600- to be evaluated once per value in the value of `.` at the call2601- site.2602-2603- Multiple definitions using the same function name are allowed.2604- Each re-definition replaces the previous one for the same2605- number of function arguments, but only for references from2606- functions (or main program) subsequent to the re-definition.2607- See also the section below on scoping.2608-2609- examples:2610- - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'2611- input: '[[1,2],[10,20]]'2612- output: ['[[1,2,1], [10,20,10]]']2613- - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'2614- input: '[[1,2],[10,20]]'2615- output: ['[[1,2,1,2], [10,20,1,2]]']2616-2617- - title: 'Scoping'2618- body: |2619-2620- There are two types of symbols in jq: value bindings (a.k.a.,2621- "variables"), and functions. Both are scoped lexically,2622- with expressions being able to refer only to symbols that2623- have been defined "to the left" of them. The only exception2624- to this rule is that functions can refer to themselves so as2625- to be able to create recursive functions.2626-2627- For example, in the following expression there is a binding2628- which is visible "to the right" of it, `... | .*3 as2629- $times_three | [. + $times_three] | ...`, but not "to the2630- left". Consider this expression now, `... | (.*3 as2631- $times_three | [.+ $times_three]) | ...`: here the binding2632- `$times_three` is _not_ visible past the closing parenthesis.2633-2634- - title: Reduce2635- body: |2636-2637- The `reduce` syntax in jq allows you to combine all of the2638- results of an expression by accumulating them into a single2639- answer. As an example, we'll pass `[3,2,1]` to this expression:2640-2641- reduce .[] as $item (0; . + $item)2642-2643- For each result that `.[]` produces, `. + $item` is run to2644- accumulate a running total, starting from 0. In this2645- example, `.[]` produces the results 3, 2, and 1, so the2646- effect is similar to running something like this:2647-2648- 0 | (3 as $item | . + $item) |2649- (2 as $item | . + $item) |2650- (1 as $item | . + $item)2651-2652- examples:2653- - program: 'reduce .[] as $item (0; . + $item)'2654- input: '[10,2,5,3]'2655- output: ['20']2656-2657- - title: "`isempty(exp)`"2658- body: |2659-2660- Returns true if `exp` produces no outputs, false otherwise.2661-2662- examples:2663- - program: 'isempty(empty)'2664- input: 'null'2665- output: ['true']2666-2667- - title: "`limit(n; exp)`"2668- body: |2669-2670- The `limit` function extracts up to `n` outputs from `exp`.2671-2672- examples:2673- - program: '[limit(3;.[])]'2674- input: '[0,1,2,3,4,5,6,7,8,9]'2675- output: ['[0,1,2]']2676-2677- - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"2678- body: |2679-2680- The `first(expr)` and `last(expr)` functions extract the first2681- and last values from `expr`, respectively.2682-2683- The `nth(n; expr)` function extracts the nth value output by2684- `expr`. This can be defined as `def nth(n; expr):2685- last(limit(n + 1; expr));`. Note that `nth(n; expr)` doesn't2686- support negative values of `n`.2687-2688- examples:2689- - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'2690- input: '10'2691- output: ['[0,9,5]']2692-2693- - title: "`first`, `last`, `nth(n)`"2694- body: |2695-2696- The `first` and `last` functions extract the first2697- and last values from any array at `.`.2698-2699- The `nth(n)` function extracts the nth value of any array at `.`.2700-2701- examples:2702- - program: '[range(.)]|[first, last, nth(5)]'2703- input: '10'2704- output: ['[0,9,5]']2705-2706- - title: "`foreach`"2707- body: |2708-2709- The `foreach` syntax is similar to `reduce`, but intended to2710- allow the construction of `limit` and reducers that produce2711- intermediate results (see example).2712-2713- The form is `foreach EXP as $var (INIT; UPDATE; EXTRACT)`.2714- Like `reduce`, `INIT` is evaluated once to produce a state2715- value, then each output of `EXP` is bound to `$var`, `UPDATE`2716- is evaluated for each output of `EXP` with the current state2717- and with `$var` visible. Each value output by `UPDATE`2718- replaces the previous state. Finally, `EXTRACT` is evaluated2719- for each new state to extract an output of `foreach`.2720-2721- This is mostly useful only for constructing `reduce`- and2722- `limit`-like functions. But it is much more general, as it2723- allows for partial reductions (see the example below).2724-2725- examples:2726- - program: '[foreach .[] as $item2727- ([[],[]];2728- if $item == null then [[],.[0]] else [(.[0] + [$item]),[]] end;2729- if $item == null then .[1] else empty end)]'2730- input: '[1,2,3,4,null,"a","b",null]'2731- output: ['[[1,2,3,4],["a","b"]]']2732-2733- - title: Recursion2734- body: |2735-2736- As described above, `recurse` uses recursion, and any jq2737- function can be recursive. The `while` builtin is also2738- implemented in terms of recursion.2739-2740- Tail calls are optimized whenever the expression to the left of2741- the recursive call outputs its last value. In practice this2742- means that the expression to the left of the recursive call2743- should not produce more than one output for each input.2744-2745- For example:2746-2747- def recurse(f): def r: ., (f | select(. != null) | r); r;2748-2749- def while(cond; update):2750- def _while:2751- if cond then ., (update | _while) else empty end;2752- _while;2753-2754- def repeat(exp):2755- def _repeat:2756- exp, _repeat;2757- _repeat;2758-2759- - title: Generators and iterators2760- body: |2761-2762- Some jq operators and functions are actually generators in2763- that they can produce zero, one, or more values for each2764- input, just as one might expect in other programming2765- languages that have generators. For example, `.[]`2766- generates all the values in its input (which must be an2767- array or an object), `range(0; 10)` generates the integers2768- between 0 and 10, and so on.2769-2770- Even the comma operator is a generator, generating first the2771- values generated by the expression to the left of the comma,2772- then for each of those, the values generate by the2773- expression on the right of the comma.2774-2775- The `empty` builtin is the generator that produces zero2776- outputs. The `empty` builtin backtracks to the preceding2777- generator expression.2778-2779- All jq functions can be generators just by using builtin2780- generators. It is also possible to define new generators2781- using only recursion and the comma operator. If the2782- recursive call(s) is(are) "in tail position" then the2783- generator will be efficient. In the example below the2784- recursive call by `_range` to itself is in tail position.2785- The example shows off three advanced topics: tail recursion,2786- generator construction, and sub-functions.2787-2788- examples:2789- - program: 'def range(init; upto; by):2790- def _range:2791- if (by > 0 and . < upto) or (by < 0 and . > upto)2792- then ., ((.+by)|_range)2793- else . end;2794- if by == 0 then init else init|_range end |2795- select((by > 0 and . < upto) or (by < 0 and . > upto));2796- range(0; 10; 3)'2797- input: 'null'2798- output: ['0', '3', '6', '9']2799- - program: 'def while(cond; update):2800- def _while:2801- if cond then ., (update | _while) else empty end;2802- _while;2803- [while(.<100; .*2)]'2804- input: '1'2805- output: ['[1,2,4,8,16,32,64]']2806-2807- - title: 'Math'2808- body: |2809-2810- jq currently only has IEEE754 double-precision (64-bit) floating2811- point number support.2812-2813- Besides simple arithmetic operators such as `+`, jq also has most2814- standard math functions from the C math library. C math functions2815- that take a single input argument (e.g., `sin()`) are available as2816- zero-argument jq functions. C math functions that take two input2817- arguments (e.g., `pow()`) are available as two-argument jq2818- functions that ignore `.`. C math functions that take three input2819- arguments are available as three-argument jq functions that ignore2820- `.`.2821-2822- Availability of standard math functions depends on the2823- availability of the corresponding math functions in your operating2824- system and C math library. Unavailable math functions will be2825- defined but will raise an error.2826-2827- One-input C math functions: `acos` `acosh` `asin` `asinh` `atan`2828- `atanh` `cbrt` `ceil` `cos` `cosh` `erf` `erfc` `exp` `exp10`2829- `exp2` `expm1` `fabs` `floor` `gamma` `j0` `j1` `lgamma` `log`2830- `log10` `log1p` `log2` `logb` `nearbyint` `pow10` `rint` `round`2831- `significand` `sin` `sinh` `sqrt` `tan` `tanh` `tgamma` `trunc`2832- `y0` `y1`.2833-2834- Two-input C math functions: `atan2` `copysign` `drem` `fdim`2835- `fmax` `fmin` `fmod` `frexp` `hypot` `jn` `ldexp` `modf`2836- `nextafter` `nexttoward` `pow` `remainder` `scalb` `scalbln` `yn`.2837-2838- Three-input C math functions: `fma`.2839-2840- See your system's manual for more information on each of these.2841-2842- - title: 'I/O'2843- body: |2844-2845- At this time jq has minimal support for I/O, mostly in the2846- form of control over when inputs are read. Two builtins functions2847- are provided for this, `input` and `inputs`, that read from the2848- same sources (e.g., `stdin`, files named on the command-line) as2849- jq itself. These two builtins, and jq's own reading actions, can2850- be interleaved with each other.2851-2852- Two builtins provide minimal output capabilities, `debug`, and2853- `stderr`. (Recall that a jq program's output values are always2854- output as JSON texts on `stdout`.) The `debug` builtin can have2855- application-specific behavior, such as for executables that use2856- the libjq C API but aren't the jq executable itself. The `stderr`2857- builtin outputs its input in raw mode to stder with no additional2858- decoration, not even a newline.2859-2860- Most jq builtins are referentially transparent, and yield constant2861- and repeatable value streams when applied to constant inputs.2862- This is not true of I/O builtins.2863-2864- entries:2865- - title: "`input`"2866- body: |2867-2868- Outputs one new input.2869-2870- - title: "`inputs`"2871- body: |2872-2873- Outputs all remaining inputs, one by one.2874-2875- This is primarily useful for reductions over a program's2876- inputs.2877-2878- - title: "`debug`"2879- body: |2880-2881- Causes a debug message based on the input value to be2882- produced. The jq executable wraps the input value with2883- `["DEBUG:", <input-value>]` and prints that and a newline on2884- stderr, compactly. This may change in the future.2885-2886- - title: "`stderr`"2887- body: |2888-2889- Prints its input in raw and compact mode to stderr with no2890- additional decoration, not even a newline.2891-2892- - title: "`input_filename`"2893- body: |2894-2895- Returns the name of the file whose input is currently being2896- filtered. Note that this will not work well unless jq is2897- running in a UTF-8 locale.2898-2899- - title: "`input_line_number`"2900- body: |2901-2902- Returns the line number of the input currently being filtered.2903-2904- - title: 'Streaming'2905- body: |2906-2907- With the `--stream` option jq can parse input texts in a streaming2908- fashion, allowing jq programs to start processing large JSON texts2909- immediately rather than after the parse completes. If you have a2910- single JSON text that is 1GB in size, streaming it will allow you2911- to process it much more quickly.2912-2913- However, streaming isn't easy to deal with as the jq program will2914- have `[<path>, <leaf-value>]` (and a few other forms) as inputs.2915-2916- Several builtins are provided to make handling streams easier.2917-2918- The examples below use the streamed form of `[0,[1]]`, which is2919- `[[0],0],[[1,0],1],[[1,0]],[[1]]`.2920-2921- Streaming forms include `[<path>, <leaf-value>]` (to indicate any2922- scalar value, empty array, or empty object), and `[<path>]` (to2923- indicate the end of an array or object). Future versions of jq2924- run with `--stream` and `-seq` may output additional forms such as2925- `["error message"]` when an input text fails to parse.2926-2927- entries:2928- - title: "`truncate_stream(stream_expression)`"2929- body: |2930-2931- Consumes a number as input and truncates the corresponding2932- number of path elements from the left of the outputs of the2933- given streaming expression.2934-2935- examples:2936- - program: '[1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]'2937- input: '1'2938- output: ['[[[0],2],[[0]]]']2939-2940- - title: "`fromstream(stream_expression)`"2941- body: |2942-2943- Outputs values corresponding to the stream expression's2944- outputs.2945-2946- examples:2947- - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'2948- input: 'null'2949- output: ['[2]']2950-2951- - title: "`tostream`"2952- body: |2953-2954- The `tostream` builtin outputs the streamed form of its input.2955-2956- examples:2957- - program: '. as $dot|fromstream($dot|tostream)|.==$dot'2958- input: '[0,[1,{"a":1},{"b":2}]]'2959- output: ['true']2960-2961- - title: Assignment2962- body: |2963- Assignment works a little differently in jq than in most2964- programming languages. jq doesn't distinguish between references2965- to and copies of something - two objects or arrays are either2966- equal or not equal, without any further notion of being "the2967- same object" or "not the same object".2968-2969- If an object has two fields which are arrays, `.foo` and `.bar`,2970- and you append something to `.foo`, then `.bar` will not get2971- bigger, even if you've previously set `.bar = .foo`. If you're2972- used to programming in languages like Python, Java, Ruby,2973- Javascript, etc. then you can think of it as though jq does a full2974- deep copy of every object before it does the assignment (for2975- performance it doesn't actually do that, but that's the general2976- idea).2977-2978- This means that it's impossible to build circular values in jq2979- (such as an array whose first element is itself). This is quite2980- intentional, and ensures that anything a jq program can produce2981- can be represented in JSON.2982-2983- All the assignment operators in jq have path expressions on the2984- left-hand side (LHS). The right-hand side (RHS) provides values2985- to set to the paths named by the LHS path expressions.2986-2987- Values in jq are always immutable. Internally, assignment works2988- by using a reduction to compute new, replacement values for `.` that2989- have had all the desired assignments applied to `.`, then2990- outputting the modified value. This might be made clear by this2991- example: `{a:{b:{c:1}}} | (.a.b|=3), .`. This will output2992- `{"a":{"b":3}}` and `{"a":{"b":{"c":1}}}` because the last2993- sub-expression, `.`, sees the original value, not the modified2994- value.2995-2996- Most users will want to use modification assignment operators,2997- such as `|=` or `+=`, rather than `=`.2998-2999- Note that the LHS of assignment operators refers to a value in3000- `.`. Thus `$var.foo = 1` won't work as expected (`$var.foo` is3001- not a valid or useful path expression in `.`); use `$var | .foo =3002- 1` instead.3003-3004- Note too that `.a,.b=0` does not set `.a` and `.b`, but3005- `(.a,.b)=0` sets both.3006-3007- entries:3008- - title: "Update-assignment: `|=`"3009- body: |3010- This is the "update" operator '|='. It takes a filter on the3011- right-hand side and works out the new value for the property3012- of `.` being assigned to by running the old value through this3013- expression. For instance, (.foo, .bar) |= .+1 will build an3014- object with the "foo" field set to the input's "foo" plus 1,3015- and the "bar" field set to the input's "bar" plus 1.3016-3017- The left-hand side can be any general path expression; see `path()`.3018-3019- Note that the left-hand side of '|=' refers to a value in `.`.3020- Thus `$var.foo |= . + 1` won't work as expected (`$var.foo` is3021- not a valid or useful path expression in `.`); use `$var |3022- .foo |= . + 1` instead.3023-3024- If the right-hand side outputs no values (i.e., `empty`), then3025- the left-hand side path will be deleted, as with `del(path)`.3026-3027- If the right-hand side outputs multiple values, only the first3028- one will be used (COMPATIBILITY NOTE: in jq 1.5 and earlier3029- releases, it used to be that only the last one was used).3030-3031- examples:3032- - program: '(..|select(type=="boolean")) |= if . then 1 else 0 end'3033- input: '[true,false,[5,true,[true,[false]],false]]'3034- output: ['[1,0,[5,1,[1,[0]],0]]']3035-3036- - title: "Arithmetic update-assignment: `+=`, `-=`, `*=`, `/=`, `%=`, `//=`"3037- body: |3038-3039- jq has a few operators of the form `a op= b`, which are all3040- equivalent to `a |= . op b`. So, `+= 1` can be used to3041- increment values, being the same as `|= . + 1`.3042-3043- examples:3044- - program: .foo += 13045- input: '{"foo": 42}'3046- output: ['{"foo": 43}']3047-3048- - title: "Plain assignment: `=`"3049- body: |3050-3051- This is the plain assignment operator. Unlike the others, the3052- input to the right-hand-side (RHS) is the same as the input to3053- the left-hand-side (LHS) rather than the value at the LHS3054- path, and all values output by the RHS will be used (as shown3055- below).3056-3057- If the RHS of '=' produces multiple values, then for each such3058- value jq will set the paths on the left-hand side to the value3059- and then it will output the modified `.`. For example,3060- `(.a,.b)=range(2)` outputs `{"a":0,"b":0}`, then3061- `{"a":1,"b":1}`. The "update" assignment forms (see above) do3062- not do this.3063-3064- This example should show the difference between '=' and '|=':3065-3066- Provide input '{"a": {"b": 10}, "b": 20}' to the programs:3067-3068- .a = .b3069-3070- .a |= .b3071-3072- The former will set the "a" field of the input to the "b"3073- field of the input, and produce the output {"a": 20, "b": 20}.3074- The latter will set the "a" field of the input to the "a"3075- field's "b" field, producing {"a": 10, "b": 20}.3076-3077- Another example of the difference between '=' and '|=':3078-3079- null|(.a,.b)=range(3)3080-3081- outputs '{"a":0,"b":0}', '{"a":1,"b":1}', and '{"a":2,"b":2}',3082- while3083-3084- null|(.a,.b)|=range(3)3085-3086- outputs just '{"a":0,"b":0}'.3087-3088- - title: Complex assignments3089- body: |3090- Lots more things are allowed on the left-hand side of a jq assignment3091- than in most languages. We've already seen simple field accesses on3092- the left hand side, and it's no surprise that array accesses work just3093- as well:3094-3095- .posts[0].title = "JQ Manual"3096-3097- What may come as a surprise is that the expression on the left may3098- produce multiple results, referring to different points in the input3099- document:3100-3101- .posts[].comments |= . + ["this is great"]3102-3103- That example appends the string "this is great" to the "comments"3104- array of each post in the input (where the input is an object with a3105- field "posts" which is an array of posts).3106-3107- When jq encounters an assignment like 'a = b', it records the "path"3108- taken to select a part of the input document while executing a. This3109- path is then used to find which part of the input to change while3110- executing the assignment. Any filter may be used on the3111- left-hand side of an equals - whichever paths it selects from the3112- input will be where the assignment is performed.3113-3114- This is a very powerful operation. Suppose we wanted to add a comment3115- to blog posts, using the same "blog" input above. This time, we only3116- want to comment on the posts written by "stedolan". We can find those3117- posts using the "select" function described earlier:3118-3119- .posts[] | select(.author == "stedolan")3120-3121- The paths provided by this operation point to each of the posts that3122- "stedolan" wrote, and we can comment on each of them in the same way3123- that we did before:3124-3125- (.posts[] | select(.author == "stedolan") | .comments) |=3126- . + ["terrible."]3127-3128- - title: Modules3129- body: |3130-3131- jq has a library/module system. Modules are files whose names end3132- in `.jq`.3133-3134- Modules imported by a program are searched for in a default search3135- path (see below). The `import` and `include` directives allow the3136- importer to alter this path.3137-3138- Paths in the a search path are subject to various substitutions.3139-3140- For paths starting with "~/", the user's home directory is3141- substituted for "~".3142-3143- For paths starting with "$ORIGIN/", the path of the jq executable3144- is substituted for "$ORIGIN".3145-3146- For paths starting with "./" or paths that are ".", the path of3147- the including file is substituted for ".". For top-level programs3148- given on the command-line, the current directory is used.3149-3150- Import directives can optionally specify a search path to which3151- the default is appended.3152-3153- The default search path is the search path given to the `-L`3154- command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",3155- "$ORIGIN/../lib"]`.3156-3157- Null and empty string path elements terminate search path3158- processing.3159-3160- A dependency with relative path "foo/bar" would be searched for in3161- "foo/bar.jq" and "foo/bar/bar.jq" in the given search path. This3162- is intended to allow modules to be placed in a directory along3163- with, for example, version control files, README files, and so on,3164- but also to allow for single-file modules.3165-3166- Consecutive components with the same name are not allowed to avoid3167- ambiguities (e.g., "foo/foo").3168-3169- For example, with `-L$HOME/.jq` a module `foo` can be found in3170- `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.3171-3172- If "$HOME/.jq" is a file, it is sourced into the main program.3173-3174- entries:3175- - title: "`import RelativePathString as NAME [<metadata>];`"3176- body: |3177-3178- Imports a module found at the given path relative to a3179- directory in a search path. A ".jq" suffix will be added to3180- the relative path string. The module's symbols are prefixed3181- with "NAME::".3182-3183- The optional metadata must be a constant jq expression. It3184- should be an object with keys like "homepage" and so on. At3185- this time jq only uses the "search" key/value of the metadata.3186- The metadata is also made available to users via the3187- `modulemeta` builtin.3188-3189- The "search" key in the metadata, if present, should have a3190- string or array value (array of strings); this is the search3191- path to be prefixed to the top-level search path.3192-3193- - title: "`include RelativePathString [<metadata>];`"3194- body: |3195-3196- Imports a module found at the given path relative to a3197- directory in a search path as if it were included in place. A3198- ".jq" suffix will be added to the relative path string. The3199- module's symbols are imported into the caller's namespace as3200- if the module's content had been included directly.3201-3202- The optional metadata must be a constant jq expression. It3203- should be an object with keys like "homepage" and so on. At3204- this time jq only uses the "search" key/value of the metadata.3205- The metadata is also made available to users via the3206- `modulemeta` builtin.3207-3208- - title: "`import RelativePathString as $NAME [<metadata>];`"3209- body: |3210-3211- Imports a JSON file found at the given path relative to a3212- directory in a search path. A ".json" suffix will be added to3213- the relative path string. The file's data will be available3214- as `$NAME::NAME`.3215-3216- The optional metadata must be a constant jq expression. It3217- should be an object with keys like "homepage" and so on. At3218- this time jq only uses the "search" key/value of the metadata.3219- The metadata is also made available to users via the3220- `modulemeta` builtin.3221-3222- The "search" key in the metadata, if present, should have a3223- string or array value (array of strings); this is the search3224- path to be prefixed to the top-level search path.3225-3226- - title: "`module <metadata>;`"3227- body: |3228-3229- This directive is entirely optional. It's not required for3230- proper operation. It serves only the purpose of providing3231- metadata that can be read with the `modulemeta` builtin.3232-3233- The metadata must be a constant jq expression. It should be3234- an object with keys like "homepage". At this time jq doesn't3235- use this metadata, but it is made available to users via the3236- `modulemeta` builtin.3237-3238- - title: "`modulemeta`"3239- body: |3240-3241- Takes a module name as input and outputs the module's metadata3242- as an object, with the module's imports (including metadata)3243- as an array value for the "deps" key.3244-3245- Programs can use this to query a module's metadata, which they3246- could then use to, for example, search for, download, and3247- install missing dependencies.3248-3249- - title: Colors3250- body: |3251-3252- To configure alternative colors just set the `JQ_COLORS`3253- environment variable to colon-delimited list of partial terminal3254- escape sequences like `"1;31"`, in this order:3255-3256- - color for `null`3257- - color for `false`3258- - color for `true`3259- - color for numbers3260- - color for strings3261- - color for arrays3262- - color for objects3263-3264- The default color scheme is the same as setting3265- `"JQ_COLORS=1;30:0;39:0;39:0;39:0;32:1;39:1;39"`.3266-3267- This is not a manual for VT100/ANSI escapes. However, each of3268- these color specifications should consist of two numbers separated3269- by a semi-colon, where the first number is one of these:3270-3271- - 1 (bright)3272- - 2 (dim)3273- - 4 (underscore)3274- - 5 (blink)3275- - 7 (reverse)3276- - 8 (hidden)3277-3278- and the second is one of these:3279-3280- - 30 (black)3281- - 31 (red)3282- - 32 (green)3283- - 33 (yellow)3284- - 34 (blue)3285- - 35 (magenta)3286- - 36 (cyan)3287- - 37 (white)deleted:docs/content/3.manual/manual.yml-3303 removed
1----2-headline: jq Manual (development version)3-4-history: |5-6- *For released versions, see [jq 1.6](/jq/manual/v1.6),7- [jq 1.5](/jq/manual/v1.5), [jq 1.4](/jq/manual/v1.4)8- or [jq 1.3](/jq/manual/v1.3).*9-10-body: |11-12- A jq program is a "filter": it takes an input, and produces an13- output. There are a lot of builtin filters for extracting a14- particular field of an object, or converting a number to a string,15- or various other standard tasks.16-17- Filters can be combined in various ways - you can pipe the output of18- one filter into another filter, or collect the output of a filter19- into an array.20-21- Some filters produce multiple results, for instance there's one that22- produces all the elements of its input array. Piping that filter23- into a second runs the second filter for each element of the24- array. Generally, things that would be done with loops and iteration25- in other languages are just done by gluing filters together in jq.26-27- It's important to remember that every filter has an input and an28- output. Even literals like "hello" or 42 are filters - they take an29- input but always produce the same literal as output. Operations that30- combine two filters, like addition, generally feed the same input to31- both and combine the results. So, you can implement an averaging32- filter as `add / length` - feeding the input array both to the `add`33- filter and the `length` filter and then performing the division.34-35- But that's getting ahead of ourselves. :) Let's start with something36- simpler:37-38-manpage_intro: |39- jq(1) -- Command-line JSON processor40- ====================================41-42- ## SYNOPSIS43-44- `jq` [<options>...] <filter> [<files>...]45-46- `jq` can transform JSON in various ways, by selecting, iterating,47- reducing and otherwise mangling JSON documents. For instance,48- running the command `jq 'map(.price) | add'` will take an array of49- JSON objects as input and return the sum of their "price" fields.50-51- `jq` can accept text input as well, but by default, `jq` reads a52- stream of JSON entities (including numbers and other literals) from53- `stdin`. Whitespace is only needed to separate entities such as 154- and 2, and true and false. One or more <files> may be specified, in55- which case `jq` will read input from those instead.56-57- The <options> are described in the [INVOKING JQ] section; they58- mostly concern input and output formatting. The <filter> is written59- in the jq language and specifies how to transform the input60- file or document.61-62- ## FILTERS63-64-manpage_epilogue: |65- ## BUGS66-67- Presumably. Report them or discuss them at:68-69- https://github.com/stedolan/jq/issues70-71- ## AUTHOR72-73- Stephen Dolan `<mu@netsoc.tcd.ie>`74-75-sections:76- - title: Invoking jq77- body: |78-79- jq filters run on a stream of JSON data. The input to jq is80- parsed as a sequence of whitespace-separated JSON values which81- are passed through the provided filter one at a time. The82- output(s) of the filter are written to standard out, again as a83- sequence of whitespace-separated JSON data.84-85- Note: it is important to mind the shell's quoting rules. As a86- general rule it's best to always quote (with single-quote87- characters) the jq program, as too many characters with special88- meaning to jq are also shell meta-characters. For example, `jq89- "foo"` will fail on most Unix shells because that will be the same90- as `jq foo`, which will generally fail because `foo is not91- defined`. When using the Windows command shell (cmd.exe) it's92- best to use double quotes around your jq program when given on the93- command-line (instead of the `-f program-file` option), but then94- double-quotes in the jq program need backslash escaping.95-96- You can affect how jq reads and writes its input and output97- using some command-line options:98-99- * `--version`:100-101- Output the jq version and exit with zero.102-103- * `--seq`:104-105- Use the `application/json-seq` MIME type scheme for separating106- JSON texts in jq's input and output. This means that an ASCII107- RS (record separator) character is printed before each value on108- output and an ASCII LF (line feed) is printed after every109- output. Input JSON texts that fail to parse are ignored (but110- warned about), discarding all subsequent input until the next111- RS. This mode also parses the output of jq without the `--seq`112- option.113-114- * `--stream`:115-116- Parse the input in streaming fashion, outputing arrays of path117- and leaf values (scalars and empty arrays or empty objects).118- For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]`119- becomes `[[0],[]]`, `[[1],"a"]`, and `[[1,0],"b"]`.120-121- This is useful for processing very large inputs. Use this in122- conjunction with filtering and the `reduce` and `foreach` syntax123- to reduce large inputs incrementally.124-125- * `--slurp`/`-s`:126-127- Instead of running the filter for each JSON object in the128- input, read the entire input stream into a large array and run129- the filter just once.130-131- * `--raw-input`/`-R`:132-133- Don't parse the input as JSON. Instead, each line of text is134- passed to the filter as a string. If combined with `--slurp`,135- then the entire input is passed to the filter as a single long136- string.137-138- * `--null-input`/`-n`:139-140- Don't read any input at all! Instead, the filter is run once141- using `null` as the input. This is useful when using jq as a142- simple calculator or to construct JSON data from scratch.143-144- * `--compact-output` / `-c`:145-146- By default, jq pretty-prints JSON output. Using this option147- will result in more compact output by instead putting each148- JSON object on a single line.149-150- * `--tab`:151-152- Use a tab for each indentation level instead of two spaces.153-154- * `--indent n`:155-156- Use the given number of spaces (no more than 8) for indentation.157-158- * `--color-output` / `-C` and `--monochrome-output` / `-M`:159-160- By default, jq outputs colored JSON if writing to a161- terminal. You can force it to produce color even if writing to162- a pipe or a file using `-C`, and disable color with `-M`.163-164- Colors can be configured with the `JQ_COLORS` environment165- variable (see below).166-167- * `--ascii-output` / `-a`:168-169- jq usually outputs non-ASCII Unicode codepoints as UTF-8, even170- if the input specified them as escape sequences (like171- "\u03bc"). Using this option, you can force jq to produce pure172- ASCII output with every non-ASCII character replaced with the173- equivalent escape sequence.174-175- * `--unbuffered`176-177- Flush the output after each JSON object is printed (useful if178- you're piping a slow data source into jq and piping jq's179- output elsewhere).180-181- * `--sort-keys` / `-S`:182-183- Output the fields of each object with the keys in sorted order.184-185- * `--raw-output` / `-r`:186-187- With this option, if the filter's result is a string then it188- will be written directly to standard output rather than being189- formatted as a JSON string with quotes. This can be useful for190- making jq filters talk to non-JSON-based systems.191-192- * `--join-output` / `-j`:193-194- Like `-r` but jq won't print a newline after each output.195-196- * `-f filename` / `--from-file filename`:197-198- Read filter from the file rather than from a command line, like199- awk's -f option. You can also use '#' to make comments.200-201- * `-Ldirectory` / `-L directory`:202-203- Prepend `directory` to the search list for modules. If this204- option is used then no builtin search list is used. See the205- section on modules below.206-207- * `-e` / `--exit-status`:208-209- Sets the exit status of jq to 0 if the last output values was210- neither `false` nor `null`, 1 if the last output value was211- either `false` or `null`, or 4 if no valid result was ever212- produced. Normally jq exits with 2 if there was any usage213- problem or system error, 3 if there was a jq program compile214- error, or 0 if the jq program ran.215-216- Another way to set the exit status is with the `halt_error`217- builtin function.218-219- * `--arg name value`:220-221- This option passes a value to the jq program as a predefined222- variable. If you run jq with `--arg foo bar`, then `$foo` is223- available in the program and has the value `"bar"`. Note that224- `value` will be treated as a string, so `--arg foo 123` will225- bind `$foo` to `"123"`.226-227- Named arguments are also available to the jq program as228- `$ARGS.named`.229-230- * `--argjson name JSON-text`:231-232- This option passes a JSON-encoded value to the jq program as a233- predefined variable. If you run jq with `--argjson foo 123`, then234- `$foo` is available in the program and has the value `123`.235-236- * `--slurpfile variable-name filename`:237-238- This option reads all the JSON texts in the named file and binds239- an array of the parsed JSON values to the given global variable.240- If you run jq with `--slurpfile foo bar`, then `$foo` is available241- in the program and has an array whose elements correspond to the242- texts in the file named `bar`.243-244- * `--rawfile variable-name filename`:245-246- This option reads in the named file and binds its contents to the given247- global variable. If you run jq with `--rawfile foo bar`, then `$foo` is248- available in the program and has a string whose contents are to the texs249- in the file named `bar`.250-251- * `--argfile variable-name filename`:252-253- Do not use. Use `--slurpfile` instead.254-255- (This option is like `--slurpfile`, but when the file has just256- one text, then that is used, else an array of texts is used as257- in `--slurpfile`.)258-259- * `--args`:260-261- Remaining arguments are positional string arguments. These are262- available to the jq program as `$ARGS.positional[]`.263-264- * `--jsonargs`:265-266- Remaining arguments are positional JSON text arguments. These267- are available to the jq program as `$ARGS.positional[]`.268-269- * `--run-tests [filename]`:270-271- Runs the tests in the given file or standard input. This must272- be the last option given and does not honor all preceding273- options. The input consists of comment lines, empty lines, and274- program lines followed by one input line, as many lines of275- output as are expected (one per output), and a terminating empty276- line. Compilation failure tests start with a line containing277- only "%%FAIL", then a line containing the program to compile,278- then a line containing an error message to compare to the279- actual.280-281- Be warned that this option can change backwards-incompatibly.282-283- - title: Basic filters284- entries:285- - title: "Identity: `.`"286- body: |287-288- The absolute simplest filter is `.` . This is a filter that289- takes its input and produces it unchanged as output. That is,290- this is the identity operator.291-292- Since jq by default pretty-prints all output, this trivial293- program can be a useful way of formatting JSON output from,294- say, `curl`.295-296- examples:297- - program: '.'298- input: '"Hello, world!"'299- output: ['"Hello, world!"']300-301- - title: "Object Identifier-Index: `.foo`, `.foo.bar`"302- body: |303-304- The simplest *useful* filter is `.foo`. When given a305- JSON object (aka dictionary or hash) as input, it produces306- the value at the key "foo", or null if there's none present.307-308- A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.309-310- This syntax only works for simple, identifier-like keys, that311- is, keys that are all made of alphanumeric characters and312- underscore, and which do not start with a digit.313-314- If the key contains special characters, you need to surround315- it with double quotes like this: `."foo$"`, or else `.["foo$"]`.316-317- For example `.["foo::bar"]` and `.["foo.bar"]` work while318- `.foo::bar` does not, and `.foo.bar` means `.["foo"].["bar"]`.319-320- examples:321- - program: '.foo'322- input: '{"foo": 42, "bar": "less interesting data"}'323- output: [42]324- - program: '.foo'325- input: '{"notfoo": true, "alsonotfoo": false}'326- output: ['null']327- - program: '.["foo"]'328- input: '{"foo": 42}'329- output: [42]330-331- - title: "Optional Object Identifier-Index: `.foo?`"332- body: |333-334- Just like `.foo`, but does not output even an error when `.`335- is not an array or an object.336-337- examples:338- - program: '.foo?'339- input: '{"foo": 42, "bar": "less interesting data"}'340- output: [42]341- - program: '.foo?'342- input: '{"notfoo": true, "alsonotfoo": false}'343- output: ['null']344- - program: '.["foo"]?'345- input: '{"foo": 42}'346- output: [42]347- - program: '[.foo?]'348- input: '[1,2]'349- output: ['[]']350-351- - title: "Generic Object Index: `.[<string>]`"352- body: |353-354- You can also look up fields of an object using syntax like355- `.["foo"]` (.foo above is a shorthand version of this, but356- only for identifier-like strings).357-358- - title: "Array Index: `.[2]`"359- body: |360-361- When the index value is an integer, `.[<value>]` can index362- arrays. Arrays are zero-based, so `.[2]` returns the third363- element.364-365- Negative indices are allowed, with -1 referring to the last366- element, -2 referring to the next to last element, and so on.367-368- examples:369- - program: '.[0]'370- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'371- output: ['{"name":"JSON", "good":true}']372-373- - program: '.[2]'374- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'375- output: ['null']376-377- - program: '.[-2]'378- input: '[1,2,3]'379- output: ['2']380-381- - title: "Array/String Slice: `.[10:15]`"382- body: |383-384- The `.[10:15]` syntax can be used to return a subarray of an385- array or substring of a string. The array returned by386- `.[10:15]` will be of length 5, containing the elements from387- index 10 (inclusive) to index 15 (exclusive). Either index may388- be negative (in which case it counts backwards from the end of389- the array), or omitted (in which case it refers to the start390- or end of the array).391-392- examples:393- - program: '.[2:4]'394- input: '["a","b","c","d","e"]'395- output: ['["c", "d"]']396-397- - program: '.[2:4]'398- input: '"abcdefghi"'399- output: ['"cd"']400-401- - program: '.[:3]'402- input: '["a","b","c","d","e"]'403- output: ['["a", "b", "c"]']404-405- - program: '.[-2:]'406- input: '["a","b","c","d","e"]'407- output: ['["d", "e"]']408-409- - title: "Array/Object Value Iterator: `.[]`"410- body: |411-412- If you use the `.[index]` syntax, but omit the index413- entirely, it will return *all* of the elements of an414- array. Running `.[]` with the input `[1,2,3]` will produce the415- numbers as three separate results, rather than as a single416- array.417-418- You can also use this on an object, and it will return all419- the values of the object.420-421- examples:422- - program: '.[]'423- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'424- output:425- - '{"name":"JSON", "good":true}'426- - '{"name":"XML", "good":false}'427-428- - program: '.[]'429- input: '[]'430- output: []431-432- - program: '.[]'433- input: '{"a": 1, "b": 1}'434- output: ['1', '1']435-436- - title: "`.[]?`"437- body: |438-439- Like `.[]`, but no errors will be output if . is not an array440- or object.441-442- - title: "Comma: `,`"443- body: |444-445- If two filters are separated by a comma, then the446- same input will be fed into both and the two filters' output447- value streams will be concatenated in order: first, all of the448- outputs produced by the left expression, and then all of the449- outputs produced by the right. For instance, filter `.foo,450- .bar`, produces both the "foo" fields and "bar" fields as451- separate outputs.452-453- examples:454- - program: '.foo, .bar'455- input: '{"foo": 42, "bar": "something else", "baz": true}'456- output: ['42', '"something else"']457-458- - program: ".user, .projects[]"459- input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'460- output: ['"stedolan"', '"jq"', '"wikiflow"']461-462- - program: '.[4,2]'463- input: '["a","b","c","d","e"]'464- output: ['"e"', '"c"']465-466- - title: "Pipe: `|`"467- body: |468-469- The | operator combines two filters by feeding the output(s) of470- the one on the left into the input of the one on the right. It's471- pretty much the same as the Unix shell's pipe, if you're used to472- that.473-474- If the one on the left produces multiple results, the one on475- the right will be run for each of those results. So, the476- expression `.[] | .foo` retrieves the "foo" field of each477- element of the input array.478-479- Note that `.a.b.c` is the same as `.a | .b | .c`.480-481- Note too that `.` is the input value at the particular stage482- in a "pipeline", specifically: where the `.` expression appears.483- Thus `.a | . | .b` is the same as `.a.b`, as the `.` in the484- middle refers to whatever value `.a` produced.485-486- examples:487- - program: '.[] | .name'488- input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'489- output: ['"JSON"', '"XML"']490-491- - title: "Parenthesis"492- body: |493-494- Parenthesis work as a grouping operator just as in any typical495- programming language.496-497- examples:498- - program: '(. + 2) * 5'499- input: '1'500- output: [15]501-502- - title: Types and Values503- body: |504-505- jq supports the same set of datatypes as JSON - numbers,506- strings, booleans, arrays, objects (which in JSON-speak are507- hashes with only string keys), and "null".508-509- Booleans, null, strings and numbers are written the same way as510- in javascript. Just like everything else in jq, these simple511- values take an input and produce an output - `42` is a valid jq512- expression that takes an input, ignores it, and returns 42513- instead.514-515- entries:516- - title: "Array construction: `[]`"517- body: |518-519- As in JSON, `[]` is used to construct arrays, as in520- `[1,2,3]`. The elements of the arrays can be any jq521- expression, including a pipeline. All of the results produced522- by all of the expressions are collected into one big array.523- You can use it to construct an array out of a known quantity524- of values (as in `[.foo, .bar, .baz]`) or to "collect" all the525- results of a filter into an array (as in `[.items[].name]`)526-527- Once you understand the "," operator, you can look at jq's array528- syntax in a different light: the expression `[1,2,3]` is not using a529- built-in syntax for comma-separated arrays, but is instead applying530- the `[]` operator (collect results) to the expression 1,2,3 (which531- produces three different results).532-533- If you have a filter `X` that produces four results,534- then the expression `[X]` will produce a single result, an535- array of four elements.536-537- examples:538- - program: "[.user, .projects[]]"539- input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'540- output: ['["stedolan", "jq", "wikiflow"]']541- - program: "[ .[] | . * 2]"542- input: '[1, 2, 3]'543- output: ['[2, 4, 6]']544-545- - title: "Object Construction: `{}`"546- body: |547-548- Like JSON, `{}` is for constructing objects (aka549- dictionaries or hashes), as in: `{"a": 42, "b": 17}`.550-551- If the keys are "identifier-like", then the quotes can be left552- off, as in `{a:42, b:17}`. Variable references as key553- expressions use the value of the variable as the key. Key554- expressions other than constant literals, identifiers, or555- variable references, need to be parenthesized, e.g.,556- `{("a"+"b"):59}`.557-558- The value can be any expression (although you may need to wrap559- it in parentheses if, for example, it contains colons), which560- gets applied to the {} expression's input (remember, all561- filters have an input and an output).562-563- {foo: .bar}564-565- will produce the JSON object `{"foo": 42}` if given the JSON566- object `{"bar":42, "baz":43}` as its input. You can use this567- to select particular fields of an object: if the input is an568- object with "user", "title", "id", and "content" fields and569- you just want "user" and "title", you can write570-571- {user: .user, title: .title}572-573- Because that is so common, there's a shortcut syntax for it:574- `{user, title}`.575-576- If one of the expressions produces multiple results,577- multiple dictionaries will be produced. If the input's578-579- {"user":"stedolan","titles":["JQ Primer", "More JQ"]}580-581- then the expression582-583- {user, title: .titles[]}584-585- will produce two outputs:586-587- {"user":"stedolan", "title": "JQ Primer"}588- {"user":"stedolan", "title": "More JQ"}589-590- Putting parentheses around the key means it will be evaluated as an591- expression. With the same input as above,592-593- {(.user): .titles}594-595- produces596-597- {"stedolan": ["JQ Primer", "More JQ"]}598-599- Variable references as keys use the value of the variable as600- the key. Without a value then the variable's name becomes the601- key and its value becomes the value,602-603- "f o o" as $foo | "b a r" as $bar | {$foo, $bar:$foo}604-605- produces606-607- {"f o o":"f o o","b a r":"f o o"}608-609- examples:610- - program: '{user, title: .titles[]}'611- input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'612- output:613- - '{"user":"stedolan", "title": "JQ Primer"}'614- - '{"user":"stedolan", "title": "More JQ"}'615- - program: '{(.user): .titles}'616- input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'617- output: ['{"stedolan": ["JQ Primer", "More JQ"]}']618-619- - title: "Recursive Descent: `..`"620- body: |621-622- Recursively descends `.`, producing every value. This is the623- same as the zero-argument `recurse` builtin (see below). This624- is intended to resemble the XPath `//` operator. Note that625- `..a` does not work; use `..|.a` instead. In the example626- below we use `..|.a?` to find all the values of object keys627- "a" in any object found "below" `.`.628-629- This is particularly useful in conjunction with `path(EXP)`630- (also see below) and the `?` operator.631-632- examples:633- - program: '..|.a?'634- input: '[[{"a":1}]]'635- output: ['1']636-637- - title: Builtin operators and functions638- body: |639-640- Some jq operator (for instance, `+`) do different things641- depending on the type of their arguments (arrays, numbers,642- etc.). However, jq never does implicit type conversions. If you643- try to add a string to an object you'll get an error message and644- no result.645-646- entries:647- - title: "Addition: `+`"648- body: |649-650- The operator `+` takes two filters, applies them both651- to the same input, and adds the results together. What652- "adding" means depends on the types involved:653-654- - **Numbers** are added by normal arithmetic.655-656- - **Arrays** are added by being concatenated into a larger array.657-658- - **Strings** are added by being joined into a larger string.659-660- - **Objects** are added by merging, that is, inserting all661- the key-value pairs from both objects into a single662- combined object. If both objects contain a value for the663- same key, the object on the right of the `+` wins. (For664- recursive merge use the `*` operator.)665-666- `null` can be added to any value, and returns the other667- value unchanged.668-669- examples:670- - program: '.a + 1'671- input: '{"a": 7}'672- output: ['8']673- - program: '.a + .b'674- input: '{"a": [1,2], "b": [3,4]}'675- output: ['[1,2,3,4]']676- - program: '.a + null'677- input: '{"a": 1}'678- output: ['1']679- - program: '.a + 1'680- input: '{}'681- output: ['1']682- - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'683- input: 'null'684- output: ['{"a": 42, "b": 2, "c": 3}']685-686- - title: "Subtraction: `-`"687- body: |688-689- As well as normal arithmetic subtraction on numbers, the `-`690- operator can be used on arrays to remove all occurrences of691- the second array's elements from the first array.692-693- examples:694- - program: '4 - .a'695- input: '{"a":3}'696- output: ['1']697- - program: . - ["xml", "yaml"]698- input: '["xml", "yaml", "json"]'699- output: ['["json"]']700-701- - title: "Multiplication, division, modulo: `*`, `/`, and `%`"702- body: |703-704- These infix operators behave as expected when given two numbers.705- Division by zero raises an error. `x % y` computes x modulo y.706-707- Multiplying a string by a number produces the concatenation of708- that string that many times. `"x" * 0` produces **null**.709-710- Dividing a string by another splits the first using the second711- as separators.712-713- Multiplying two objects will merge them recursively: this works714- like addition but if both objects contain a value for the715- same key, and the values are objects, the two are merged with716- the same strategy.717-718- examples:719- - program: '10 / . * 3'720- input: 5721- output: [6]722- - program: '. / ", "'723- input: '"a, b,c,d, e"'724- output: ['["a","b,c,d","e"]']725- - program: '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'726- input: 'null'727- output: ['{"k": {"a": 0, "b": 2, "c": 3}}']728- - program: '.[] | (1 / .)?'729- input: '[1,0,-1]'730- output: ['1', '-1']731-732-733- - title: "`length`"734- body: |735-736- The builtin function `length` gets the length of various737- different types of value:738-739- - The length of a **string** is the number of Unicode740- codepoints it contains (which will be the same as its741- JSON-encoded length in bytes if it's pure ASCII).742-743- - The length of an **array** is the number of elements.744-745- - The length of an **object** is the number of key-value pairs.746-747- - The length of **null** is zero.748-749- examples:750- - program: '.[] | length'751- input: '[[1,2], "string", {"a":2}, null]'752- output: [2, 6, 1, 0]753-754-755- - title: "`utf8bytelength`"756- body: |757-758- The builtin function `utf8bytelength` outputs the number of759- bytes used to encode a string in UTF-8.760-761- examples:762- - program: 'utf8bytelength'763- input: '"\u03bc"'764- output: [2]765-766- - title: "`keys`, `keys_unsorted`"767- body: |768-769- The builtin function `keys`, when given an object, returns770- its keys in an array.771-772- The keys are sorted "alphabetically", by unicode codepoint773- order. This is not an order that makes particular sense in774- any particular language, but you can count on it being the775- same for any two objects with the same set of keys,776- regardless of locale settings.777-778- When `keys` is given an array, it returns the valid indices779- for that array: the integers from 0 to length-1.780-781- The `keys_unsorted` function is just like `keys`, but if782- the input is an object then the keys will not be sorted,783- instead the keys will roughly be in insertion order.784-785- examples:786- - program: 'keys'787- input: '{"abc": 1, "abcd": 2, "Foo": 3}'788- output: ['["Foo", "abc", "abcd"]']789- - program: 'keys'790- input: '[42,3,35]'791- output: ['[0,1,2]']792-793- - title: "`has(key)`"794- body: |795-796- The builtin function `has` returns whether the input object797- has the given key, or the input array has an element at the798- given index.799-800- `has($key)` has the same effect as checking whether `$key`801- is a member of the array returned by `keys`, although `has`802- will be faster.803-804- examples:805- - program: 'map(has("foo"))'806- input: '[{"foo": 42}, {}]'807- output: ['[true, false]']808- - program: 'map(has(2))'809- input: '[[0,1], ["a","b","c"]]'810- output: ['[false, true]']811-812- - title: "`in`"813- body: |814-815- The builtin function `in` returns whether or not the input key is in the816- given object, or the input index corresponds to an element817- in the given array. It is, essentially, an inversed version818- of `has`.819-820- examples:821- - program: '.[] | in({"foo": 42})'822- input: '["foo", "bar"]'823- output: ['true', 'false']824- - program: 'map(in([0,1]))'825- input: '[2, 0]'826- output: ['[false, true]']827-828- - title: "`map(x)`, `map_values(x)`"829- body: |830-831- For any filter `x`, `map(x)` will run that filter for each832- element of the input array, and return the outputs in a new833- array. `map(.+1)` will increment each element of an array of numbers.834-835- Similarly, `map_values(x)` will run that filter for each element,836- but it will return an object when an object is passed.837-838- `map(x)` is equivalent to `[.[] | x]`. In fact, this is how839- it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`.840-841- examples:842- - program: 'map(.+1)'843- input: '[1,2,3]'844- output: ['[2,3,4]']845-846- - program: 'map_values(.+1)'847- input: '{"a": 1, "b": 2, "c": 3}'848- output: ['{"a": 2, "b": 3, "c": 4}']849-850- - title: "`path(path_expression)`"851- body: |852-853- Outputs array representations of the given path expression854- in `.`. The outputs are arrays of strings (object keys)855- and/or numbers (array indices).856-857- Path expressions are jq expressions like `.a`, but also `.[]`.858- There are two types of path expressions: ones that can match859- exactly, and ones that cannot. For example, `.a.b.c` is an860- exact match path expression, while `.a[].b` is not.861-862- `path(exact_path_expression)` will produce the array863- representation of the path expression even if it does not864- exist in `.`, if `.` is `null` or an array or an object.865-866- `path(pattern)` will produce array representations of the867- paths matching `pattern` if the paths exist in `.`.868-869- Note that the path expressions are not different from normal870- expressions. The expression871- `path(..|select(type=="boolean"))` outputs all the paths to872- boolean values in `.`, and only those paths.873-874- examples:875- - program: 'path(.a[0].b)'876- input: 'null'877- output: ['["a",0,"b"]']878- - program: '[path(..)]'879- input: '{"a":[{"b":1}]}'880- output: ['[[],["a"],["a",0],["a",0,"b"]]']881-882- - title: "`del(path_expression)`"883- body: |884-885- The builtin function `del` removes a key and its corresponding886- value from an object.887-888- examples:889- - program: 'del(.foo)'890- input: '{"foo": 42, "bar": 9001, "baz": 42}'891- output: ['{"bar": 9001, "baz": 42}']892- - program: 'del(.[1, 2])'893- input: '["foo", "bar", "baz"]'894- output: ['["foo"]']895-896- - title: "`getpath(PATHS)`"897- body: |898-899- The builtin function `getpath` outputs the values in `.` found900- at each path in `PATHS`.901-902- examples:903- - program: 'getpath(["a","b"])'904- input: 'null'905- output: ['null']906- - program: '[getpath(["a","b"], ["a","c"])]'907- input: '{"a":{"b":0, "c":1}}'908- output: ['[0, 1]']909-910- - title: "`setpath(PATHS; VALUE)`"911- body: |912-913- The builtin function `setpath` sets the `PATHS` in `.` to `VALUE`.914-915- examples:916- - program: 'setpath(["a","b"]; 1)'917- input: 'null'918- output: ['{"a": {"b": 1}}']919- - program: 'setpath(["a","b"]; 1)'920- input: '{"a":{"b":0}}'921- output: ['{"a": {"b": 1}}']922- - program: 'setpath([0,"a"]; 1)'923- input: 'null'924- output: ['[{"a":1}]']925-926- - title: "`delpaths(PATHS)`"927- body: |928-929- The builtin function `delpaths` sets the `PATHS` in `.`.930- `PATHS` must be an array of paths, where each path is an array931- of strings and numbers.932-933- examples:934- - program: 'delpaths([["a","b"]])'935- input: '{"a":{"b":1},"x":{"y":2}}'936- output: ['{"a":{},"x":{"y":2}}']937-938- - title: "`to_entries`, `from_entries`, `with_entries`"939- body: |940-941- These functions convert between an object and an array of942- key-value pairs. If `to_entries` is passed an object, then943- for each `k: v` entry in the input, the output array944- includes `{"key": k, "value": v}`.945-946- `from_entries` does the opposite conversion, and947- `with_entries(foo)` is a shorthand for `to_entries |948- map(foo) | from_entries`, useful for doing some operation to949- all keys and values of an object. `from_entries` accepts key, Key,950- name, Name, value and Value as keys.951-952- examples:953- - program: 'to_entries'954- input: '{"a": 1, "b": 2}'955- output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']956- - program: 'from_entries'957- input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'958- output: ['{"a": 1, "b": 2}']959- - program: 'with_entries(.key |= "KEY_" + .)'960- input: '{"a": 1, "b": 2}'961- output: ['{"KEY_a": 1, "KEY_b": 2}']962-963-964- - title: "`select(boolean_expression)`"965- body: |966-967- The function `select(foo)` produces its input unchanged if968- `foo` returns true for that input, and produces no output969- otherwise.970-971- It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`972- will give you `[2,3]`.973-974- examples:975- - program: 'map(select(. >= 2))'976- input: '[1,5,3,0,7]'977- output: ['[5,3,7]']978- - program: '.[] | select(.id == "second")'979- input: '[{"id": "first", "val": 1}, {"id": "second", "val": 2}]'980- output: ['{"id": "second", "val": 2}']981-982-983- - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"984- body: |985-986- These built-ins select only inputs that are arrays, objects,987- iterables (arrays or objects), booleans, numbers, normal988- numbers, finite numbers, strings, null, non-null values, and989- non-iterables, respectively.990-991- examples:992- - program: '.[]|numbers'993- input: '[[],{},1,"foo",null,true,false]'994- output: ['1']995-996- - title: "`empty`"997- body: |998-999- `empty` returns no results. None at all. Not even `null`.1000-1001- It's useful on occasion. You'll know if you need it :)1002-1003- examples:1004- - program: '1, empty, 2'1005- input: 'null'1006- output: [1, 2]1007- - program: '[1,2,empty,3]'1008- input: 'null'1009- output: ['[1,2,3]']1010-1011- - title: "`error(message)`"1012- body: |1013-1014- Produces an error, just like `.a` applied to values other than1015- null and objects would, but with the given message as the1016- error's value. Errors can be caught with try/catch; see below.1017-1018- - title: "`halt`"1019- body: |1020-1021- Stops the jq program with no further outputs. jq will exit1022- with exit status `0`.1023-1024- - title: "`halt_error`, `halt_error(exit_code)`"1025- body: |1026-1027- Stops the jq program with no further outputs. The input will1028- be printed on `stderr` as raw output (i.e., strings will not1029- have double quotes) with no decoration, not even a newline.1030-1031- The given `exit_code` (defaulting to `5`) will be jq's exit1032- status.1033-1034- For example, `"Error: somthing went wrong\n"|halt_error(1)`.1035-1036- - title: "`$__loc__`"1037- body: |1038-1039- Produces an object with a "file" key and a "line" key, with1040- the filename and line number where `$__loc__` occurs, as1041- values.1042-1043- examples:1044- - program: 'try error("\($__loc__)") catch .'1045- input: 'null'1046- output: ['"{\"file\":\"<top-level>\",\"line\":1}"']1047-1048- - title: "`paths`, `paths(node_filter)`, `leaf_paths`"1049- body: |1050-1051- `paths` outputs the paths to all the elements in its input1052- (except it does not output the empty list, representing .1053- itself).1054-1055- `paths(f)` outputs the paths to any values for which `f` is true.1056- That is, `paths(numbers)` outputs the paths to all numeric1057- values.1058-1059- `leaf_paths` is an alias of `paths(scalars)`; `leaf_paths` is1060- *deprecated* and will be removed in the next major release.1061-1062- examples:1063- - program: '[paths]'1064- input: '[1,[[],{"a":2}]]'1065- output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']1066- - program: '[paths(scalars)]'1067- input: '[1,[[],{"a":2}]]'1068- output: ['[[0],[1,1,"a"]]']1069-1070- - title: "`add`"1071- body: |1072-1073- The filter `add` takes as input an array, and produces as1074- output the elements of the array added together. This might1075- mean summed, concatenated or merged depending on the types1076- of the elements of the input array - the rules are the same1077- as those for the `+` operator (described above).1078-1079- If the input is an empty array, `add` returns `null`.1080-1081- examples:1082- - program: add1083- input: '["a","b","c"]'1084- output: ['"abc"']1085- - program: add1086- input: '[1, 2, 3]'1087- output: [6]1088- - program: add1089- input: '[]'1090- output: ["null"]1091-1092- - title: "`any`, `any(condition)`, `any(generator; condition)`"1093- body: |1094-1095- The filter `any` takes as input an array of boolean values,1096- and produces `true` as output if any of the elements of1097- the array are `true`.1098-1099- If the input is an empty array, `any` returns `false`.1100-1101- The `any(condition)` form applies the given condition to the1102- elements of the input array.1103-1104- The `any(generator; condition)` form applies the given1105- condition to all the outputs of the given generator.1106-1107- examples:1108- - program: any1109- input: '[true, false]'1110- output: ["true"]1111- - program: any1112- input: '[false, false]'1113- output: ["false"]1114- - program: any1115- input: '[]'1116- output: ["false"]1117-1118- - title: "`all`, `all(condition)`, `all(generator; condition)`"1119- body: |1120-1121- The filter `all` takes as input an array of boolean values,1122- and produces `true` as output if all of the elements of1123- the array are `true`.1124-1125- The `all(condition)` form applies the given condition to the1126- elements of the input array.1127-1128- The `all(generator; condition)` form applies the given1129- condition to all the outputs of the given generator.1130-1131- If the input is an empty array, `all` returns `true`.1132-1133- examples:1134- - program: all1135- input: '[true, false]'1136- output: ["false"]1137- - program: all1138- input: '[true, true]'1139- output: ["true"]1140- - program: all1141- input: '[]'1142- output: ["true"]1143-1144- - title: "`flatten`, `flatten(depth)`"1145- body: |1146-1147- The filter `flatten` takes as input an array of nested arrays,1148- and produces a flat array in which all arrays inside the original1149- array have been recursively replaced by their values. You can pass1150- an argument to it to specify how many levels of nesting to flatten.1151-1152- `flatten(2)` is like `flatten`, but going only up to two1153- levels deep.1154-1155- examples:1156- - program: flatten1157- input: '[1, [2], [[3]]]'1158- output: ["[1, 2, 3]"]1159- - program: flatten(1)1160- input: '[1, [2], [[3]]]'1161- output: ["[1, 2, [3]]"]1162- - program: flatten1163- input: '[[]]'1164- output: ["[]"]1165- - program: flatten1166- input: '[{"foo": "bar"}, [{"foo": "baz"}]]'1167- output: ['[{"foo": "bar"}, {"foo": "baz"}]']1168-1169- - title: "`range(upto)`, `range(from;upto)` `range(from;upto;by)`"1170- body: |1171-1172- The `range` function produces a range of numbers. `range(4;10)`1173- produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers1174- are produced as separate outputs. Use `[range(4;10)]` to get a range as1175- an array.1176-1177- The one argument form generates numbers from 0 to the given1178- number, with an increment of 1.1179-1180- The two argument form generates numbers from `from` to `upto`1181- with an increment of 1.1182-1183- The three argument form generates numbers `from` to `upto`1184- with an increment of `by`.1185-1186- examples:1187- - program: 'range(2;4)'1188- input: 'null'1189- output: ['2', '3']1190- - program: '[range(2;4)]'1191- input: 'null'1192- output: ['[2,3]']1193- - program: '[range(4)]'1194- input: 'null'1195- output: ['[0,1,2,3]']1196- - program: '[range(0;10;3)]'1197- input: 'null'1198- output: ['[0,3,6,9]']1199- - program: '[range(0;10;-1)]'1200- input: 'null'1201- output: ['[]']1202- - program: '[range(0;-5;-1)]'1203- input: 'null'1204- output: ['[0,-1,-2,-3,-4]']1205-1206- - title: "`floor`"1207- body: |1208-1209- The `floor` function returns the floor of its numeric input.1210-1211- examples:1212- - program: 'floor'1213- input: '3.14159'1214- output: ['3']1215-1216- - title: "`sqrt`"1217- body: |1218-1219- The `sqrt` function returns the square root of its numeric input.1220-1221- examples:1222- - program: 'sqrt'1223- input: '9'1224- output: ['3']1225-1226- - title: "`tonumber`"1227- body: |1228-1229- The `tonumber` function parses its input as a number. It1230- will convert correctly-formatted strings to their numeric1231- equivalent, leave numbers alone, and give an error on all other input.1232-1233- examples:1234- - program: '.[] | tonumber'1235- input: '[1, "1"]'1236- output: [1, 1]1237-1238- - title: "`tostring`"1239- body: |1240-1241- The `tostring` function prints its input as a1242- string. Strings are left unchanged, and all other values are1243- JSON-encoded.1244-1245- examples:1246- - program: '.[] | tostring'1247- input: '[1, "1", [1]]'1248- output: ['"1"', '"1"', '"[1]"']1249-1250- - title: "`type`"1251- body: |1252-1253- The `type` function returns the type of its argument as a1254- string, which is one of null, boolean, number, string, array1255- or object.1256-1257- examples:1258- - program: 'map(type)'1259- input: '[0, false, [], {}, null, "hello"]'1260- output: ['["number", "boolean", "array", "object", "null", "string"]']1261-1262- - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1263- body: |1264-1265- Some arithmetic operations can yield infinities and "not a1266- number" (NaN) values. The `isinfinite` builtin returns `true`1267- if its input is infinite. The `isnan` builtin returns `true`1268- if its input is a NaN. The `infinite` builtin returns a1269- positive infinite value. The `nan` builtin returns a NaN.1270- The `isnormal` builtin returns true if its input is a normal1271- number.1272-1273- Note that division by zero raises an error.1274-1275- Currently most arithmetic operations operating on infinities,1276- NaNs, and sub-normals do not raise errors.1277-1278- examples:1279- - program: '.[] | (infinite * .) < 0'1280- input: '[-1, 1]'1281- output: ['true', 'false']1282- - program: 'infinite, nan | type'1283- input: 'null'1284- output: ['"number"', '"number"']1285-1286- - title: "`sort, sort_by(path_expression)`"1287- body: |1288-1289- The `sort` functions sorts its input, which must be an1290- array. Values are sorted in the following order:1291-1292- * `null`1293- * `false`1294- * `true`1295- * numbers1296- * strings, in alphabetical order (by unicode codepoint value)1297- * arrays, in lexical order1298- * objects1299-1300- The ordering for objects is a little complex: first they're1301- compared by comparing their sets of keys (as arrays in1302- sorted order), and if their keys are equal then the values1303- are compared key by key.1304-1305- `sort` may be used to sort by a particular field of an1306- object, or by applying any jq filter.1307-1308- `sort_by(foo)` compares two elements by comparing the result of1309- `foo` on each element.1310-1311- examples:1312- - program: 'sort'1313- input: '[8,3,null,6]'1314- output: ['[null,3,6,8]']1315- - program: 'sort_by(.foo)'1316- input: '[{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}]'1317- output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']1318-1319- - title: "`group_by(path_expression)`"1320- body: |1321-1322- `group_by(.foo)` takes as input an array, groups the1323- elements having the same `.foo` field into separate arrays,1324- and produces all of these arrays as elements of a larger1325- array, sorted by the value of the `.foo` field.1326-1327- Any jq expression, not just a field access, may be used in1328- place of `.foo`. The sorting order is the same as described1329- in the `sort` function above.1330-1331- examples:1332- - program: 'group_by(.foo)'1333- input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'1334- output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']1335-1336- - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1337- body: |1338-1339- Find the minimum or maximum element of the input array.1340-1341- The `min_by(path_exp)` and `max_by(path_exp)` functions allow1342- you to specify a particular field or property to examine, e.g.1343- `min_by(.foo)` finds the object with the smallest `foo` field.1344-1345- examples:1346- - program: 'min'1347- input: '[5,4,2,7]'1348- output: ['2']1349- - program: 'max_by(.foo)'1350- input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'1351- output: ['{"foo":2, "bar":3}']1352-1353- - title: "`unique`, `unique_by(path_exp)`"1354- body: |1355-1356- The `unique` function takes as input an array and produces1357- an array of the same elements, in sorted order, with1358- duplicates removed.1359-1360- The `unique_by(path_exp)` function will keep only one element1361- for each value obtained by applying the argument. Think of it1362- as making an array by taking one element out of every group1363- produced by `group`.1364-1365- examples:1366- - program: 'unique'1367- input: '[1,2,5,3,5,3,1,3]'1368- output: ['[1,2,3,5]']1369- - program: 'unique_by(.foo)'1370- input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'1371- output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']1372- - program: 'unique_by(length)'1373- input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'1374- output: ['["bacon", "chunky", "asparagus"]']1375-1376- - title: "`reverse`"1377- body: |1378-1379- This function reverses an array.1380-1381- examples:1382- - program: 'reverse'1383- input: '[1,2,3,4]'1384- output: ['[4,3,2,1]']1385-1386- - title: "`contains(element)`"1387- body: |1388-1389- The filter `contains(b)` will produce true if b is1390- completely contained within the input. A string B is1391- contained in a string A if B is a substring of A. An array B1392- is contained in an array A if all elements in B are1393- contained in any element in A. An object B is contained in1394- object A if all of the values in B are contained in the1395- value in A with the same key. All other types are assumed to1396- be contained in each other if they are equal.1397-1398- examples:1399- - program: 'contains("bar")'1400- input: '"foobar"'1401- output: ['true']1402- - program: 'contains(["baz", "bar"])'1403- input: '["foobar", "foobaz", "blarp"]'1404- output: ['true']1405- - program: 'contains(["bazzzzz", "bar"])'1406- input: '["foobar", "foobaz", "blarp"]'1407- output: ['false']1408- - program: 'contains({foo: 12, bar: [{barp: 12}]})'1409- input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1410- output: ['true']1411- - program: 'contains({foo: 12, bar: [{barp: 15}]})'1412- input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1413- output: ['false']1414-1415- - title: "`indices(s)`"1416- body: |1417-1418- Outputs an array containing the indices in `.` where `s`1419- occurs. The input may be an array, in which case if `s` is an1420- array then the indices output will be those where all elements1421- in `.` match those of `s`.1422-1423- examples:1424- - program: 'indices(", ")'1425- input: '"a,b, cd, efg, hijk"'1426- output: ['[3,7,12]']1427- - program: 'indices(1)'1428- input: '[0,1,2,1,3,1,4]'1429- output: ['[1,3,5]']1430- - program: 'indices([1,2])'1431- input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1432- output: ['[1,8]']1433-1434- - title: "`index(s)`, `rindex(s)`"1435- body: |1436-1437- Outputs the index of the first (`index`) or last (`rindex`)1438- occurrence of `s` in the input.1439-1440- examples:1441- - program: 'index(", ")'1442- input: '"a,b, cd, efg, hijk"'1443- output: ['3']1444- - program: 'rindex(", ")'1445- input: '"a,b, cd, efg, hijk"'1446- output: ['12']1447-1448- - title: "`inside`"1449- body: |1450-1451- The filter `inside(b)` will produce true if the input is1452- completely contained within b. It is, essentially, an1453- inversed version of `contains`.1454-1455- examples:1456- - program: 'inside("foobar")'1457- input: '"bar"'1458- output: ['true']1459- - program: 'inside(["foobar", "foobaz", "blarp"])'1460- input: '["baz", "bar"]'1461- output: ['true']1462- - program: 'inside(["foobar", "foobaz", "blarp"])'1463- input: '["bazzzzz", "bar"]'1464- output: ['false']1465- - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1466- input: '{"foo": 12, "bar": [{"barp": 12}]}'1467- output: ['true']1468- - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1469- input: '{"foo": 12, "bar": [{"barp": 15}]}'1470- output: ['false']1471-1472- - title: "`startswith(str)`"1473- body: |1474-1475- Outputs `true` if . starts with the given string argument.1476-1477- examples:1478- - program: '[.[]|startswith("foo")]'1479- input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1480- output: ['[false, true, false, true, false]']1481-1482- - title: "`endswith(str)`"1483- body: |1484-1485- Outputs `true` if . ends with the given string argument.1486-1487- examples:1488- - program: '[.[]|endswith("foo")]'1489- input: '["foobar", "barfoo"]'1490- output: ['[false, true]']1491-1492- - title: "`combinations`, `combinations(n)`"1493- body: |1494-1495- Outputs all combinations of the elements of the arrays in the1496- input array. If given an argument `n`, it outputs all combinations1497- of `n` repetitions of the input array.1498-1499- examples:1500- - program: 'combinations'1501- input: '[[1,2], [3, 4]]'1502- output: ['[1, 3]', '[1, 4]', '[2, 3]', '[2, 4]']1503- - program: 'combinations(2)'1504- input: '[0, 1]'1505- output: ['[0, 0]', '[0, 1]', '[1, 0]', '[1, 1]']1506-1507- - title: "`ltrimstr(str)`"1508- body: |1509-1510- Outputs its input with the given prefix string removed, if it1511- starts with it.1512-1513- examples:1514- - program: '[.[]|ltrimstr("foo")]'1515- input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1516- output: ['["fo","","barfoo","bar","afoo"]']1517-1518- - title: "`rtrimstr(str)`"1519- body: |1520-1521- Outputs its input with the given suffix string removed, if it1522- ends with it.1523-1524- examples:1525- - program: '[.[]|rtrimstr("foo")]'1526- input: '["fo", "foo", "barfoo", "foobar", "foob"]'1527- output: ['["fo","","bar","foobar","foob"]']1528-1529- - title: "`explode`"1530- body: |1531-1532- Converts an input string into an array of the string's1533- codepoint numbers.1534-1535- examples:1536- - program: 'explode'1537- input: '"foobar"'1538- output: ['[102,111,111,98,97,114]']1539-1540- - title: "`implode`"1541- body: |1542-1543- The inverse of explode.1544-1545- examples:1546- - program: 'implode'1547- input: '[65, 66, 67]'1548- output: ['"ABC"']1549-1550- - title: "`split(str)`"1551- body: |1552-1553- Splits an input string on the separator argument.1554-1555- examples:1556- - program: 'split(", ")'1557- input: '"a, b,c,d, e, "'1558- output: ['["a","b,c,d","e",""]']1559-1560- - title: "`join(str)`"1561- body: |1562-1563- Joins the array of elements given as input, using the1564- argument as separator. It is the inverse of `split`: that is,1565- running `split("foo") | join("foo")` over any input string1566- returns said input string.1567-1568- Numbers and booleans in the input are converted to strings.1569- Null values are treated as empty strings. Arrays and objects1570- in the input are not supported.1571-1572- examples:1573- - program: 'join(", ")'1574- input: '["a","b,c,d","e"]'1575- output: ['"a, b,c,d, e"']1576- - program: 'join(" ")'1577- input: '["a",1,2.3,true,null,false]'1578- output: ['"a 1 2.3 true false"']1579-1580- - title: "`ascii_downcase`, `ascii_upcase`"1581- body: |1582-1583- Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1584- converted to the specified case.1585-1586- example:1587- - program: 'ascii_upcase'1588- input: '"useful but not for é"'1589- output: '"USEFUL BUT NOT FOR é"'1590-1591- - title: "`while(cond; update)`"1592- body: |1593-1594- The `while(cond; update)` function allows you to repeatedly1595- apply an update to `.` until `cond` is false.1596-1597- Note that `while(cond; update)` is internally defined as a1598- recursive jq function. Recursive calls within `while` will1599- not consume additional memory if `update` produces at most one1600- output for each input. See advanced topics below.1601-1602- examples:1603- - program: '[while(.<100; .*2)]'1604- input: '1'1605- output: ['[1,2,4,8,16,32,64]']1606-1607- - title: "`until(cond; next)`"1608- body: |1609-1610- The `until(cond; next)` function allows you to repeatedly1611- apply the expression `next`, initially to `.` then to its own1612- output, until `cond` is true. For example, this can be used1613- to implement a factorial function (see below).1614-1615- Note that `until(cond; next)` is internally defined as a1616- recursive jq function. Recursive calls within `until()` will1617- not consume additional memory if `next` produces at most one1618- output for each input. See advanced topics below.1619-1620- examples:1621- - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1622- input: '4'1623- output: ['24']1624-1625-1626- - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`, `recurse_down`"1627- body: |1628-1629- The `recurse(f)` function allows you to search through a1630- recursive structure, and extract interesting data from all1631- levels. Suppose your input represents a filesystem:1632-1633- {"name": "/", "children": [1634- {"name": "/bin", "children": [1635- {"name": "/bin/ls", "children": []},1636- {"name": "/bin/sh", "children": []}]},1637- {"name": "/home", "children": [1638- {"name": "/home/stephen", "children": [1639- {"name": "/home/stephen/jq", "children": []}]}]}]}1640-1641- Now suppose you want to extract all of the filenames1642- present. You need to retrieve `.name`, `.children[].name`,1643- `.children[].children[].name`, and so on. You can do this1644- with:1645-1646- recurse(.children[]) | .name1647-1648- When called without an argument, `recurse` is equivalent to1649- `recurse(.[]?)`.1650-1651- `recurse(f)` is identical to `recurse(f; . != null)` and can be1652- used without concerns about recursion depth.1653-1654- `recurse(f; condition)` is a generator which begins by1655- emitting . and then emits in turn .|f, .|f|f, .|f|f|f, ... so long1656- as the computed value satisfies the condition. For example,1657- to generate all the integers, at least in principle, one1658- could write `recurse(.+1; true)`.1659-1660- For legacy reasons, `recurse_down` exists as an alias to1661- calling `recurse` without arguments. This alias is considered1662- *deprecated* and will be removed in the next major release.1663-1664- The recursive calls in `recurse` will not consume additional1665- memory whenever `f` produces at most a single output for each1666- input.1667-1668- examples:1669- - program: 'recurse(.foo[])'1670- input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'1671- output:1672- - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'1673- - '{"foo":[]}'1674- - '{"foo":[{"foo":[]}]}'1675- - '{"foo":[]}'1676-1677- - program: 'recurse'1678- input: '{"a":0,"b":[1]}'1679- output:1680- - '{"a":0,"b":[1]}'1681- - '0'1682- - '[1]'1683- - '1'1684-1685- - program: 'recurse(. * .; . < 20)'1686- input: 21687- output:1688- - 21689- - 41690- - 161691-1692- - title: "`walk(f)`"1693- body: |1694-1695- The `walk(f)` function applies f recursively to every1696- component of the input entity. When an array is1697- encountered, f is first applied to its elements and then to1698- the array itself; when an object is encountered, f is first1699- applied to all the values and then to the object. In1700- practice, f will usually test the type of its input, as1701- illustrated in the following examples. The first example1702- highlights the usefulness of processing the elements of an1703- array of arrays before processing the array itself. The second1704- example shows how all the keys of all the objects within the1705- input can be considered for alteration.1706-1707- examples:1708- - program: 'walk(if type == "array" then sort else . end)'1709- input: '[[4, 1, 7], [8, 5, 2], [3, 6, 9]]'1710- output:1711- - '[[1,4,7],[2,5,8],[3,6,9]]'1712-1713- - program: 'walk( if type == "object" then with_entries( .key |= sub( "^_+"; "") ) else . end )'1714- input: '[ { "_a": { "__b": 2 } } ]'1715- output:1716- - '[{"a":{"b":2}}]'1717-1718- - title: "`$ENV`, `env`"1719- body: |1720-1721- `$ENV` is an object representing the environment variables as1722- set when the jq program started.1723-1724- `env` outputs an object representing jq's current environment.1725-1726- At the moment there is no builtin for setting environment1727- variables.1728-1729- examples:1730- - program: '$ENV.PAGER'1731- input: 'null'1732- output: ['"less"']1733-1734- - program: 'env.PAGER'1735- input: 'null'1736- output: ['"less"']1737-1738- - title: "`transpose`"1739- body: |1740-1741- Transpose a possibly jagged matrix (an array of arrays).1742- Rows are padded with nulls so the result is always rectangular.1743-1744- examples:1745- - program: 'transpose'1746- input: '[[1], [2,3]]'1747- output: ['[[1,2],[null,3]]']1748-1749- - title: "`bsearch(x)`"1750- body: |1751-1752- bsearch(x) conducts a binary search for x in the input1753- array. If the input is sorted and contains x, then1754- bsearch(x) will return its index in the array; otherwise, if1755- the array is sorted, it will return (-1 - ix) where ix is an1756- insertion point such that the array would still be sorted1757- after the insertion of x at ix. If the array is not sorted,1758- bsearch(x) will return an integer that is probably of no1759- interest.1760-1761- examples:1762- - program: 'bsearch(0)'1763- input: '[0,1]'1764- output: ['0']1765- - program: 'bsearch(0)'1766- input: '[1,2,3]'1767- output: ['-1']1768- - program: 'bsearch(4) as $ix | if $ix < 0 then .[-(1+$ix)] = 4 else . end'1769- input: '[1,2,3]'1770- output: ['[1,2,3,4]']1771-1772- - title: "String interpolation - `\\(foo)`"1773- body: |1774-1775- Inside a string, you can put an expression inside parens1776- after a backslash. Whatever the expression returns will be1777- interpolated into the string.1778-1779- examples:1780- - program: '"The input was \(.), which is one less than \(.+1)"'1781- input: '42'1782- output: ['"The input was 42, which is one less than 43"']1783-1784- - title: "Convert to/from JSON"1785- body: |1786-1787- The `tojson` and `fromjson` builtins dump values as JSON texts1788- or parse JSON texts into values, respectively. The tojson1789- builtin differs from tostring in that tostring returns strings1790- unmodified, while tojson encodes strings as JSON strings.1791-1792- examples:1793- - program: '[.[]|tostring]'1794- input: '[1, "foo", ["foo"]]'1795- output: ['["1","foo","[\"foo\"]"]']1796- - program: '[.[]|tojson]'1797- input: '[1, "foo", ["foo"]]'1798- output: ['["1","\"foo\"","[\"foo\"]"]']1799- - program: '[.[]|tojson|fromjson]'1800- input: '[1, "foo", ["foo"]]'1801- output: ['[1,"foo",["foo"]]']1802-1803- - title: "Format strings and escaping"1804- body: |1805-1806- The `@foo` syntax is used to format and escape strings,1807- which is useful for building URLs, documents in a language1808- like HTML or XML, and so forth. `@foo` can be used as a1809- filter on its own, the possible escapings are:1810-1811- * `@text`:1812-1813- Calls `tostring`, see that function for details.1814-1815- * `@json`:1816-1817- Serializes the input as JSON.1818-1819- * `@html`:1820-1821- Applies HTML/XML escaping, by mapping the characters1822- `<>&'"` to their entity equivalents `<`, `>`,1823- `&`, `'`, `"`.1824-1825- * `@uri`:1826-1827- Applies percent-encoding, by mapping all reserved URI1828- characters to a `%XX` sequence.1829-1830- * `@csv`:1831-1832- The input must be an array, and it is rendered as CSV1833- with double quotes for strings, and quotes escaped by1834- repetition.1835-1836- * `@tsv`:1837-1838- The input must be an array, and it is rendered as TSV1839- (tab-separated values). Each input array will be printed as1840- a single line. Fields are separated by a single1841- tab (ascii `0x09`). Input characters line-feed (ascii `0x0a`),1842- carriage-return (ascii `0x0d`), tab (ascii `0x09`) and1843- backslash (ascii `0x5c`) will be output as escape sequences1844- `\n`, `\r`, `\t`, `\\` respectively.1845-1846- * `@sh`:1847-1848- The input is escaped suitable for use in a command-line1849- for a POSIX shell. If the input is an array, the output1850- will be a series of space-separated strings.1851-1852- * `@base64`:1853-1854- The input is converted to base64 as specified by RFC 4648.1855-1856- * `@base64d`:1857-1858- The inverse of `@base64`, input is decoded as specified by RFC 4648.1859- Note\: If the decoded string is not UTF-8, the results are undefined.1860-1861- This syntax can be combined with string interpolation in a1862- useful way. You can follow a `@foo` token with a string1863- literal. The contents of the string literal will *not* be1864- escaped. However, all interpolations made inside that string1865- literal will be escaped. For instance,1866-1867- @uri "https://www.google.com/search?q=\(.search)"1868-1869- will produce the following output for the input1870- `{"search":"what is jq?"}`:1871-1872- "https://www.google.com/search?q=what%20is%20jq%3F"1873-1874- Note that the slashes, question mark, etc. in the URL are1875- not escaped, as they were part of the string literal.1876-1877- examples:1878- - program: '@html'1879- input: '"This works if x < y"'1880- output: ['"This works if x < y"']1881-1882-# - program: '@html "<span>Anonymous said: \(.)</span>"'1883-# input: '"<script>alert(\"lol hax\");</script>"'1884-# output: ["<span>Anonymous said: <script>alert("lol hax");</script></span>"]1885-1886- - program: '@sh "echo \(.)"'1887- input: "\"O'Hara's Ale\""1888- output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]1889-1890- - program: '@base64'1891- input: '"This is a message"'1892- output: ['"VGhpcyBpcyBhIG1lc3NhZ2U="']1893-1894- - program: '@base64d'1895- input: '"VGhpcyBpcyBhIG1lc3NhZ2U="'1896- output: ['"This is a message"']1897-1898- - title: "Dates"1899- body: |1900-1901- jq provides some basic date handling functionality, with some1902- high-level and low-level builtins. In all cases these1903- builtins deal exclusively with time in UTC.1904-1905- The `fromdateiso8601` builtin parses datetimes in the ISO 86011906- format to a number of seconds since the Unix epoch1907- (1970-01-01T00:00:00Z). The `todateiso8601` builtin does the1908- inverse.1909-1910- The `fromdate` builtin parses datetime strings. Currently1911- `fromdate` only supports ISO 8601 datetime strings, but in the1912- future it will attempt to parse datetime strings in more1913- formats.1914-1915- The `todate` builtin is an alias for `todateiso8601`.1916-1917- The `now` builtin outputs the current time, in seconds since1918- the Unix epoch.1919-1920- Low-level jq interfaces to the C-library time functions are1921- also provided: `strptime`, `strftime`, `strflocaltime`,1922- `mktime`, `gmtime`, and `localtime`. Refer to your host1923- operating system's documentation for the format strings used1924- by `strptime` and `strftime`. Note: these are not necessarily1925- stable interfaces in jq, particularly as to their localization1926- functionality.1927-1928- The `gmtime` builtin consumes a number of seconds since the1929- Unix epoch and outputs a "broken down time" representation of1930- Greenwhich Meridian time as an array of numbers representing1931- (in this order): the year, the month (zero-based), the day of1932- the month (one-based), the hour of the day, the minute of the1933- hour, the second of the minute, the day of the week, and the1934- day of the year -- all one-based unless otherwise stated. The1935- day of the week number may be wrong on some systems for dates1936- before March 1st 1900, or after December 31 2099.1937-1938- The `localtime` builtin works like the `gmtime` builtin, but1939- using the local timezone setting.1940-1941- The `mktime` builtin consumes "broken down time"1942- representations of time output by `gmtime` and `strptime`.1943-1944- The `strptime(fmt)` builtin parses input strings matching the1945- `fmt` argument. The output is in the "broken down time"1946- representation consumed by `gmtime` and output by `mktime`.1947-1948- The `strftime(fmt)` builtin formats a time (GMT) with the1949- given format. The `strflocaltime` does the same, but using1950- the local timezone setting.1951-1952- The format strings for `strptime` and `strftime` are described1953- in typical C library documentation. The format string for ISO1954- 8601 datetime is `"%Y-%m-%dT%H:%M:%SZ"`.1955-1956- jq may not support some or all of this date functionality on1957- some systems. In particular, the `%u` and `%j` specifiers for1958- `strptime(fmt)` are not supported on macOS.1959-1960- examples:1961- - program: 'fromdate'1962- input: '"2015-03-05T23:51:47Z"'1963- output: ['1425599507']1964-1965- - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")'1966- input: '"2015-03-05T23:51:47Z"'1967- output: ['[2015,2,5,23,51,47,4,63]']1968-1969- - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'1970- input: '"2015-03-05T23:51:47Z"'1971- output: ['1425599507']1972-1973- - title: "SQL-Style Operators"1974- body: |1975-1976- jq provides a few SQL-style operators.1977-1978- * INDEX(stream; index_expression):1979-1980- This builtin produces an object whose keys are computed by1981- the given index expression applied to each value from the1982- given stream.1983-1984- * JOIN($idx; stream; idx_expr; join_expr):1985-1986- This builtin joins the values from the given stream to the1987- given index. The index's keys are computed by applying the1988- given index expression to each value from the given stream.1989- An array of the value in the stream and the corresponding1990- value from the index is fed to the given join expression to1991- produce each result.1992-1993- * JOIN($idx; stream; idx_expr):1994-1995- Same as `JOIN($idx; stream; idx_expr; .)`.1996-1997- * JOIN($idx; idx_expr):1998-1999- This builtin joins the input `.` to the given index, applying2000- the given index expression to `.` to compute the index key.2001- The join operation is as described above.2002-2003- * IN(s):2004-2005- This builtin outputs `true` if `.` appears in the given2006- stream, otherwise it outputs `false`.2007-2008- * IN(source; s):2009-2010- This builtin outputs `true` if any value in the source stream2011- appears in the second stream, otherwise it outputs `false`.2012-2013- - title: "`builtins`"2014- body: |2015-2016- Returns a list of all builtin functions in the format `name/arity`.2017- Since functions with the same name but different arities are considered2018- separate functions, `all/0`, `all/1`, and `all/2` would all be present2019- in the list.2020-2021- - title: Conditionals and Comparisons2022- entries:2023- - title: "`==`, `!=`"2024- body: |2025-2026- The expression 'a == b' will produce 'true' if the result of a and b2027- are equal (that is, if they represent equivalent JSON documents) and2028- 'false' otherwise. In particular, strings are never considered equal2029- to numbers. If you're coming from Javascript, jq's == is like2030- Javascript's === - considering values equal only when they have the2031- same type as well as the same value.2032-2033- != is "not equal", and 'a != b' returns the opposite value of 'a == b'2034-2035- examples:2036- - program: '.[] == 1'2037- input: '[1, 1.0, "1", "banana"]'2038- output: ['true', 'true', 'false', 'false']2039-2040- - title: if-then-else2041- body: |2042-2043- `if A then B else C end` will act the same as `B` if `A`2044- produces a value other than false or null, but act the same2045- as `C` otherwise.2046-2047- `if A then B end` is the same as `if A then B else . end`.2048- That is, the `else` branch is optional, and if absent is the2049- same as `.`.2050-2051- Checking for false or null is a simpler notion of2052- "truthiness" than is found in Javascript or Python, but it2053- means that you'll sometimes have to be more explicit about2054- the condition you want. You can't test whether, e.g. a2055- string is empty using `if .name then A else B end`, you'll2056- need something more like `if .name then A else B end` instead.2057-2058- If the condition `A` produces multiple results, then `B` is evaluated2059- once for each result that is not false or null, and `C` is evaluated2060- once for each false or null.2061-2062- More cases can be added to an if using `elif A then B` syntax.2063-2064- examples:2065- - program: 'if . == 0 then2066- "zero"2067- elif . == 1 then2068- "one"2069- else2070- "many"2071- end'2072- input: 22073- output: ['"many"']2074-2075- - title: "`>, >=, <=, <`"2076- body: |2077-2078- The comparison operators `>`, `>=`, `<=`, `<` return whether2079- their left argument is greater than, greater than or equal2080- to, less than or equal to or less than their right argument2081- (respectively).2082-2083- The ordering is the same as that described for `sort`, above.2084-2085- examples:2086- - program: '. < 5'2087- input: 22088- output: ['true']2089-2090- - title: and/or/not2091- body: |2092-2093- jq supports the normal Boolean operators and/or/not. They have the2094- same standard of truth as if expressions - false and null are2095- considered "false values", and anything else is a "true value".2096-2097- If an operand of one of these operators produces multiple2098- results, the operator itself will produce a result for each input.2099-2100- `not` is in fact a builtin function rather than an operator,2101- so it is called as a filter to which things can be piped2102- rather than with special syntax, as in `.foo and .bar |2103- not`.2104-2105- These three only produce the values "true" and "false", and2106- so are only useful for genuine Boolean operations, rather2107- than the common Perl/Python/Ruby idiom of2108- "value_that_may_be_null or default". If you want to use this2109- form of "or", picking between two values rather than2110- evaluating a condition, see the "//" operator below.2111-2112- examples:2113- - program: '42 and "a string"'2114- input: 'null'2115- output: ['true']2116- - program: '(true, false) or false'2117- input: 'null'2118- output: ['true', 'false']2119-# - program: '(true, false) and (true, false)'2120-# input: 'null'2121-# output: ['true', 'false', 'false', 'false']2122- - program: '(true, true) and (true, false)'2123- input: 'null'2124- output: ['true', 'false', 'true', 'false']2125- - program: '[true, false | not]'2126- input: 'null'2127- output: ['[false, true]']2128-2129- - title: "Alternative operator: `//`"2130- body: |2131-2132- A filter of the form `a // b` produces the same2133- results as `a`, if `a` produces results other than `false`2134- and `null`. Otherwise, `a // b` produces the same results as `b`.2135-2136- This is useful for providing defaults: `.foo // 1` will2137- evaluate to `1` if there's no `.foo` element in the2138- input. It's similar to how `or` is sometimes used in Python2139- (jq's `or` operator is reserved for strictly Boolean2140- operations).2141-2142- examples:2143- - program: '.foo // 42'2144- input: '{"foo": 19}'2145- output: [19]2146- - program: '.foo // 42'2147- input: '{}'2148- output: [42]2149-2150- - title: try-catch2151- body: |2152-2153- Errors can be caught by using `try EXP catch EXP`. The first2154- expression is executed, and if it fails then the second is2155- executed with the error message. The output of the handler,2156- if any, is output as if it had been the output of the2157- expression to try.2158-2159- The `try EXP` form uses `empty` as the exception handler.2160-2161- examples:2162- - program: 'try .a catch ". is not an object"'2163- input: 'true'2164- output: ['". is not an object"']2165- - program: '[.[]|try .a]'2166- input: '[{}, true, {"a":1}]'2167- output: ['[null, 1]']2168- - program: 'try error("some exception") catch .'2169- input: 'true'2170- output: ['"some exception"']2171-2172- - title: Breaking out of control structures2173- body: |2174-2175- A convenient use of try/catch is to break out of control2176- structures like `reduce`, `foreach`, `while`, and so on.2177-2178- For example:2179-2180- # Repeat an expression until it raises "break" as an2181- # error, then stop repeating without re-raising the error.2182- # But if the error caught is not "break" then re-raise it.2183- try repeat(exp) catch .=="break" then empty else error;2184-2185- jq has a syntax for named lexical labels to "break" or "go (back) to":2186-2187- label $out | ... break $out ...2188-2189- The `break $label_name` expression will cause the program to2190- to act as though the nearest (to the left) `label $label_name`2191- produced `empty`.2192-2193- The relationship between the `break` and corresponding `label`2194- is lexical: the label has to be "visible" from the break.2195-2196- To break out of a `reduce`, for example:2197-2198- label $out | reduce .[] as $item (null; if .==false then break $out else ... end)2199-2200- The following jq program produces a syntax error:2201-2202- break $out2203-2204- because no label `$out` is visible.2205-2206- - title: "Error Suppression / Optional Operator: `?`"2207- body: |2208-2209- The `?` operator, used as `EXP?`, is shorthand for `try EXP`.2210-2211- examples:2212- - program: '[.[]|(.a)?]'2213- input: '[{}, true, {"a":1}]'2214- output: ['[null, 1]']2215-2216-2217- - title: Regular expressions (PCRE)2218- body: |2219-2220- jq uses the Oniguruma regular expression library, as do php,2221- ruby, TextMate, Sublime Text, etc, so the description here2222- will focus on jq specifics.2223-2224- The jq regex filters are defined so that they can be used using2225- one of these patterns:2226-2227- STRING | FILTER( REGEX )2228- STRING | FILTER( REGEX; FLAGS )2229- STRING | FILTER( [REGEX] )2230- STRING | FILTER( [REGEX, FLAGS] )2231-2232- where:2233- * STRING, REGEX and FLAGS are jq strings and subject to jq string interpolation;2234- * REGEX, after string interpolation, should be a valid PCRE regex;2235- * FILTER is one of `test`, `match`, or `capture`, as described below.2236-2237- FLAGS is a string consisting of one of more of the supported flags:2238-2239- * `g` - Global search (find all matches, not just the first)2240- * `i` - Case insensitive search2241- * `m` - Multi line mode ('.' will match newlines)2242- * `n` - Ignore empty matches2243- * `p` - Both s and m modes are enabled2244- * `s` - Single line mode ('^' -> '\A', '$' -> '\Z')2245- * `l` - Find longest possible matches2246- * `x` - Extended regex format (ignore whitespace and comments)2247-2248- To match whitespace in an x pattern use an escape such as \s, e.g.2249-2250- * test( "a\\sb", "x" ).2251-2252- Note that certain flags may also be specified within REGEX, e.g.2253-2254- * jq -n '("test", "TEst", "teST", "TEST") | test( "(?i)te(?-i)st" )'2255-2256- evaluates to: true, true, false, false.2257-2258- entries:2259- - title: "`test(val)`, `test(regex; flags)`"2260- body: |2261-2262- Like `match`, but does not return match objects, only `true` or `false`2263- for whether or not the regex matches the input.2264-2265- examples:2266- - program: 'test("foo")'2267- input: '"foo"'2268- output: ['true']2269- - program: '.[] | test("a b c # spaces are ignored"; "ix")'2270- input: '["xabcd", "ABC"]'2271- output: ['true', 'true']2272-2273- - title: "`match(val)`, `match(regex; flags)`"2274- body: |2275-2276- **match** outputs an object for each match it finds. Matches have2277- the following fields:2278-2279- * `offset` - offset in UTF-8 codepoints from the beginning of the input2280- * `length` - length in UTF-8 codepoints of the match2281- * `string` - the string that it matched2282- * `captures` - an array of objects representing capturing groups.2283-2284- Capturing group objects have the following fields:2285-2286- * `offset` - offset in UTF-8 codepoints from the beginning of the input2287- * `length` - length in UTF-8 codepoints of this capturing group2288- * `string` - the string that was captured2289- * `name` - the name of the capturing group (or `null` if it was unnamed)2290-2291- Capturing groups that did not match anything return an offset of -12292-2293- examples:2294- - program: 'match("(abc)+"; "g")'2295- input: '"abc abc"'2296- output:2297- - '{"offset": 0, "length": 3, "string": "abc", "captures": [{"offset": 0, "length": 3, "string": "abc", "name": null}]}'2298- - '{"offset": 4, "length": 3, "string": "abc", "captures": [{"offset": 4, "length": 3, "string": "abc", "name": null}]}'2299- - program: 'match("foo")'2300- input: '"foo bar foo"'2301- output: ['{"offset": 0, "length": 3, "string": "foo", "captures": []}']2302- - program: 'match(["foo", "ig"])'2303- input: '"foo bar FOO"'2304- output:2305- - '{"offset": 0, "length": 3, "string": "foo", "captures": []}'2306- - '{"offset": 8, "length": 3, "string": "FOO", "captures": []}'2307- - program: 'match("foo (?<bar123>bar)? foo"; "ig")'2308- input: '"foo bar foo foo foo"'2309- output:2310- - '{"offset": 0, "length": 11, "string": "foo bar foo", "captures": [{"offset": 4, "length": 3, "string": "bar", "name": "bar123"}]}'2311- - '{"offset": 12, "length": 8, "string": "foo foo", "captures": [{"offset": -1, "length": 0, "string": null, "name": "bar123"}]}'2312-2313- - program: '[ match("."; "g")] | length'2314- input: '"abc"'2315- output: [3]2316-2317-2318- - title: "`capture(val)`, `capture(regex; flags)`"2319- body: |2320-2321- Collects the named captures in a JSON object, with the name2322- of each capture as the key, and the matched string as the2323- corresponding value.2324-2325- examples:2326- - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2327- input: '"xyzzy-14"'2328- output: ['{ "a": "xyzzy", "n": "14" }']2329-2330- - title: "`scan(regex)`, `scan(regex; flags)`"2331- body: |2332-2333- Emit a stream of the non-overlapping substrings of the input2334- that match the regex in accordance with the flags, if any2335- have been specified. If there is no match, the stream is empty.2336- To capture all the matches for each input string, use the idiom2337- `[ expr ]`, e.g. `[ scan(regex) ]`.2338-2339- example:2340- - program: 'scan("c")'2341- input: '"abcdefabc"'2342- output: ['"c"', '"c"']2343-2344- - program: 'scan("b")'2345- input: ("", "")2346- output: ['[]', '[]']2347-2348- - title: "`split(regex; flags)`"2349- body: |2350-2351- For backwards compatibility, `split` splits on a string, not a regex.2352-2353- example:2354- - program: 'split(", *"; null)'2355- input: '"ab,cd, ef"'2356- output: ['"ab","cd","ef"']2357-2358-2359- - title: "`splits(regex)`, `splits(regex; flags)`"2360- body: |2361-2362- These provide the same results as their `split` counterparts,2363- but as a stream instead of an array.2364-2365- example:2366- - program: 'splits(", *")'2367- input: '("ab,cd", "ef, gh")'2368- output: ['"ab"', '"cd"', '"ef"', '"gh"']2369-2370- - title: "`sub(regex; tostring)` `sub(regex; string; flags)`"2371- body: |2372-2373- Emit the string obtained by replacing the first match of regex in the2374- input string with `tostring`, after interpolation. `tostring` should2375- be a jq string, and may contain references to named captures. The2376- named captures are, in effect, presented as a JSON object (as2377- constructed by `capture`) to `tostring`, so a reference to a captured2378- variable named "x" would take the form: "\(.x)".2379-2380- example:2381- - program: 'sub("^[^a-z]*(?<x>[a-z]*).*")'2382- input: '"123abc456"'2383- output: '"ZabcZabc"'2384-2385-2386- - title: "`gsub(regex; string)`, `gsub(regex; string; flags)`"2387- body: |2388-2389- `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2390- replaced by the string, after interpolation.2391-2392- example:2393- - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2394- input: '"Abcabc"'2395- output: '"+A-+a-"'2396-2397-2398- - title: Advanced features2399- body: |2400- Variables are an absolute necessity in most programming languages, but2401- they're relegated to an "advanced feature" in jq.2402-2403- In most languages, variables are the only means of passing around2404- data. If you calculate a value, and you want to use it more than once,2405- you'll need to store it in a variable. To pass a value to another part2406- of the program, you'll need that part of the program to define a2407- variable (as a function parameter, object member, or whatever) in2408- which to place the data.2409-2410- It is also possible to define functions in jq, although this is2411- is a feature whose biggest use is defining jq's standard library2412- (many jq functions such as `map` and `find` are in fact written2413- in jq).2414-2415- jq has reduction operators, which are very powerful but a bit2416- tricky. Again, these are mostly used internally, to define some2417- useful bits of jq's standard library.2418-2419- It may not be obvious at first, but jq is all about generators2420- (yes, as often found in other languages). Some utilities are2421- provided to help deal with generators.2422-2423- Some minimal I/O support (besides reading JSON from standard2424- input, and writing JSON to standard output) is available.2425-2426- Finally, there is a module/library system.2427-2428- entries:2429- - title: "Variable / Symbolic Binding Operator: `... as $identifier | ...`"2430- body: |2431-2432- In jq, all filters have an input and an output, so manual2433- plumbing is not necessary to pass a value from one part of a program2434- to the next. Many expressions, for instance `a + b`, pass their input2435- to two distinct subexpressions (here `a` and `b` are both passed the2436- same input), so variables aren't usually necessary in order to use a2437- value twice.2438-2439- For instance, calculating the average value of an array of numbers2440- requires a few variables in most languages - at least one to hold the2441- array, perhaps one for each element or for a loop counter. In jq, it's2442- simply `add / length` - the `add` expression is given the array and2443- produces its sum, and the `length` expression is given the array and2444- produces its length.2445-2446- So, there's generally a cleaner way to solve most problems in jq than2447- defining variables. Still, sometimes they do make things easier, so jq2448- lets you define variables using `expression as $variable`. All2449- variable names start with `$`. Here's a slightly uglier version of the2450- array-averaging example:2451-2452- length as $array_length | add / $array_length2453-2454- We'll need a more complicated problem to find a situation where using2455- variables actually makes our lives easier.2456-2457-2458- Suppose we have an array of blog posts, with "author" and "title"2459- fields, and another object which is used to map author usernames to2460- real names. Our input looks like:2461-2462- {"posts": [{"title": "Frist psot", "author": "anon"},2463- {"title": "A well-written article", "author": "person1"}],2464- "realnames": {"anon": "Anonymous Coward",2465- "person1": "Person McPherson"}}2466-2467- We want to produce the posts with the author field containing a real2468- name, as in:2469-2470- {"title": "Frist psot", "author": "Anonymous Coward"}2471- {"title": "A well-written article", "author": "Person McPherson"}2472-2473- We use a variable, $names, to store the realnames object, so that we2474- can refer to it later when looking up author usernames:2475-2476- .realnames as $names | .posts[] | {title, author: $names[.author]}2477-2478- The expression `exp as $x | ...` means: for each value of expression2479- `exp`, run the rest of the pipeline with the entire original input, and2480- with `$x` set to that value. Thus `as` functions as something of a2481- foreach loop.2482-2483- Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2484- `{$foo}` is a handy way of writing `{foo:$foo}`.2485-2486- Multiple variables may be declared using a single `as` expression by2487- providing a pattern that matches the structure of the input2488- (this is known as "destructuring"):2489-2490- . as {realnames: $names, posts: [$first, $second]} | ...2491-2492- The variable declarations in array patterns (e.g., `. as2493- [$first, $second]`) bind to the elements of the array in from2494- the element at index zero on up, in order. When there is no2495- value at the index for an array pattern element, `null` is2496- bound to that variable.2497-2498- Variables are scoped over the rest of the expression that defines2499- them, so2500-2501- .realnames as $names | (.posts[] | {title, author: $names[.author]})2502-2503- will work, but2504-2505- (.realnames as $names | .posts[]) | {title, author: $names[.author]}2506-2507- won't.2508-2509- For programming language theorists, it's more accurate to2510- say that jq variables are lexically-scoped bindings. In2511- particular there's no way to change the value of a binding;2512- one can only setup a new binding with the same name, but which2513- will not be visible where the old one was.2514-2515- examples:2516- - program: '.bar as $x | .foo | . + $x'2517- input: '{"foo":10, "bar":200}'2518- output: ['210']2519- - program: '. as $i|[(.*2|. as $i| $i), $i]'2520- input: '5'2521- output: ['[10,5]']2522- - program: '. as [$a, $b, {c: $c}] | $a + $b + $c'2523- input: '[2, 3, {"c": 4, "d": 5}]'2524- output: ['9']2525- - program: '.[] as [$a, $b] | {a: $a, b: $b}'2526- input: '[[0], [0, 1], [2, 1, 0]]'2527- output: ['{"a":0,"b":null}', '{"a":0,"b":1}', '{"a":2,"b":1}']2528-2529- - title: 'Destructuring Alternative Operator: `?//`'2530- body: |2531- 2532- The destructuring alternative operator provides a concise mechanism2533- for destructuring an input that can take one of several forms.2534-2535- Suppose we have an API that returns a list of resources and events2536- associated with them, and we want to get the user_id and timestamp of2537- the first event for each resource. The API (having been clumsily2538- converted from XML) will only wrap the events in an array if the resource2539- has multiple events:2540- 2541- {"resources": [{"id": 1, "kind": "widget", "events": {"action": "create", "user_id": 1, "ts": 13}},2542- {"id": 2, "kind": "widget", "events": [{"action": "create", "user_id": 1, "ts": 14}, {"action": "destroy", "user_id": 1, "ts": 15}]}]}2543- 2544- We can use the destructuring alternative operator to handle this structural change simply:2545-2546- .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$user_id, $ts}]} | {$user_id, $kind, $id, $ts}2547-2548- Or, if we aren't sure if the input is an array of values or an object:2549-2550- .[] as [$id, $kind, $user_id, $ts] ?// {$id, $kind, $user_id, $ts} | ...2551-2552- Each alternative need not define all of the same variables, but all named2553- variables will be available to the subsequent expression. Variables not2554- matched in the alternative that succeeded will be `null`:2555-2556- .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$first_user_id, $first_ts}]} | {$user_id, $first_user_id, $kind, $id, $ts, $first_ts}2557-2558- Additionally, if the subsequent expression returns an error, the2559- alternative operator will attempt to try the next binding. Errors2560- that occur during the final alternative are passed through.2561-2562- [[3]] | .[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end2563-2564- examples:2565- - program: '.[] as {$a, $b, c: {$d, $e}} ?// {$a, $b, c: [{$d, $e}]} | {$a, $b, $d, $e}'2566- input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2567- output: ['{"a":1,"b":2,"d":3,"e":4}', '{"a":1,"b":2,"d":3,"e":4}']2568- - program: '.[] as {$a, $b, c: {$d}} ?// {$a, $b, c: [{$e}]} | {$a, $b, $d, $e}'2569- input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2570- output: ['{"a":1,"b":2,"d":3,"e":null}', '{"a":1,"b":2,"d":null,"e":4}']2571- - program: '.[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end'2572- input: '[[3]]'2573- output: ['{"a":null,"b":3}']2574-2575- - title: 'Defining Functions'2576- body: |2577-2578- You can give a filter a name using "def" syntax:2579-2580- def increment: . + 1;2581-2582- From then on, `increment` is usable as a filter just like a2583- builtin function (in fact, this is how many of the builtins2584- are defined). A function may take arguments:2585-2586- def map(f): [.[] | f];2587-2588- Arguments are passed as _filters_ (functions with no2589- arguments), _not_ as values. The same argument may be2590- referenced multiple times with different inputs (here `f` is2591- run for each element of the input array). Arguments to a2592- function work more like callbacks than like value arguments.2593- This is important to understand. Consider:2594-2595- def foo(f): f|f;2596- 5|foo(.*2)2597-2598- The result will be 20 because `f` is `.*2`, and during the2599- first invocation of `f` `.` will be 5, and the second time it2600- will be 10 (5 * 2), so the result will be 20. Function2601- arguments are filters, and filters expect an input when2602- invoked.2603-2604- If you want the value-argument behaviour for defining simple2605- functions, you can just use a variable:2606-2607- def addvalue(f): f as $f | map(. + $f);2608-2609- Or use the short-hand:2610-2611- def addvalue($f): ...;2612-2613- With either definition, `addvalue(.foo)` will add the current2614- input's `.foo` field to each element of the array. Do note2615- that calling `addvalue(.[])` will cause the `map(. + $f)` part2616- to be evaluated once per value in the value of `.` at the call2617- site.2618-2619- Multiple definitions using the same function name are allowed.2620- Each re-definition replaces the previous one for the same2621- number of function arguments, but only for references from2622- functions (or main program) subsequent to the re-definition.2623- See also the section below on scoping.2624-2625- examples:2626- - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'2627- input: '[[1,2],[10,20]]'2628- output: ['[[1,2,1], [10,20,10]]']2629- - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'2630- input: '[[1,2],[10,20]]'2631- output: ['[[1,2,1,2], [10,20,1,2]]']2632-2633- - title: 'Scoping'2634- body: |2635-2636- There are two types of symbols in jq: value bindings (a.k.a.,2637- "variables"), and functions. Both are scoped lexically,2638- with expressions being able to refer only to symbols that2639- have been defined "to the left" of them. The only exception2640- to this rule is that functions can refer to themselves so as2641- to be able to create recursive functions.2642-2643- For example, in the following expression there is a binding2644- which is visible "to the right" of it, `... | .*3 as2645- $times_three | [. + $times_three] | ...`, but not "to the2646- left". Consider this expression now, `... | (.*3 as2647- $times_three | [.+ $times_three]) | ...`: here the binding2648- `$times_three` is _not_ visible past the closing parenthesis.2649-2650- - title: Reduce2651- body: |2652-2653- The `reduce` syntax in jq allows you to combine all of the2654- results of an expression by accumulating them into a single2655- answer. As an example, we'll pass `[3,2,1]` to this expression:2656-2657- reduce .[] as $item (0; . + $item)2658-2659- For each result that `.[]` produces, `. + $item` is run to2660- accumulate a running total, starting from 0. In this2661- example, `.[]` produces the results 3, 2, and 1, so the2662- effect is similar to running something like this:2663-2664- 0 | (3 as $item | . + $item) |2665- (2 as $item | . + $item) |2666- (1 as $item | . + $item)2667-2668- examples:2669- - program: 'reduce .[] as $item (0; . + $item)'2670- input: '[10,2,5,3]'2671- output: ['20']2672-2673- - title: "`isempty(exp)`"2674- body: |2675-2676- Returns true if `exp` produces no outputs, false otherwise.2677-2678- examples:2679- - program: 'isempty(empty)'2680- input: 'null'2681- output: ['true']2682-2683- - title: "`limit(n; exp)`"2684- body: |2685-2686- The `limit` function extracts up to `n` outputs from `exp`.2687-2688- examples:2689- - program: '[limit(3;.[])]'2690- input: '[0,1,2,3,4,5,6,7,8,9]'2691- output: ['[0,1,2]']2692-2693- - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"2694- body: |2695-2696- The `first(expr)` and `last(expr)` functions extract the first2697- and last values from `expr`, respectively.2698-2699- The `nth(n; expr)` function extracts the nth value output by2700- `expr`. This can be defined as `def nth(n; expr):2701- last(limit(n + 1; expr));`. Note that `nth(n; expr)` doesn't2702- support negative values of `n`.2703-2704- examples:2705- - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'2706- input: '10'2707- output: ['[0,9,5]']2708-2709- - title: "`first`, `last`, `nth(n)`"2710- body: |2711-2712- The `first` and `last` functions extract the first2713- and last values from any array at `.`.2714-2715- The `nth(n)` function extracts the nth value of any array at `.`.2716-2717- examples:2718- - program: '[range(.)]|[first, last, nth(5)]'2719- input: '10'2720- output: ['[0,9,5]']2721-2722- - title: "`foreach`"2723- body: |2724-2725- The `foreach` syntax is similar to `reduce`, but intended to2726- allow the construction of `limit` and reducers that produce2727- intermediate results (see example).2728-2729- The form is `foreach EXP as $var (INIT; UPDATE; EXTRACT)`.2730- Like `reduce`, `INIT` is evaluated once to produce a state2731- value, then each output of `EXP` is bound to `$var`, `UPDATE`2732- is evaluated for each output of `EXP` with the current state2733- and with `$var` visible. Each value output by `UPDATE`2734- replaces the previous state. Finally, `EXTRACT` is evaluated2735- for each new state to extract an output of `foreach`.2736-2737- This is mostly useful only for constructing `reduce`- and2738- `limit`-like functions. But it is much more general, as it2739- allows for partial reductions (see the example below).2740-2741- examples:2742- - program: '[foreach .[] as $item2743- ([[],[]];2744- if $item == null then [[],.[0]] else [(.[0] + [$item]),[]] end;2745- if $item == null then .[1] else empty end)]'2746- input: '[1,2,3,4,null,"a","b",null]'2747- output: ['[[1,2,3,4],["a","b"]]']2748-2749- - title: Recursion2750- body: |2751-2752- As described above, `recurse` uses recursion, and any jq2753- function can be recursive. The `while` builtin is also2754- implemented in terms of recursion.2755-2756- Tail calls are optimized whenever the expression to the left of2757- the recursive call outputs its last value. In practice this2758- means that the expression to the left of the recursive call2759- should not produce more than one output for each input.2760-2761- For example:2762-2763- def recurse(f): def r: ., (f | select(. != null) | r); r;2764-2765- def while(cond; update):2766- def _while:2767- if cond then ., (update | _while) else empty end;2768- _while;2769-2770- def repeat(exp):2771- def _repeat:2772- exp, _repeat;2773- _repeat;2774-2775- - title: Generators and iterators2776- body: |2777-2778- Some jq operators and functions are actually generators in2779- that they can produce zero, one, or more values for each2780- input, just as one might expect in other programming2781- languages that have generators. For example, `.[]`2782- generates all the values in its input (which must be an2783- array or an object), `range(0; 10)` generates the integers2784- between 0 and 10, and so on.2785-2786- Even the comma operator is a generator, generating first the2787- values generated by the expression to the left of the comma,2788- then for each of those, the values generate by the2789- expression on the right of the comma.2790-2791- The `empty` builtin is the generator that produces zero2792- outputs. The `empty` builtin backtracks to the preceding2793- generator expression.2794-2795- All jq functions can be generators just by using builtin2796- generators. It is also possible to define new generators2797- using only recursion and the comma operator. If the2798- recursive call(s) is(are) "in tail position" then the2799- generator will be efficient. In the example below the2800- recursive call by `_range` to itself is in tail position.2801- The example shows off three advanced topics: tail recursion,2802- generator construction, and sub-functions.2803-2804- examples:2805- - program: 'def range(init; upto; by):2806- def _range:2807- if (by > 0 and . < upto) or (by < 0 and . > upto)2808- then ., ((.+by)|_range)2809- else . end;2810- if by == 0 then init else init|_range end |2811- select((by > 0 and . < upto) or (by < 0 and . > upto));2812- range(0; 10; 3)'2813- input: 'null'2814- output: ['0', '3', '6', '9']2815- - program: 'def while(cond; update):2816- def _while:2817- if cond then ., (update | _while) else empty end;2818- _while;2819- [while(.<100; .*2)]'2820- input: '1'2821- output: ['[1,2,4,8,16,32,64]']2822-2823- - title: 'Math'2824- body: |2825-2826- jq currently only has IEEE754 double-precision (64-bit) floating2827- point number support.2828-2829- Besides simple arithmetic operators such as `+`, jq also has most2830- standard math functions from the C math library. C math functions2831- that take a single input argument (e.g., `sin()`) are available as2832- zero-argument jq functions. C math functions that take two input2833- arguments (e.g., `pow()`) are available as two-argument jq2834- functions that ignore `.`. C math functions that take three input2835- arguments are available as three-argument jq functions that ignore2836- `.`.2837-2838- Availability of standard math functions depends on the2839- availability of the corresponding math functions in your operating2840- system and C math library. Unavailable math functions will be2841- defined but will raise an error.2842-2843- One-input C math functions: `acos` `acosh` `asin` `asinh` `atan`2844- `atanh` `cbrt` `ceil` `cos` `cosh` `erf` `erfc` `exp` `exp10`2845- `exp2` `expm1` `fabs` `floor` `gamma` `j0` `j1` `lgamma` `log`2846- `log10` `log1p` `log2` `logb` `nearbyint` `pow10` `rint` `round`2847- `significand` `sin` `sinh` `sqrt` `tan` `tanh` `tgamma` `trunc`2848- `y0` `y1`.2849-2850- Two-input C math functions: `atan2` `copysign` `drem` `fdim`2851- `fmax` `fmin` `fmod` `frexp` `hypot` `jn` `ldexp` `modf`2852- `nextafter` `nexttoward` `pow` `remainder` `scalb` `scalbln` `yn`.2853-2854- Three-input C math functions: `fma`.2855-2856- See your system's manual for more information on each of these.2857-2858- - title: 'I/O'2859- body: |2860-2861- At this time jq has minimal support for I/O, mostly in the2862- form of control over when inputs are read. Two builtins functions2863- are provided for this, `input` and `inputs`, that read from the2864- same sources (e.g., `stdin`, files named on the command-line) as2865- jq itself. These two builtins, and jq's own reading actions, can2866- be interleaved with each other.2867-2868- Two builtins provide minimal output capabilities, `debug`, and2869- `stderr`. (Recall that a jq program's output values are always2870- output as JSON texts on `stdout`.) The `debug` builtin can have2871- application-specific behavior, such as for executables that use2872- the libjq C API but aren't the jq executable itself. The `stderr`2873- builtin outputs its input in raw mode to stder with no additional2874- decoration, not even a newline.2875-2876- Most jq builtins are referentially transparent, and yield constant2877- and repeatable value streams when applied to constant inputs.2878- This is not true of I/O builtins.2879-2880- entries:2881- - title: "`input`"2882- body: |2883-2884- Outputs one new input.2885-2886- - title: "`inputs`"2887- body: |2888-2889- Outputs all remaining inputs, one by one.2890-2891- This is primarily useful for reductions over a program's2892- inputs.2893-2894- - title: "`debug`"2895- body: |2896-2897- Causes a debug message based on the input value to be2898- produced. The jq executable wraps the input value with2899- `["DEBUG:", <input-value>]` and prints that and a newline on2900- stderr, compactly. This may change in the future.2901-2902- - title: "`stderr`"2903- body: |2904-2905- Prints its input in raw and compact mode to stderr with no2906- additional decoration, not even a newline.2907-2908- - title: "`input_filename`"2909- body: |2910-2911- Returns the name of the file whose input is currently being2912- filtered. Note that this will not work well unless jq is2913- running in a UTF-8 locale.2914-2915- - title: "`input_line_number`"2916- body: |2917-2918- Returns the line number of the input currently being filtered.2919-2920- - title: 'Streaming'2921- body: |2922-2923- With the `--stream` option jq can parse input texts in a streaming2924- fashion, allowing jq programs to start processing large JSON texts2925- immediately rather than after the parse completes. If you have a2926- single JSON text that is 1GB in size, streaming it will allow you2927- to process it much more quickly.2928-2929- However, streaming isn't easy to deal with as the jq program will2930- have `[<path>, <leaf-value>]` (and a few other forms) as inputs.2931-2932- Several builtins are provided to make handling streams easier.2933-2934- The examples below use the streamed form of `[0,[1]]`, which is2935- `[[0],0],[[1,0],1],[[1,0]],[[1]]`.2936-2937- Streaming forms include `[<path>, <leaf-value>]` (to indicate any2938- scalar value, empty array, or empty object), and `[<path>]` (to2939- indicate the end of an array or object). Future versions of jq2940- run with `--stream` and `-seq` may output additional forms such as2941- `["error message"]` when an input text fails to parse.2942-2943- entries:2944- - title: "`truncate_stream(stream_expression)`"2945- body: |2946-2947- Consumes a number as input and truncates the corresponding2948- number of path elements from the left of the outputs of the2949- given streaming expression.2950-2951- examples:2952- - program: '[1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]'2953- input: '1'2954- output: ['[[[0],2],[[0]]]']2955-2956- - title: "`fromstream(stream_expression)`"2957- body: |2958-2959- Outputs values corresponding to the stream expression's2960- outputs.2961-2962- examples:2963- - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'2964- input: 'null'2965- output: ['[2]']2966-2967- - title: "`tostream`"2968- body: |2969-2970- The `tostream` builtin outputs the streamed form of its input.2971-2972- examples:2973- - program: '. as $dot|fromstream($dot|tostream)|.==$dot'2974- input: '[0,[1,{"a":1},{"b":2}]]'2975- output: ['true']2976-2977- - title: Assignment2978- body: |2979- Assignment works a little differently in jq than in most2980- programming languages. jq doesn't distinguish between references2981- to and copies of something - two objects or arrays are either2982- equal or not equal, without any further notion of being "the2983- same object" or "not the same object".2984-2985- If an object has two fields which are arrays, `.foo` and `.bar`,2986- and you append something to `.foo`, then `.bar` will not get2987- bigger, even if you've previously set `.bar = .foo`. If you're2988- used to programming in languages like Python, Java, Ruby,2989- Javascript, etc. then you can think of it as though jq does a full2990- deep copy of every object before it does the assignment (for2991- performance it doesn't actually do that, but that's the general2992- idea).2993-2994- This means that it's impossible to build circular values in jq2995- (such as an array whose first element is itself). This is quite2996- intentional, and ensures that anything a jq program can produce2997- can be represented in JSON.2998-2999- All the assignment operators in jq have path expressions on the3000- left-hand side (LHS). The right-hand side (RHS) provides values3001- to set to the paths named by the LHS path expressions.3002-3003- Values in jq are always immutable. Internally, assignment works3004- by using a reduction to compute new, replacement values for `.` that3005- have had all the desired assignments applied to `.`, then3006- outputting the modified value. This might be made clear by this3007- example: `{a:{b:{c:1}}} | (.a.b|=3), .`. This will output3008- `{"a":{"b":3}}` and `{"a":{"b":{"c":1}}}` because the last3009- sub-expression, `.`, sees the original value, not the modified3010- value.3011-3012- Most users will want to use modification assignment operators,3013- such as `|=` or `+=`, rather than `=`.3014-3015- Note that the LHS of assignment operators refers to a value in3016- `.`. Thus `$var.foo = 1` won't work as expected (`$var.foo` is3017- not a valid or useful path expression in `.`); use `$var | .foo =3018- 1` instead.3019-3020- Note too that `.a,.b=0` does not set `.a` and `.b`, but3021- `(.a,.b)=0` sets both.3022-3023- entries:3024- - title: "Update-assignment: `|=`"3025- body: |3026- This is the "update" operator '|='. It takes a filter on the3027- right-hand side and works out the new value for the property3028- of `.` being assigned to by running the old value through this3029- expression. For instance, (.foo, .bar) |= .+1 will build an3030- object with the "foo" field set to the input's "foo" plus 1,3031- and the "bar" field set to the input's "bar" plus 1.3032-3033- The left-hand side can be any general path expression; see `path()`.3034-3035- Note that the left-hand side of '|=' refers to a value in `.`.3036- Thus `$var.foo |= . + 1` won't work as expected (`$var.foo` is3037- not a valid or useful path expression in `.`); use `$var |3038- .foo |= . + 1` instead.3039-3040- If the right-hand side outputs no values (i.e., `empty`), then3041- the left-hand side path will be deleted, as with `del(path)`.3042-3043- If the right-hand side outputs multiple values, only the first3044- one will be used (COMPATIBILITY NOTE: in jq 1.5 and earlier3045- releases, it used to be that only the last one was used).3046-3047- examples:3048- - program: '(..|select(type=="boolean")) |= if . then 1 else 0 end'3049- input: '[true,false,[5,true,[true,[false]],false]]'3050- output: ['[1,0,[5,1,[1,[0]],0]]']3051-3052- - title: "Arithmetic update-assignment: `+=`, `-=`, `*=`, `/=`, `%=`, `//=`"3053- body: |3054-3055- jq has a few operators of the form `a op= b`, which are all3056- equivalent to `a |= . op b`. So, `+= 1` can be used to3057- increment values, being the same as `|= . + 1`.3058-3059- examples:3060- - program: .foo += 13061- input: '{"foo": 42}'3062- output: ['{"foo": 43}']3063-3064- - title: "Plain assignment: `=`"3065- body: |3066-3067- This is the plain assignment operator. Unlike the others, the3068- input to the right-hand-side (RHS) is the same as the input to3069- the left-hand-side (LHS) rather than the value at the LHS3070- path, and all values output by the RHS will be used (as shown3071- below).3072-3073- If the RHS of '=' produces multiple values, then for each such3074- value jq will set the paths on the left-hand side to the value3075- and then it will output the modified `.`. For example,3076- `(.a,.b)=range(2)` outputs `{"a":0,"b":0}`, then3077- `{"a":1,"b":1}`. The "update" assignment forms (see above) do3078- not do this.3079-3080- This example should show the difference between '=' and '|=':3081-3082- Provide input '{"a": {"b": 10}, "b": 20}' to the programs:3083-3084- .a = .b3085-3086- .a |= .b3087-3088- The former will set the "a" field of the input to the "b"3089- field of the input, and produce the output {"a": 20, "b": 20}.3090- The latter will set the "a" field of the input to the "a"3091- field's "b" field, producing {"a": 10, "b": 20}.3092-3093- Another example of the difference between '=' and '|=':3094-3095- null|(.a,.b)=range(3)3096-3097- outputs '{"a":0,"b":0}', '{"a":1,"b":1}', and '{"a":2,"b":2}',3098- while3099-3100- null|(.a,.b)|=range(3)3101-3102- outputs just '{"a":0,"b":0}'.3103-3104- - title: Complex assignments3105- body: |3106- Lots more things are allowed on the left-hand side of a jq assignment3107- than in most languages. We've already seen simple field accesses on3108- the left hand side, and it's no surprise that array accesses work just3109- as well:3110-3111- .posts[0].title = "JQ Manual"3112-3113- What may come as a surprise is that the expression on the left may3114- produce multiple results, referring to different points in the input3115- document:3116-3117- .posts[].comments |= . + ["this is great"]3118-3119- That example appends the string "this is great" to the "comments"3120- array of each post in the input (where the input is an object with a3121- field "posts" which is an array of posts).3122-3123- When jq encounters an assignment like 'a = b', it records the "path"3124- taken to select a part of the input document while executing a. This3125- path is then used to find which part of the input to change while3126- executing the assignment. Any filter may be used on the3127- left-hand side of an equals - whichever paths it selects from the3128- input will be where the assignment is performed.3129-3130- This is a very powerful operation. Suppose we wanted to add a comment3131- to blog posts, using the same "blog" input above. This time, we only3132- want to comment on the posts written by "stedolan". We can find those3133- posts using the "select" function described earlier:3134-3135- .posts[] | select(.author == "stedolan")3136-3137- The paths provided by this operation point to each of the posts that3138- "stedolan" wrote, and we can comment on each of them in the same way3139- that we did before:3140-3141- (.posts[] | select(.author == "stedolan") | .comments) |=3142- . + ["terrible."]3143-3144- - title: Modules3145- body: |3146-3147- jq has a library/module system. Modules are files whose names end3148- in `.jq`.3149-3150- Modules imported by a program are searched for in a default search3151- path (see below). The `import` and `include` directives allow the3152- importer to alter this path.3153-3154- Paths in the a search path are subject to various substitutions.3155-3156- For paths starting with "~/", the user's home directory is3157- substituted for "~".3158-3159- For paths starting with "$ORIGIN/", the path of the jq executable3160- is substituted for "$ORIGIN".3161-3162- For paths starting with "./" or paths that are ".", the path of3163- the including file is substituted for ".". For top-level programs3164- given on the command-line, the current directory is used.3165-3166- Import directives can optionally specify a search path to which3167- the default is appended.3168-3169- The default search path is the search path given to the `-L`3170- command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",3171- "$ORIGIN/../lib"]`.3172-3173- Null and empty string path elements terminate search path3174- processing.3175-3176- A dependency with relative path "foo/bar" would be searched for in3177- "foo/bar.jq" and "foo/bar/bar.jq" in the given search path. This3178- is intended to allow modules to be placed in a directory along3179- with, for example, version control files, README files, and so on,3180- but also to allow for single-file modules.3181-3182- Consecutive components with the same name are not allowed to avoid3183- ambiguities (e.g., "foo/foo").3184-3185- For example, with `-L$HOME/.jq` a module `foo` can be found in3186- `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.3187-3188- If "$HOME/.jq" is a file, it is sourced into the main program.3189-3190- entries:3191- - title: "`import RelativePathString as NAME [<metadata>];`"3192- body: |3193-3194- Imports a module found at the given path relative to a3195- directory in a search path. A ".jq" suffix will be added to3196- the relative path string. The module's symbols are prefixed3197- with "NAME::".3198-3199- The optional metadata must be a constant jq expression. It3200- should be an object with keys like "homepage" and so on. At3201- this time jq only uses the "search" key/value of the metadata.3202- The metadata is also made available to users via the3203- `modulemeta` builtin.3204-3205- The "search" key in the metadata, if present, should have a3206- string or array value (array of strings); this is the search3207- path to be prefixed to the top-level search path.3208-3209- - title: "`include RelativePathString [<metadata>];`"3210- body: |3211-3212- Imports a module found at the given path relative to a3213- directory in a search path as if it were included in place. A3214- ".jq" suffix will be added to the relative path string. The3215- module's symbols are imported into the caller's namespace as3216- if the module's content had been included directly.3217-3218- The optional metadata must be a constant jq expression. It3219- should be an object with keys like "homepage" and so on. At3220- this time jq only uses the "search" key/value of the metadata.3221- The metadata is also made available to users via the3222- `modulemeta` builtin.3223-3224- - title: "`import RelativePathString as $NAME [<metadata>];`"3225- body: |3226-3227- Imports a JSON file found at the given path relative to a3228- directory in a search path. A ".json" suffix will be added to3229- the relative path string. The file's data will be available3230- as `$NAME::NAME`.3231-3232- The optional metadata must be a constant jq expression. It3233- should be an object with keys like "homepage" and so on. At3234- this time jq only uses the "search" key/value of the metadata.3235- The metadata is also made available to users via the3236- `modulemeta` builtin.3237-3238- The "search" key in the metadata, if present, should have a3239- string or array value (array of strings); this is the search3240- path to be prefixed to the top-level search path.3241-3242- - title: "`module <metadata>;`"3243- body: |3244-3245- This directive is entirely optional. It's not required for3246- proper operation. It serves only the purpose of providing3247- metadata that can be read with the `modulemeta` builtin.3248-3249- The metadata must be a constant jq expression. It should be3250- an object with keys like "homepage". At this time jq doesn't3251- use this metadata, but it is made available to users via the3252- `modulemeta` builtin.3253-3254- - title: "`modulemeta`"3255- body: |3256-3257- Takes a module name as input and outputs the module's metadata3258- as an object, with the module's imports (including metadata)3259- as an array value for the "deps" key.3260-3261- Programs can use this to query a module's metadata, which they3262- could then use to, for example, search for, download, and3263- install missing dependencies.3264-3265- - title: Colors3266- body: |3267-3268- To configure alternative colors just set the `JQ_COLORS`3269- environment variable to colon-delimited list of partial terminal3270- escape sequences like `"1;31"`, in this order:3271-3272- - color for `null`3273- - color for `false`3274- - color for `true`3275- - color for numbers3276- - color for strings3277- - color for arrays3278- - color for objects3279-3280- The default color scheme is the same as setting3281- `"JQ_COLORS=1;30:0;39:0;39:0;39:0;32:1;39:1;39"`.3282-3283- This is not a manual for VT100/ANSI escapes. However, each of3284- these color specifications should consist of two numbers separated3285- by a semi-colon, where the first number is one of these:3286-3287- - 1 (bright)3288- - 2 (dim)3289- - 4 (underscore)3290- - 5 (blink)3291- - 7 (reverse)3292- - 8 (hidden)3293-3294- and the second is one of these:3295-3296- - 30 (black)3297- - 31 (red)3298- - 32 (green)3299- - 33 (yellow)3300- - 34 (blue)3301- - 35 (magenta)3302- - 36 (cyan)3303- - 37 (white)added:docs/content/download/default.yml+192 added
1+headline: Download jq2+body:3+4+ - text: |5+6+ jq is written in C and has no runtime dependencies, so it should be7+ possible to build it for nearly any platform. Prebuilt binaries are8+ available for Linux, OS X and Windows.9+10+ The binaries should just run, but on OS X and Linux you may need11+ to make them executable first using `chmod +x jq`.12+13+ jq is licensed under the MIT license. For all of the gory14+ details, read the file `COPYING` in the source distribution.15+16+17+ ### Linux18+19+ * jq 1.5 is in the official [Debian](https://packages.debian.org/jq) and20+ [Ubuntu](http://packages.ubuntu.com/jq) repositories. Install using21+ `sudo apt-get install jq`.22+23+ * jq 1.5 is in the official24+ [Fedora](http://pkgs.fedoraproject.org/cgit/jq.git/) repository.25+ Install using `sudo dnf install jq`.26+27+ * jq 1.4 is in the official [openSUSE](https://software.opensuse.org/package/jq)28+ repository. Install using `sudo zypper install jq`.29+30+ * jq 1.5 is in the official31+ [Arch](https://www.archlinux.org/packages/?sort=&q=jq&maintainer=&flagged=)32+ repository. Install using `sudo pacman -Sy jq`.33+34+ * jq 1.6 binaries for35+ [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64)36+ or37+ [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux32).38+39+ * jq 1.5 binaries for40+ [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64)41+ or42+ [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux32).43+44+ * jq 1.4 binaries for45+ [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-linux-x86_64)46+ or47+ [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-linux-x86).48+49+ * jq 1.3 binaries for50+ [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.3/jq-linux-x86_64)51+ or52+ [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.3/jq-linux-x86).53+54+ ### OS X55+56+ * Use [Homebrew](http://brew.sh/) to install jq 1.5 with57+ `brew install jq`.58+59+ * jq 1.6 binary for60+ [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-osx-amd64).61+62+ * jq 1.5 binary for63+ [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-osx-amd64).64+65+ * jq 1.4 binaries for66+ [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-osx-x86_64)67+ or68+ [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-osx-x86).69+70+ * jq 1.3 binaries for71+ [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.3/jq-osx-x86_64)72+ or73+ [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.3/jq-osx-x86).74+75+ ### FreeBSD76+77+ * `pkg install jq` as root installs a pre-built78+ [binary package](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/pkgng-intro.html).79+80+ * `make -C /usr/ports/textproc/jq install clean` as root installs the81+ [jq](https://www.freshports.org/textproc/jq/)82+ [port](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/ports-using.html)83+ from source.84+85+ ### Solaris86+87+ * `pkgutil -i jq` in [OpenCSW](https://www.opencsw.org/p/jq) for Solaris88+ 10+, Sparc and x86.89+90+ * jq 1.4 binaries for Solaris 1191+ [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-solaris11-64)92+ or93+ [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-solaris11-32).94+95+ ### Windows96+97+ * Use [Chocolatey NuGet](https://chocolatey.org/) to install jq 1.5 with98+ `chocolatey install jq`.99+100+ * jq 1.6 executables for101+ [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-win64.exe)102+ or103+ [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-win32.exe).104+105+ * jq 1.5 executables for106+ [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-win64.exe)107+ or108+ [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-win32.exe).109+110+ * jq 1.4 executables for111+ [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-win64.exe)112+ or113+ [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.4/jq-win32.exe).114+115+ * jq 1.3 executables for116+ [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.3/jq-win64.exe)117+ or118+ [32-bit](https://github.com/stedolan/jq/releases/download/jq-1.3/jq-win32.exe).119+120+ ### Checksums and signatures121+122+ SHA-256 checksums are provided for all release and pre-release binaries.123+ They can be found under124+ [sig/v1.x/sha256sum.txt](https://github.com/stedolan/jq/tree/master/sig).125+ The checksums for jq 1.6 are in126+ [sig/v1.6/sha256sum.txt](https://raw.githubusercontent.com/stedolan/jq/master/sig/v1.6/sha256sum.txt).127+ The checksums for jq 1.5 are in128+ [sig/v1.5/sha256sum.txt](https://raw.githubusercontent.com/stedolan/jq/master/sig/v1.5/sha256sum.txt).129+130+ Additionally, all binaries are signed by the131+ [jq Package Signing Key](https://raw.githubusercontent.com/stedolan/jq/master/sig/jq-release.key).132+ The signatures can be found under133+ [sig/v1.x/\*.asc](https://github.com/stedolan/jq/tree/master/sig).134+ The signatures for jq 1.6 are in135+ [sig/v1.5/\*.asc](https://github.com/stedolan/jq/tree/master/sig/v1.6).136+ The signatures for jq 1.5 are in137+ [sig/v1.5/\*.asc](https://github.com/stedolan/jq/tree/master/sig/v1.5).138+ You can use [GnuPG](https://gnupg.org/) to verify a signature by downloading139+ the signature and running `gpg --verify signature.asc`.140+141+ ### From source on Linux, OS X, Cygwin, and other POSIX-like operating systems142+143+ * [Source tarball for jq 1.6](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-1.6.tar.gz)144+ * [Source tarball for jq 1.5](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-1.5.tar.gz)145+146+ You can build it using the usual `./configure && make && sudo147+ make install` rigmarole.148+149+ If you're interested in using the lastest development version, try:150+151+ git clone https://github.com/stedolan/jq.git152+ cd jq153+ autoreconf -i154+ ./configure --disable-maintainer-mode155+ make156+ sudo make install157+158+ To build it from a git clone, you'll need to install a few159+ packages first:160+161+ * [GCC](https://gcc.gnu.org)162+ * [Make](https://www.gnu.org/software/make/)163+ * [Autotools](https://www.gnu.org/software/automake/)164+165+ For Linux systems, these will all be in your system's package166+ manager, and if you do development on the machine they're most167+ likely already installed.168+169+ On OS X, these are all included in Apple's command line tools, which can170+ be installed from [Xcode](https://developer.apple.com/xcode/). However,171+ you may find that you need a newer version of Bison than the one provided172+ by Apple. This can be found in [Homebrew](http://brew.sh) or173+ [MacPorts](https://macports.org/).174+175+ The `--disable-maintainer-mode` flag says to use the pre-generated lexer176+ and parser that come with the code. To compile the lexer and parser also177+ from source, leave out this flag. You will need to install178+ [Flex](http://flex.sourceforge.net/) and179+ [Bison](https://www.gnu.org/software/bison/).180+181+ #### Building the documentation182+183+ jq's documentation is compiled into static HTML using Python.184+ To build the docs, run `pipenv run python3 build_website.py` from185+ the docs/ subdirectory. To serve them locally, you can run186+ `python3 -m SimpleHTTPServer`. You'll need a few Python dependencies,187+ which can be installed by following the instructions in `docs/README.md`.188+189+ The man page is built by `make jq.1`, or just `make`, also from190+ the YAML docs, and you'll still need the Python dependencies to191+ build the manpage.192+deleted:docs/content/index/index.yml-73 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273headline: jq
blurb: |
jq is a lightweight and flexible command-line JSON processor.
body1: |
jq is like `sed` for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that `sed`, `awk`, `grep` and friends let you play with text.
body2: |
jq is written in portable C, and it has zero runtime dependencies. You can download a single binary, `scp` it to a far away machine of the same type, and expect it to work.
body3: |
jq can mangle the data format that you have into the one that you want with very little effort, and the program to do so is often shorter and simpler than you'd expect.
tail: |
Go read the [tutorial](/jq/tutorial/) for more, or the [manual](/jq/manual/) for *way* more.
Ask questions on [stackoverflow](https://stackoverflow.com/) using the [jq tag](https://stackoverflow.com/questions/tagged/jq), or on the [#jq](http://irc.lc/freenode/%23jq/) channel on [Freenode](https://webchat.freenode.net/).
news: - date: 1 November 2018 body: | jq 1.6 released. See installation options on the [download](/jq/download/) page, and the [release notes](https://github.com/stedolan/jq/releases/tag/jq-1.6) for details.
- date: 15 August 2015 body: |
jq 1.5 released, including new datetime, math, and regexp functions, try/catch syntax, array and object destructuring, a streaming parser, and a module system. See installation options on the [download](/jq/download/) page, and the [release notes](https://github.com/stedolan/jq/releases/tag/jq-1.5) for details.
- date: 26 July 2015 body: |
jq 1.5rc2 is available. Get it on the [releases](https://github.com/stedolan/jq/releases) page.
- date: 01 January 2015 body: |
jq 1.5rc1 is available. Get it on the [releases](https://github.com/stedolan/jq/releases) page.
- date: 09 June 2014 body: |
jq 1.4 (finally) released! Get it on the [download](/jq/download/) page.
- date: 19 May 2013 body: |
jq 1.3 released.
added:docs/content/manual/v1.3/manual.yml+1270 added
1+---2+headline: jq 1.3 Manual3+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 dividing the results.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+ By default, `jq` reads a stream of JSON objects (whitespace51+ separated) from `stdin`. One or more <files> may be specified, in52+ which case `jq` will read input from those instead.53+54+ The <options> are described in the [INVOKING JQ] section, they55+ mostly concern input and output formatting. The <filter> is written56+ in the jq language and specifies how to transform the input57+ document.58+59+ ## FILTERS60+61+manpage_epilogue: |62+ ## BUGS63+64+ Presumably. Report them or discuss them at:65+66+ https://github.com/stedolan/jq/issues67+68+ ## AUTHOR69+70+ Stephen Dolan `<mu@netsoc.tcd.ie>`71+72+sections:73+ - title: Invoking jq74+ body: |75+76+ jq filters run on a stream of JSON data. The input to jq is77+ parsed as a sequence of whitespace-separated JSON values which78+ are passed through the provided filter one at a time. The79+ output(s) of the filter are written to standard out, again as a80+ sequence of whitespace-separated JSON data.81+82+ You can affect how jq reads and writes its input and output83+ using some command-line options:84+85+ * `--slurp`/`-s`:86+87+ Instead of running the filter for each JSON object in the88+ input, read the entire input stream into a large array and run89+ the filter just once.90+91+ * `--raw-input`/`-R`:92+93+ Don't parse the input as JSON. Instead, each line of text is94+ passed to the filter as a string. If combined with `--slurp`,95+ then the entire input is passed to the filter as a single long96+ string.97+98+ * `--null-input`/`-n`:99+100+ Don't read any input at all! Instead, the filter is run once101+ using `null` as the input. This is useful when using jq as a102+ simple calculator or to construct JSON data from scratch.103+104+ * `--compact-output` / `-c`:105+106+ By default, jq pretty-prints JSON output. Using this option107+ will result in more compact output by instead putting each108+ JSON object on a single line.109+110+ * `--color-output` / `-C` and `--monochrome-output` / `-M`:111+112+ By default, jq outputs colored JSON if writing to a113+ terminal. You can force it to produce color even if writing to114+ a pipe or a file using `-C`, and disable color with `-M`.115+116+ * `--ascii-output` / `-a`:117+118+ jq usually outputs non-ASCII Unicode codepoints as UTF-8, even119+ if the input specified them as escape sequences (like120+ "\u03bc"). Using this option, you can force jq to produce pure121+ ASCII output with every non-ASCII character replaced with the122+ equivalent escape sequence.123+124+ * `--raw-output` / `-r`:125+126+ With this option, if the filter's result is a string then it127+ will be written directly to standard output rather than being128+ formatted as a JSON string with quotes. This can be useful for129+ making jq filters talk to non-JSON-based systems.130+131+ * `--arg name value`:132+133+ This option passes a value to the jq program as a predefined134+ variable. If you run jq with `--arg foo bar`, then `$foo` is135+ available in the program and has the value `"bar"`.136+137+ - title: Basic filters138+ entries:139+ - title: "`.`"140+ body: |141+142+ The absolute simplest (and least interesting) filter143+ is `.`. This is a filter that takes its input and144+ produces it unchanged as output.145+146+ Since jq by default pretty-prints all output, this trivial147+ program can be a useful way of formatting JSON output from,148+ say, `curl`.149+150+ examples:151+ - program: '.'152+ input: '"Hello, world!"'153+ output: ['"Hello, world!"']154+155+ - title: "`.foo`"156+ body: |157+158+ The simplest *useful* filter is .foo. When given a159+ JSON object (aka dictionary or hash) as input, it produces160+ the value at the key "foo", or null if there's none present.161+162+ examples:163+ - program: '.foo'164+ input: '{"foo": 42, "bar": "less interesting data"}'165+ output: [42]166+ - program: '.foo'167+ input: '{"notfoo": true, "alsonotfoo": false}'168+ output: ['null']169+170+ - title: "`.[foo]`, `.[2]`, `.[10:15]`"171+ body: |172+173+ You can also look up fields of an object using syntax like174+ `.["foo"]` (.foo above is a shorthand version of this). This175+ one works for arrays as well, if the key is an176+ integer. Arrays are zero-based (like javascript), so `.[2]`177+ returns the third element of the array.178+179+ The `.[10:15]` syntax can be used to return a subarray of an180+ array. The array returned by `.[10:15]` will be of length 5,181+ containing the elements from index 10 (inclusive) to index182+ 15 (exclusive). Either index may be negative (in which case183+ it counts backwards from the end of the array), or omitted184+ (in which case it refers to the start or end of the array).185+186+ examples:187+ - program: '.[0]'188+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'189+ output: ['{"name":"JSON", "good":true}']190+191+ - program: '.[2]'192+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'193+ output: ['null']194+195+ - program: '.[2:4]'196+ input: '["a","b","c","d","e"]'197+ output: ['["c", "d"]']198+199+ - program: '.[:3]'200+ input: '["a","b","c","d","e"]'201+ output: ['["a", "b", "c"]']202+203+ - program: '.[-2:]'204+ input: '["a","b","c","d","e"]'205+ output: ['["d", "e"]']206+207+ - title: "`.[]`"208+ body: |209+210+ If you use the `.[foo]` syntax, but omit the index211+ entirely, it will return *all* of the elements of an212+ array. Running `.[]` with the input `[1,2,3]` will produce the213+ numbers as three separate results, rather than as a single214+ array.215+216+ You can also use this on an object, and it will return all217+ the values of the object.218+219+ examples:220+ - program: '.[]'221+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'222+ output:223+ - '{"name":"JSON", "good":true}'224+ - '{"name":"XML", "good":false}'225+226+ - program: '.[]'227+ input: '[]'228+ output: []229+230+ - program: '.[]'231+ input: '{"a": 1, "b": 1}'232+ output: ['1', '1']233+234+ - title: "`,`"235+ body: |236+237+ If two filters are separated by a comma, then the238+ input will be fed into both and there will be multiple239+ outputs: first, all of the outputs produced by the left240+ expression, and then all of the outputs produced by the241+ right. For instance, filter `.foo, .bar`, produces242+ both the "foo" fields and "bar" fields as separate outputs.243+244+ examples:245+ - program: '.foo, .bar'246+ input: '{"foo": 42, "bar": "something else", "baz": true}'247+ output: ['42', '"something else"']248+249+ - program: ".user, .projects[]"250+ input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'251+ output: ['"stedolan"', '"jq"', '"wikiflow"']252+253+ - program: '.[4,2]'254+ input: '["a","b","c","d","e"]'255+ output: ['"e"', '"c"']256+257+ - title: "`|`"258+ body: |259+ The | operator combines two filters by feeding the output(s) of260+ the one on the left into the input of the one on the right. It's261+ pretty much the same as the Unix shell's pipe, if you're used to262+ that.263+264+ If the one on the left produces multiple results, the one on265+ the right will be run for each of those results. So, the266+ expression `.[] | .foo` retrieves the "foo" field of each267+ element of the input array.268+269+ examples:270+ - program: '.[] | .name'271+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'272+ output: ['"JSON"', '"XML"']273+274+ - title: Types and Values275+ body: |276+277+ jq supports the same set of datatypes as JSON - numbers,278+ strings, booleans, arrays, objects (which in JSON-speak are279+ hashes with only string keys), and "null".280+281+ Booleans, null, strings and numbers are written the same way as282+ in javascript. Just like everything else in jq, these simple283+ values take an input and produce an output - `42` is a valid jq284+ expression that takes an input, ignores it, and returns 42285+ instead.286+287+ entries:288+ - title: Array construction - `[]`289+ body: |290+291+ As in JSON, `[]` is used to construct arrays, as in292+ `[1,2,3]`. The elements of the arrays can be any jq293+ expression. All of the results produced by all of the294+ expressions are collected into one big array. You can use it295+ to construct an array out of a known quantity of values (as296+ in `[.foo, .bar, .baz]`) or to "collect" all the results of a297+ filter into an array (as in `[.items[].name]`)298+299+ Once you understand the "," operator, you can look at jq's array300+ syntax in a different light: the expression `[1,2,3]` is not using a301+ built-in syntax for comma-separated arrays, but is instead applying302+ the `[]` operator (collect results) to the expression 1,2,3 (which303+ produces three different results).304+305+ If you have a filter `X` that produces four results,306+ then the expression `[X]` will produce a single result, an307+ array of four elements.308+309+ examples:310+ - program: "[.user, .projects[]]"311+ input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'312+ output: ['["stedolan", "jq", "wikiflow"]']313+ - title: Objects - `{}`314+ body: |315+316+ Like JSON, `{}` is for constructing objects (aka317+ dictionaries or hashes), as in: `{"a": 42, "b": 17}`.318+319+ If the keys are "sensible" (all alphabetic characters), then320+ the quotes can be left off. The value can be any expression321+ (although you may need to wrap it in parentheses if it's a322+ complicated one), which gets applied to the {} expression's323+ input (remember, all filters have an input and an324+ output).325+326+ {foo: .bar}327+328+ will produce the JSON object `{"foo": 42}` if given the JSON329+ object `{"bar":42, "baz":43}`. You can use this to select330+ particular fields of an object: if the input is an object331+ with "user", "title", "id", and "content" fields and you332+ just want "user" and "title", you can write333+334+ {user: .user, title: .title}335+336+ Because that's so common, there's a shortcut syntax: `{user, title}`.337+338+ If one of the expressions produces multiple results,339+ multiple dictionaries will be produced. If the input's340+341+ {"user":"stedolan","titles":["JQ Primer", "More JQ"]}342+343+ then the expression344+345+ {user, title: .titles[]}346+347+ will produce two outputs:348+349+ {"user":"stedolan", "title": "JQ Primer"}350+ {"user":"stedolan", "title": "More JQ"}351+352+ Putting parentheses around the key means it will be evaluated as an353+ expression. With the same input as above,354+355+ {(.user): .titles}356+357+ produces358+359+ {"stedolan": ["JQ Primer", "More JQ"]}360+361+ examples:362+ - program: '{user, title: .titles[]}'363+ input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'364+ output:365+ - '{"user":"stedolan", "title": "JQ Primer"}'366+ - '{"user":"stedolan", "title": "More JQ"}'367+ - program: '{(.user): .titles}'368+ input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'369+ output: ['{"stedolan": ["JQ Primer", "More JQ"]}']370+371+ - title: Builtin operators and functions372+ body: |373+374+ Some jq operator (for instance, `+`) do different things375+ depending on the type of their arguments (arrays, numbers,376+ etc.). However, jq never does implicit type conversions. If you377+ try to add a string to an object you'll get an error message and378+ no result.379+380+ entries:381+ - title: Addition - `+`382+ body: |383+384+ The operator `+` takes two filters, applies them both385+ to the same input, and adds the results together. What386+ "adding" means depends on the types involved:387+388+ - **Numbers** are added by normal arithmetic.389+390+ - **Arrays** are added by being concatenated into a larger array.391+392+ - **Strings** are added by being joined into a larger string.393+394+ - **Objects** are added by merging, that is, inserting all395+ the key-value pairs from both objects into a single396+ combined object. If both objects contain a value for the397+ same key, the object on the right of the `+` wins.398+399+ `null` can be added to any value, and returns the other400+ value unchanged.401+402+ examples:403+ - program: '.a + 1'404+ input: '{"a": 7}'405+ output: ['8']406+ - program: '.a + .b'407+ input: '{"a": [1,2], "b": [3,4]}'408+ output: ['[1,2,3,4]']409+ - program: '.a + null'410+ input: '{"a": 1}'411+ output: ['1']412+ - program: '.a + 1'413+ input: '{}'414+ output: ['1']415+ - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'416+ input: 'null'417+ output: ['{"a": 42, "b": 2, "c": 3}']418+419+ - title: Subtraction - `-`420+ body: |421+422+ As well as normal arithmetic subtraction on numbers, the `-`423+ operator can be used on arrays to remove all occurences of424+ the second array's elements from the first array.425+426+ examples:427+ - program: '4 - .a'428+ input: '{"a":3}'429+ output: ['1']430+ - program: . - ["xml", "yaml"]431+ input: '["xml", "yaml", "json"]'432+ output: ['["json"]']433+434+ - title: Multiplication, division - `*` and `/`435+ body: |436+437+ These operators only work on numbers, and do the expected.438+439+ examples:440+ - program: '10 / . * 3'441+ input: 5442+ output: [6]443+444+ - title: '`length`'445+ body: |446+447+ The builtin function `length` gets the length of various448+ different types of value:449+450+ - The length of a **string** is the number of Unicode451+ codepoints it contains (which will be the same as its452+ JSON-encoded length in bytes if it's pure ASCII).453+454+ - The length of an **array** is the number of elements.455+456+ - The length of an **object** is the number of key-value pairs.457+458+ - The length of **null** is zero.459+460+ examples:461+ - program: '.[] | length'462+ input: '[[1,2], "string", {"a":2}, null]'463+ output: [2, 6, 1, 0]464+465+ - title: '`keys`'466+ body: |467+468+ The builtin function `keys`, when given an object, returns469+ its keys in an array.470+471+ The keys are sorted "alphabetically", by unicode codepoint472+ order. This is not an order that makes particular sense in473+ any particular language, but you can count on it being the474+ same for any two objects with the same set of keys,475+ regardless of locale settings.476+477+ When `keys` is given an array, it returns the valid indices478+ for that array: the integers from 0 to length-1.479+480+ examples:481+ - program: 'keys'482+ input: '{"abc": 1, "abcd": 2, "Foo": 3}'483+ output: ['["Foo", "abc", "abcd"]']484+ - program: 'keys'485+ input: '[42,3,35]'486+ output: ['[0,1,2]']487+488+ - title: '`has`'489+ body: |490+491+ The builtin function `has` returns whether the input object492+ has the given key, or the input array has an element at the493+ given index.494+495+ `has($key)` has the same effect as checking whether `$key`496+ is a member of the array returned by `keys`, although `has`497+ will be faster.498+499+ examples:500+ - program: 'map(has("foo"))'501+ input: '[{"foo": 42}, {}]'502+ output: ['[true, false]']503+ - program: 'map(has(2))'504+ input: '[[0,1], ["a","b","c"]]'505+ output: ['[false, true]']506+507+ - title: '`to_entries`, `from_entries`, `with_entries`'508+ body: |509+510+ These functions convert between an object and an array of511+ key-value pairs. If `to_entries` is passed an object, then512+ for each `k: v` entry in the input, the output array513+ includes `{"key": k, "value": v}`.514+515+ `from_entries` does the opposite conversion, and516+ `with_entries(foo)` is a shorthand for `to_entries |517+ map(foo) | from_entries`, useful for doing some operation to518+ all keys and values of an object.519+520+ examples:521+ - program: 'to_entries'522+ input: '{"a": 1, "b": 2}'523+ output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']524+ - program: 'from_entries'525+ input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'526+ output: ['{"a": 1, "b": 2}']527+ - program: 'with_entries(.key |= "KEY_" + .)'528+ input: '{"a": 1, "b": 2}'529+ output: ['{"KEY_a": 1, "KEY_b": 2}']530+531+532+ - title: '`select`'533+ body: |534+535+ The function `select(foo)` produces its input unchanged if536+ `foo` returns true for that input, and produces no output537+ otherwise.538+539+ It's useful for filtering lists: '`[1,2,3] | map(select(. >= 2))`'540+ will give you `[3]`.541+542+ examples:543+ - program: 'map(select(. >= 2))'544+ input: '[1,5,3,0,7]'545+ output: ['[5,3,7]']546+547+ - title: '`empty`'548+ body: |549+550+ `empty` returns no results. None at all. Not even `null`.551+552+ It's useful on occasion. You'll know if you need it :)553+554+ examples:555+ - program: '1, empty, 2'556+ input: 'null'557+ output: [1, 2]558+ - program: '[1,2,empty,3]'559+ input: 'null'560+ output: ['[1,2,3]']561+562+ - title: '`map(x)`'563+ body: |564+565+ For any filter `x`, `map(x)` will run that filter for each566+ element of the input array, and produce the outputs a new567+ array. `map(.+1)` will increment each element of an array of numbers.568+569+ `map(x)` is equivalent to `[.[] | x]`. In fact, this is how570+ it's defined.571+572+ examples:573+ - program: 'map(.+1)'574+ input: '[1,2,3]'575+ output: ['[2,3,4]']576+577+ - title: '`add`'578+ body: |579+580+ The filter `add` takes as input an array, and produces as581+ output the elements of the array added together. This might582+ mean summed, concatenated or merged depending on the types583+ of the elements of the input array - the rules are the same584+ as those for the `+` operator (described above).585+586+ If the input is an empty array, `add` returns `null`.587+588+ examples:589+ - program: add590+ input: '["a","b","c"]'591+ output: ['"abc"']592+ - program: add593+ input: '[1, 2, 3]'594+ output: [6]595+ - program: add596+ input: '[]'597+ output: ["null"]598+599+ - title: '`range`'600+ body: |601+602+ The `range` function produces a range of numbers. `range(4;10)`603+ produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers604+ are produced as separate outputs. Use `[range(4;10)]` to get a range as605+ an array.606+607+ examples:608+ - program: 'range(2;4)'609+ input: 'null'610+ output: ['2', '3']611+ - program: '[range(2;4)]'612+ input: 'null'613+ output: ['[2,3]']614+615+ - title: '`tonumber`'616+ body: |617+618+ The `tonumber` function parses its input as a number. It619+ will convert correctly-formatted strings to their numeric620+ equivalent, leave numbers alone, and give an error on all other input.621+622+ examples:623+ - program: '.[] | tonumber'624+ input: '[1, "1"]'625+ output: [1, 1]626+627+ - title: '`tostring`'628+ body: |629+630+ The `tostring` function prints its input as a631+ string. Strings are left unchanged, and all other values are632+ JSON-encoded.633+634+ examples:635+ - program: '.[] | tostring'636+ input: '[1, "1", [1]]'637+ output: ['"1"', '"1"', '"[1]"']638+639+ - title: '`type`'640+ body: |641+642+ The `type` function returns the type of its argument as a643+ string, which is one of null, boolean, number, string, array644+ or object.645+646+ examples:647+ - program: 'map(type)'648+ input: '[0, false, [], {}, null, "hello"]'649+ output: ['["number", "boolean", "array", "object", "null", "string"]']650+651+ - title: '`sort, sort_by`'652+ body: |653+654+ The `sort` functions sorts its input, which must be an655+ array. Values are sorted in the following order:656+657+ * `null`658+ * `false`659+ * `true`660+ * numbers661+ * strings, in alphabetical order (by unicode codepoint value)662+ * arrays, in lexical order663+ * objects664+665+ The ordering for objects is a little complex: first they're666+ compared by comparing their sets of keys (as arrays in667+ sorted order), and if their keys are equal then the values668+ are compared key by key.669+670+ `sort_by` may be used to sort by a particular field of an671+ object, or by applying any jq filter. `sort_by(foo)`672+ compares two elements by comparing the result of `foo` on673+ each element.674+675+ examples:676+ - program: 'sort'677+ input: '[8,3,null,6]'678+ output: ['[null,3,6,8]']679+ - program: 'sort_by(.foo)'680+ input: '[{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}]'681+ output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']682+683+ - title: '`group_by`'684+ body: |685+686+ `group_by(.foo)` takes as input an array, groups the687+ elements having the same `.foo` field into separate arrays,688+ and produces all of these arrays as elements of a larger689+ array, sorted by the value of the `.foo` field.690+691+ Any jq expression, not just a field access, may be used in692+ place of `.foo`. The sorting order is the same as described693+ in the `sort` function above.694+695+ examples:696+ - program: 'group_by(.foo)'697+ input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'698+ output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']699+700+ - title: '`min`, `max`, `min_by`, `max_by`'701+ body: |702+703+ Find the minimum or maximum element of the input array. The704+ `_by` versions allow you to specify a particular field or705+ property to examine, e.g. `min_by(.foo)` finds the object706+ with the smallest `foo` field.707+708+ examples:709+ - program: 'min'710+ input: '[5,4,2,7]'711+ output: ['2']712+ - program: 'max_by(.foo)'713+ input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'714+ output: ['{"foo":2, "bar":3}']715+716+ - title: '`unique`'717+ body: |718+719+ The `unique` function takes as input an array and produces720+ an array of the same elements, in sorted order, with721+ duplicates removed.722+723+ examples:724+ - program: 'unique'725+ input: '[1,2,5,3,5,3,1,3]'726+ output: ['[1,2,3,5]']727+728+ - title: '`reverse`'729+ body: |730+731+ This function reverses an array.732+733+ examples:734+ - program: 'reverse'735+ input: '[1,2,3,4]'736+ output: ['[4,3,2,1]']737+738+ - title: '`contains`'739+ body: |740+741+ The filter `contains(b)` will produce true if b is742+ completely contained within the input. A string B is743+ contained in a string A if B is a substring of A. An array B744+ is contained in an array A is all elements in B are745+ contained in any element in A. An object B is contained in746+ object A if all of the values in B are contained in the747+ value in A with the same key. All other types are assumed to748+ be contained in each other if they are equal.749+750+ examples:751+ - program: 'contains("bar")'752+ input: '"foobar"'753+ output: ['true']754+ - program: 'contains(["baz", "bar"])'755+ input: '["foobar", "foobaz", "blarp"]'756+ output: ['true']757+ - program: 'contains(["bazzzzz", "bar"])'758+ input: '["foobar", "foobaz", "blarp"]'759+ output: ['false']760+ - program: 'contains({foo: 12, bar: [{barp: 12}]})'761+ input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'762+ output: ['true']763+ - program: 'contains({foo: 12, bar: [{barp: 15}]})'764+ input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'765+ output: ['false']766+767+ - title: '`recurse`'768+ body: |769+770+ The `recurse` function allows you to search through a771+ recursive structure, and extract interesting data from all772+ levels. Suppose your input represents a filesystem:773+774+ {"name": "/", "children": [775+ {"name": "/bin", "children": [776+ {"name": "/bin/ls", "children": []},777+ {"name": "/bin/sh", "children": []}]},778+ {"name": "/home", "children": [779+ {"name": "/home/stephen", "children": [780+ {"name": "/home/stephen/jq", "children": []}]}]}]}781+782+ Now suppose you want to extract all of the filenames783+ present. You need to retrieve `.name`, `.children[].name`,784+ `.children[].children[].name`, and so on. You can do this785+ with:786+787+ recurse(.children[]) | .name788+789+ examples:790+ - program: 'recurse(.foo[])'791+ input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'792+ output:793+ - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'794+ - '{"foo":[]}'795+ - '{"foo":[{"foo":[]}]}'796+ - '{"foo":[]}'797+798+799+ - title: String interpolation - `\(foo)`800+ body: |801+802+ Inside a string, you can put an expression inside parens803+ after a backslash. Whatever the expression returns will be804+ interpolated into the string.805+806+ examples:807+ - program: '"The input was \(.), which is one less than \(.+1)"'808+ input: '42'809+ output: ['"The input was 42, which is one less than 43"']810+811+ - title: "Format strings and escaping"812+ body: |813+814+ The `@foo` syntax is used to format and escape strings,815+ which is useful for building URLs, documents in a language816+ like HTML or XML, and so forth. `@foo` can be used as a817+ filter on its own, the possible escapings are:818+819+ * `@text`:820+821+ Calls `tostring`, see that function for details.822+823+ * `@json`:824+825+ Serialises the input as JSON.826+827+ * `@html`:828+829+ Applies HTML/XML escaping, by mapping the characters830+ `<>&'"` to their entity equivalents `<`, `>`,831+ `&`, `'`, `"`.832+833+ * `@uri`:834+835+ Applies percent-encoding, by mapping all reserved URI836+ characters to a `%xx` sequence.837+838+ * `@csv`:839+840+ The input must be an array, and it is rendered as CSV841+ with double quotes for strings, and quotes escaped by842+ repetition.843+844+ * `@sh`:845+846+ The input is escaped suitable for use in a command-line847+ for a POSIX shell. If the input is an array, the output848+ will be a series of space-separated strings.849+850+ * `@base64`:851+852+ The input is converted to base64 as specified by RFC 4648.853+854+ This syntax can be combined with string interpolation in a855+ useful way. You can follow a `@foo` token with a string856+ literal. The contents of the string literal will *not* be857+ escaped. However, all interpolations made inside that string858+ literal will be escaped. For instance,859+860+ @uri "https://www.google.com/search?q=\(.search)"861+862+ will produce the following output for the input863+ `{"search":"jq!"}`:864+865+ https://www.google.com/search?q=jq%21866+867+ Note that the slashes, question mark, etc. in the URL are868+ not escaped, as they were part of the string literal.869+870+ examples:871+ - program: '@html'872+ input: '"This works if x < y"'873+ output: ['"This works if x < y"']874+875+# - program: '@html "<span>Anonymous said: \(.)</span>"'876+# input: '"<script>alert(\"lol hax\");</script>"'877+# output: ["<span>Anonymous said: <script>alert("lol hax");</script></span>"]878+879+ - program: '@sh "echo \(.)"'880+ input: "\"O'Hara's Ale\""881+ output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]882+883+ - title: Conditionals and Comparisons884+ entries:885+ - title: '`==`, `!=`'886+ body: |887+888+ The expression 'a == b' will produce 'true' if the result of a and b889+ are equal (that is, if they represent equivalent JSON documents) and890+ 'false' otherwise. In particular, strings are never considered equal891+ to numbers. If you're coming from Javascript, jq's == is like892+ Javascript's === - considering values equal only when they have the893+ same type as well as the same value.894+895+ != is "not equal", and 'a != b' returns the opposite value of 'a == b'896+897+ examples:898+ - program: '.[] == 1'899+ input: '[1, 1.0, "1", "banana"]'900+ output: ['true', 'true', 'false', 'false']901+ - title: if-then-else902+ body: |903+904+ `if A then B else C end` will act the same as `B` if `A`905+ produces a value other than false or null, but act the same906+ as `C` otherwise.907+908+ Checking for false or null is a simpler notion of909+ "truthiness" than is found in Javascript or Python, but it910+ means that you'll sometimes have to be more explicit about911+ the condition you want: you can't test whether, e.g. a912+ string is empty using `if .name then A else B end`, you'll913+ need something more like `if (.name | count) > 0 then A else914+ B end` instead.915+916+ If the condition `A` produces multiple results, then `B` is evaluated917+ once for each result that is not false or null, and `C` is evaluated918+ once for each false or null.919+920+ More cases can be added to an if using `elif A then B` syntax.921+922+ examples:923+ - program: |-924+ if . == 0 then925+ "zero"926+ elif . == 1 then927+ "one"928+ else929+ "many"930+ end931+ input: 2932+ output: ['"many"']933+934+ - title: '`>, >=, <=, <`'935+ body: |936+937+ The comparison operators `>`, `>=`, `<=`, `<` return whether938+ their left argument is greater than, greater than or equal939+ to, less than or equal to or less than their right argument940+ (respectively).941+942+ The ordering is the same as that described for `sort`, above.943+944+ examples:945+ - program: '. < 5'946+ input: 2947+ output: ['true']948+949+ - title: and/or/not950+ body: |951+952+ jq supports the normal Boolean operators and/or/not. They have the953+ same standard of truth as if expressions - false and null are954+ considered "false values", and anything else is a "true value".955+956+ If an operand of one of these operators produces multiple957+ results, the operator itself will produce a result for each input.958+959+ `not` is in fact a builtin function rather than an operator,960+ so it is called as a filter to which things can be piped961+ rather than with special syntax, as in `.foo and .bar |962+ not`.963+964+ These three only produce the values "true" and "false", and965+ so are only useful for genuine Boolean operations, rather966+ than the common Perl/Python/Ruby idiom of967+ "value_that_may_be_null or default". If you want to use this968+ form of "or", picking between two values rather than969+ evaluating a condition, see the "//" operator below.970+971+ examples:972+ - program: '42 and "a string"'973+ input: 'null'974+ output: ['true']975+ - program: '(true, false) or false'976+ input: 'null'977+ output: ['true', 'false']978+# - program: '(true, false) and (true, false)'979+# input: 'null'980+# output: ['true', 'false', 'false', 'false']981+ - program: '(true, true) and (true, false)'982+ input: 'null'983+ output: ['true', 'false', 'true', 'false']984+ - program: '[true, false | not]'985+ input: 'null'986+ output: ['[false, true]']987+988+ - title: Alternative operator - `//`989+ body: |990+991+ A filter of the form `a // b` produces the same992+ results as `a`, if `a` produces results other than `false`993+ and `null`. Otherwise, `a // b` produces the same results as `b`.994+995+ This is useful for providing defaults: `.foo // 1` will996+ evaluate to `1` if there's no `.foo` element in the997+ input. It's similar to how `or` is sometimes used in Python998+ (jq's `or` operator is reserved for strictly Boolean999+ operations).1000+1001+ examples:1002+ - program: '.foo // 42'1003+ input: '{"foo": 19}'1004+ output: [19]1005+ - program: '.foo // 42'1006+ input: '{}'1007+ output: [42]1008+1009+ - title: Advanced features1010+ body: |1011+ Variables are an absolute necessity in most programming languages, but1012+ they're relegated to an "advanced feature" in jq.1013+1014+ In most languages, variables are the only means of passing around1015+ data. If you calculate a value, and you want to use it more than once,1016+ you'll need to store it in a variable. To pass a value to another part1017+ of the program, you'll need that part of the program to define a1018+ variable (as a function parameter, object member, or whatever) in1019+ which to place the data.1020+1021+ It is also possible to define functions in jq, although this is1022+ is a feature whose biggest use is defining jq's standard library1023+ (many jq functions such as `map` and `find` are in fact written1024+ in jq).1025+1026+ Finally, jq has a `reduce` operation, which is very powerful but a1027+ bit tricky. Again, it's mostly used internally, to define some1028+ useful bits of jq's standard library.1029+1030+ entries:1031+ - title: Variables1032+ body: |1033+1034+ In jq, all filters have an input and an output, so manual1035+ plumbing is not necessary to pass a value from one part of a program1036+ to the next. Many expressions, for instance `a + b`, pass their input1037+ to two distinct subexpressions (here `a` and `b` are both passed the1038+ same input), so variables aren't usually necessary in order to use a1039+ value twice.1040+1041+ For instance, calculating the average value of an array of numbers1042+ requires a few variables in most languages - at least one to hold the1043+ array, perhaps one for each element or for a loop counter. In jq, it's1044+ simply `add / length` - the `add` expression is given the array and1045+ produces its sum, and the `length` expression is given the array and1046+ produces its length.1047+1048+ So, there's generally a cleaner way to solve most problems in jq that1049+ defining variables. Still, sometimes they do make things easier, so jq1050+ lets you define variables using `expression as $variable`. All1051+ variable names start with `$`. Here's a slightly uglier version of the1052+ array-averaging example:1053+1054+ length as $array_length | add / $array_length1055+1056+ We'll need a more complicated problem to find a situation where using1057+ variables actually makes our lives easier.1058+1059+1060+ Suppose we have an array of blog posts, with "author" and "title"1061+ fields, and another object which is used to map author usernames to1062+ real names. Our input looks like:1063+1064+ {"posts": [{"title": "Frist psot", "author": "anon"},1065+ {"title": "A well-written article", "author": "person1"}],1066+ "realnames": {"anon": "Anonymous Coward",1067+ "person1": "Person McPherson"}}1068+1069+ We want to produce the posts with the author field containing a real1070+ name, as in:1071+1072+ {"title": "Frist psot", "author": "Anonymous Coward"}1073+ {"title": "A well-written article", "author": "Person McPherson"}1074+1075+ We use a variable, $names, to store the realnames object, so that we1076+ can refer to it later when looking up author usernames:1077+1078+ .realnames as $names | .posts[] | {title, author: $names[.author]}1079+1080+ The expression `exp as $x | ...` means: for each value of expression1081+ `exp`, run the rest of the pipeline with the entire original input, and1082+ with `$x` set to that value. Thus `as` functions as something of a1083+ foreach loop.1084+1085+ Variables are scoped over the rest of the expression that defines1086+ them, so1087+1088+ .realnames as $names | (.posts[] | {title, author: $names[.author]})1089+1090+ will work, but1091+1092+ (.realnames as $names | .posts[]) | {title, author: $names[.author]}1093+1094+ won't.1095+1096+ examples:1097+ - program: '.bar as $x | .foo | . + $x'1098+ input: '{"foo":10, "bar":200}'1099+ output: ['210']1100+1101+ - title: 'Defining Functions'1102+ body: |1103+1104+ You can give a filter a name using "def" syntax:1105+1106+ def increment: . + 1;1107+1108+ From then on, `increment` is usable as a filter just like a1109+ builtin function (in fact, this is how some of the builtins1110+ are defined). A function may take arguments:1111+1112+ def map(f): [.[] | f];1113+1114+ Arguments are passed as filters, not as values. The1115+ same argument may be referenced multiple times with1116+ different inputs (here `f` is run for each element of the1117+ input array). Arguments to a function work more like1118+ callbacks than like value arguments.1119+1120+ If you want the value-argument behaviour for defining simple1121+ functions, you can just use a variable:1122+1123+ def addvalue(f): f as $value | map(. + $value);1124+1125+ With that definition, `addvalue(.foo)` will add the current1126+ input's `.foo` field to each element of the array.1127+1128+ examples:1129+ - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'1130+ input: '[[1,2],[10,20]]'1131+ output: ['[[1,2,1], [10,20,10]]']1132+ - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'1133+ input: '[[1,2],[10,20]]'1134+ output: ['[[1,2,1,2], [10,20,1,2]]']1135+1136+ - title: Reduce1137+ body: |1138+1139+ The `reduce` syntax in jq allows you to combine all of the1140+ results of an expression by accumulating them into a single1141+ answer. As an example, we'll pass `[3,2,1]` to this expression:1142+1143+ reduce .[] as $item (0; . + $item)1144+1145+ For each result that `.[]` produces, `. + $item` is run to1146+ accumulate a running total, starting from 0. In this1147+ example, `.[]` produces the results 3, 2, and 1, so the1148+ effect is similar to running something like this:1149+1150+ 0 | (3 as $item | . + $item) |1151+ (2 as $item | . + $item) |1152+ (1 as $item | . + $item)1153+1154+ examples:1155+ - program: 'reduce .[] as $item (0; . + $item)'1156+ input: '[10,2,5,3]'1157+ output: ['20']1158+1159+1160+ - title: Assignment1161+ body: |1162+1163+ Assignment works a little differently in jq than in most1164+ programming languages. jq doesn't distinguish between references1165+ to and copies of something - two objects or arrays are either1166+ equal or not equal, without any further notion of being "the1167+ same object" or "not the same object".1168+1169+ If an object has two fields which are arrays, `.foo` and `.bar`,1170+ and you append something to `.foo`, then `.bar` will not get1171+ bigger. Even if you've just set `.bar = .foo`. If you're used to1172+ programming in languages like Python, Java, Ruby, Javascript,1173+ etc. then you can think of it as though jq does a full deep copy1174+ of every object before it does the assignment (for performance,1175+ it doesn't actually do that, but that's the general idea).1176+1177+ entries:1178+ - title: "`=`"1179+ body: |1180+1181+ The filter `.foo = 1` will take as input an object1182+ and produce as output an object with the "foo" field set to1183+ 1. There is no notion of "modifying" or "changing" something1184+ in jq - all jq values are immutable. For instance,1185+1186+ .foo = .bar | .foo.baz = 11187+1188+ will not have the side-effect of setting .bar.baz to be set1189+ to 1, as the similar-looking program in Javascript, Python,1190+ Ruby or other languages would. Unlike these languages (but1191+ like Haskell and some other functional languages), there is1192+ no notion of two arrays or objects being "the same array" or1193+ "the same object". They can be equal, or not equal, but if1194+ we change one of them in no circumstances will the other1195+ change behind our backs.1196+1197+ This means that it's impossible to build circular values in1198+ jq (such as an array whose first element is itself). This is1199+ quite intentional, and ensures that anything a jq program1200+ can produce can be represented in JSON.1201+1202+ - title: "`|=`"1203+ body: |1204+ As well as the assignment operator '=', jq provides the "update"1205+ operator '|=', which takes a filter on the right-hand side and1206+ works out the new value for the property being assigned to by running1207+ the old value through this expression. For instance, .foo |= .+1 will1208+ build an object with the "foo" field set to the input's "foo" plus 1.1209+1210+ This example should show the difference between '=' and '|=':1211+1212+ Provide input '{"a": {"b": 10}, "b": 20}' to the programs:1213+1214+ .a = .b1215+ .a |= .b1216+1217+ The former will set the "a" field of the input to the "b" field of the1218+ input, and produce the output {"a": 20}. The latter will set the "a"1219+ field of the input to the "a" field's "b" field, producing {"a": 10}.1220+1221+ - title: "`+=`, `-=`, `*=`, `/=`, `//=`"1222+ body: |1223+1224+ jq has a few operators of the form `a op= b`, which are all1225+ equivalent to `a |= . op b`. So, `+= 1` can be used to increment values.1226+1227+ examples:1228+ - program: .foo += 11229+ input: '{"foo": 42}'1230+ output: ['{"foo": 43}']1231+1232+ - title: Complex assignments1233+ body: |1234+ Lots more things are allowed on the left-hand side of a jq assignment1235+ than in most langauges. We've already seen simple field accesses on1236+ the left hand side, and it's no surprise that array accesses work just1237+ as well:1238+1239+ .posts[0].title = "JQ Manual"1240+1241+ What may come as a surprise is that the expression on the left may1242+ produce multiple results, referring to different points in the input1243+ document:1244+1245+ .posts[].comments |= . + ["this is great"]1246+1247+ That example appends the string "this is great" to the "comments"1248+ array of each post in the input (where the input is an object with a1249+ field "posts" which is an array of posts).1250+1251+ When jq encounters an assignment like 'a = b', it records the "path"1252+ taken to select a part of the input document while executing a. This1253+ path is then used to find which part of the input to change while1254+ executing the assignment. Any filter may be used on the1255+ left-hand side of an equals - whichever paths it selects from the1256+ input will be where the assignment is performed.1257+1258+ This is a very powerful operation. Suppose we wanted to add a comment1259+ to blog posts, using the same "blog" input above. This time, we only1260+ want to comment on the posts written by "stedolan". We can find those1261+ posts using the "select" function described earlier:1262+1263+ .posts[] | select(.author == "stedolan")1264+1265+ The paths provided by this operation point to each of the posts that1266+ "stedolan" wrote, and we can comment on each of them in the same way1267+ that we did before:1268+1269+ (.posts[] | select(.author == "stedolan") | .comments) |=1270+ . + ["terrible."]added:docs/content/manual/v1.4/manual.yml+1672 added
1+---2+headline: jq 1.4 Manual3+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 dividing the results.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+ By default, `jq` reads a stream of JSON objects (whitespace51+ separated) from `stdin`. One or more <files> may be specified, in52+ which case `jq` will read input from those instead.53+54+ The <options> are described in the [INVOKING JQ] section, they55+ mostly concern input and output formatting. The <filter> is written56+ in the jq language and specifies how to transform the input57+ document.58+59+ ## FILTERS60+61+manpage_epilogue: |62+ ## BUGS63+64+ Presumably. Report them or discuss them at:65+66+ https://github.com/stedolan/jq/issues67+68+ ## AUTHOR69+70+ Stephen Dolan `<mu@netsoc.tcd.ie>`71+72+sections:73+ - title: Invoking jq74+ body: |75+76+ jq filters run on a stream of JSON data. The input to jq is77+ parsed as a sequence of whitespace-separated JSON values which78+ are passed through the provided filter one at a time. The79+ output(s) of the filter are written to standard out, again as a80+ sequence of whitespace-separated JSON data.81+82+ Note: it is important to mind the shell's quoting rules. As a83+ general rule it's best to always quote (with single-quote84+ characters) the jq program, as too many characters with special85+ meaning to jq are also shell meta-characters. For example, `jq86+ "foo"` will fail on most Unix shells because that will be the same87+ as `jq foo`, which will generally fail because `foo is not88+ defined`. When using the Windows command shell (cmd.exe) it's89+ best to use double quotes around your jq program when given on the90+ command-line (instead of the `-f program-file` option), but then91+ double-quotes in the jq program need backslash escaping.92+93+ You can affect how jq reads and writes its input and output94+ using some command-line options:95+96+ * `--version`:97+98+ Output the jq version and exit with zero.99+100+ * `--slurp`/`-s`:101+102+ Instead of running the filter for each JSON object in the103+ input, read the entire input stream into a large array and run104+ the filter just once.105+106+ * `--online-input`/`-I`:107+108+ When the top-level input value is an array produce its elements109+ instead of the array. This allows on-line processing of110+ potentially very large top-level arrays' elements.111+112+ * `--raw-input`/`-R`:113+114+ Don't parse the input as JSON. Instead, each line of text is115+ passed to the filter as a string. If combined with `--slurp`,116+ then the entire input is passed to the filter as a single long117+ string.118+119+ * `--null-input`/`-n`:120+121+ Don't read any input at all! Instead, the filter is run once122+ using `null` as the input. This is useful when using jq as a123+ simple calculator or to construct JSON data from scratch.124+125+ * `--compact-output` / `-c`:126+127+ By default, jq pretty-prints JSON output. Using this option128+ will result in more compact output by instead putting each129+ JSON object on a single line.130+131+ * `--color-output` / `-C` and `--monochrome-output` / `-M`:132+133+ By default, jq outputs colored JSON if writing to a134+ terminal. You can force it to produce color even if writing to135+ a pipe or a file using `-C`, and disable color with `-M`.136+137+ * `--ascii-output` / `-a`:138+139+ jq usually outputs non-ASCII Unicode codepoints as UTF-8, even140+ if the input specified them as escape sequences (like141+ "\u03bc"). Using this option, you can force jq to produce pure142+ ASCII output with every non-ASCII character replaced with the143+ equivalent escape sequence.144+145+ * `--unbuffered`146+147+ Flush the output after each JSON object is printed (useful if148+ you're piping a slow data source into jq and piping jq's149+ output elsewhere).150+151+ * `--sort-keys` / `-S`:152+153+ Output the fields of each object with the keys in sorted order.154+155+ * `--raw-output` / `-r`:156+157+ With this option, if the filter's result is a string then it158+ will be written directly to standard output rather than being159+ formatted as a JSON string with quotes. This can be useful for160+ making jq filters talk to non-JSON-based systems.161+162+ * `-f filename` / `--from-file filename`:163+164+ Read filter from the file rather than from a command line, like165+ awk's -f option. You can also use '#' to make comments.166+167+ * `-e` / `--exit-status`:168+169+ Sets the exit status of jq to 0 if the last output values was170+ neither `false` nor `null`, 1 if the last output value was171+ either `false` or `null`, or 4 if no valid result was ever172+ produced. Normally jq exits with 2 if there was any usage173+ problem or system error, 3 if there was a jq program compile174+ error, or 0 if the jq program ran.175+176+ * `--arg name value`:177+178+ This option passes a value to the jq program as a predefined179+ variable. If you run jq with `--arg foo bar`, then `$foo` is180+ available in the program and has the value `"bar"`.181+182+ * `--argfile name filename`:183+184+ This option passes the first value from the named file as a185+ value to the jq program as a predefined variable. If you run jq186+ with `--argfile foo bar`, then `$foo` is available in the187+ program and has the value resulting from parsing the content of188+ the file named `bar`.189+190+ - title: Basic filters191+ entries:192+ - title: "`.`"193+ body: |194+195+ The absolute simplest (and least interesting) filter196+ is `.`. This is a filter that takes its input and197+ produces it unchanged as output.198+199+ Since jq by default pretty-prints all output, this trivial200+ program can be a useful way of formatting JSON output from,201+ say, `curl`.202+203+ examples:204+ - program: '.'205+ input: '"Hello, world!"'206+ output: ['"Hello, world!"']207+208+ - title: "`.foo`, `.foo.bar`"209+ body: |210+211+ The simplest *useful* filter is `.foo`. When given a212+ JSON object (aka dictionary or hash) as input, it produces213+ the value at the key "foo", or null if there's none present.214+215+ If the key contains special characters, you need to surround216+ it with double quotes like this: `."foo$"`.217+218+ A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.219+220+ examples:221+ - program: '.foo'222+ input: '{"foo": 42, "bar": "less interesting data"}'223+ output: [42]224+ - program: '.foo'225+ input: '{"notfoo": true, "alsonotfoo": false}'226+ output: ['null']227+ - program: '.["foo"]'228+ input: '{"foo": 42}'229+ output: [42]230+231+ - title: "`.foo?`"232+ body: |233+234+ Just like `.foo`, but does not output even an error when `.`235+ is not an array or an object.236+237+ examples:238+ - program: '.foo?'239+ input: '{"foo": 42, "bar": "less interesting data"}'240+ output: [42]241+ - program: '.foo?'242+ input: '{"notfoo": true, "alsonotfoo": false}'243+ output: ['null']244+ - program: '.["foo"]?'245+ input: '{"foo": 42}'246+ output: [42]247+ - program: '[.foo?]'248+ input: '[1,2]'249+ output: ['[]']250+251+ - title: "`.[<string>]`, `.[2]`, `.[10:15]`"252+ body: |253+254+ You can also look up fields of an object using syntax like255+ `.["foo"]` (.foo above is a shorthand version of this). This256+ one works for arrays as well, if the key is an257+ integer. Arrays are zero-based (like javascript), so `.[2]`258+ returns the third element of the array.259+260+ The `.[10:15]` syntax can be used to return a subarray of an261+ array or substring of a string. The array returned by262+ `.[10:15]` will be of length 5, containing the elements from263+ index 10 (inclusive) to index 15 (exclusive). Either index may264+ be negative (in which case it counts backwards from the end of265+ the array), or omitted (in which case it refers to the start266+ or end of the array).267+268+ The `?` "operator" can also be used with the slice operator,269+ as in `.[10:15]?`, which outputs values where the inputs are270+ slice-able.271+272+ examples:273+ - program: '.[0]'274+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'275+ output: ['{"name":"JSON", "good":true}']276+277+ - program: '.[2]'278+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'279+ output: ['null']280+281+ - program: '.[2:4]'282+ input: '["a","b","c","d","e"]'283+ output: ['["c", "d"]']284+285+ - program: '.[2:4]'286+ input: '"abcdefghi"'287+ output: ['"cd"']288+289+ - program: '.[:3]'290+ input: '["a","b","c","d","e"]'291+ output: ['["a", "b", "c"]']292+293+ - program: '.[-2:]'294+ input: '["a","b","c","d","e"]'295+ output: ['["d", "e"]']296+297+ - title: "`.[]`"298+ body: |299+300+ If you use the `.[index]` syntax, but omit the index301+ entirely, it will return *all* of the elements of an302+ array. Running `.[]` with the input `[1,2,3]` will produce the303+ numbers as three separate results, rather than as a single304+ array.305+306+ You can also use this on an object, and it will return all307+ the values of the object.308+309+ examples:310+ - program: '.[]'311+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'312+ output:313+ - '{"name":"JSON", "good":true}'314+ - '{"name":"XML", "good":false}'315+316+ - program: '.[]'317+ input: '[]'318+ output: []319+320+ - program: '.[]'321+ input: '{"a": 1, "b": 1}'322+ output: ['1', '1']323+324+ - title: "`.[]?`"325+ body: |326+327+ Like `.[]`, but no errors will be output if . is not an array328+ or object.329+330+ - title: "`,`"331+ body: |332+333+ If two filters are separated by a comma, then the334+ input will be fed into both and there will be multiple335+ outputs: first, all of the outputs produced by the left336+ expression, and then all of the outputs produced by the337+ right. For instance, filter `.foo, .bar`, produces338+ both the "foo" fields and "bar" fields as separate outputs.339+340+ examples:341+ - program: '.foo, .bar'342+ input: '{"foo": 42, "bar": "something else", "baz": true}'343+ output: ['42', '"something else"']344+345+ - program: ".user, .projects[]"346+ input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'347+ output: ['"stedolan"', '"jq"', '"wikiflow"']348+349+ - program: '.[4,2]'350+ input: '["a","b","c","d","e"]'351+ output: ['"e"', '"c"']352+353+ - title: "`|`"354+ body: |355+ The | operator combines two filters by feeding the output(s) of356+ the one on the left into the input of the one on the right. It's357+ pretty much the same as the Unix shell's pipe, if you're used to358+ that.359+360+ If the one on the left produces multiple results, the one on361+ the right will be run for each of those results. So, the362+ expression `.[] | .foo` retrieves the "foo" field of each363+ element of the input array.364+365+ examples:366+ - program: '.[] | .name'367+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'368+ output: ['"JSON"', '"XML"']369+370+ - title: Types and Values371+ body: |372+373+ jq supports the same set of datatypes as JSON - numbers,374+ strings, booleans, arrays, objects (which in JSON-speak are375+ hashes with only string keys), and "null".376+377+ Booleans, null, strings and numbers are written the same way as378+ in javascript. Just like everything else in jq, these simple379+ values take an input and produce an output - `42` is a valid jq380+ expression that takes an input, ignores it, and returns 42381+ instead.382+383+ entries:384+ - title: Array construction - `[]`385+ body: |386+387+ As in JSON, `[]` is used to construct arrays, as in388+ `[1,2,3]`. The elements of the arrays can be any jq389+ expression. All of the results produced by all of the390+ expressions are collected into one big array. You can use it391+ to construct an array out of a known quantity of values (as392+ in `[.foo, .bar, .baz]`) or to "collect" all the results of a393+ filter into an array (as in `[.items[].name]`)394+395+ Once you understand the "," operator, you can look at jq's array396+ syntax in a different light: the expression `[1,2,3]` is not using a397+ built-in syntax for comma-separated arrays, but is instead applying398+ the `[]` operator (collect results) to the expression 1,2,3 (which399+ produces three different results).400+401+ If you have a filter `X` that produces four results,402+ then the expression `[X]` will produce a single result, an403+ array of four elements.404+405+ examples:406+ - program: "[.user, .projects[]]"407+ input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'408+ output: ['["stedolan", "jq", "wikiflow"]']409+ - title: Objects - `{}`410+ body: |411+412+ Like JSON, `{}` is for constructing objects (aka413+ dictionaries or hashes), as in: `{"a": 42, "b": 17}`.414+415+ If the keys are "sensible" (all alphabetic characters), then416+ the quotes can be left off. The value can be any expression417+ (although you may need to wrap it in parentheses if it's a418+ complicated one), which gets applied to the {} expression's419+ input (remember, all filters have an input and an420+ output).421+422+ {foo: .bar}423+424+ will produce the JSON object `{"foo": 42}` if given the JSON425+ object `{"bar":42, "baz":43}`. You can use this to select426+ particular fields of an object: if the input is an object427+ with "user", "title", "id", and "content" fields and you428+ just want "user" and "title", you can write429+430+ {user: .user, title: .title}431+432+ Because that's so common, there's a shortcut syntax: `{user, title}`.433+434+ If one of the expressions produces multiple results,435+ multiple dictionaries will be produced. If the input's436+437+ {"user":"stedolan","titles":["JQ Primer", "More JQ"]}438+439+ then the expression440+441+ {user, title: .titles[]}442+443+ will produce two outputs:444+445+ {"user":"stedolan", "title": "JQ Primer"}446+ {"user":"stedolan", "title": "More JQ"}447+448+ Putting parentheses around the key means it will be evaluated as an449+ expression. With the same input as above,450+451+ {(.user): .titles}452+453+ produces454+455+ {"stedolan": ["JQ Primer", "More JQ"]}456+457+ examples:458+ - program: '{user, title: .titles[]}'459+ input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'460+ output:461+ - '{"user":"stedolan", "title": "JQ Primer"}'462+ - '{"user":"stedolan", "title": "More JQ"}'463+ - program: '{(.user): .titles}'464+ input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'465+ output: ['{"stedolan": ["JQ Primer", "More JQ"]}']466+467+ - title: Builtin operators and functions468+ body: |469+470+ Some jq operator (for instance, `+`) do different things471+ depending on the type of their arguments (arrays, numbers,472+ etc.). However, jq never does implicit type conversions. If you473+ try to add a string to an object you'll get an error message and474+ no result.475+476+ entries:477+ - title: Addition - `+`478+ body: |479+480+ The operator `+` takes two filters, applies them both481+ to the same input, and adds the results together. What482+ "adding" means depends on the types involved:483+484+ - **Numbers** are added by normal arithmetic.485+486+ - **Arrays** are added by being concatenated into a larger array.487+488+ - **Strings** are added by being joined into a larger string.489+490+ - **Objects** are added by merging, that is, inserting all491+ the key-value pairs from both objects into a single492+ combined object. If both objects contain a value for the493+ same key, the object on the right of the `+` wins. (For494+ recursive merge use the `*` operator.)495+496+ `null` can be added to any value, and returns the other497+ value unchanged.498+499+ examples:500+ - program: '.a + 1'501+ input: '{"a": 7}'502+ output: ['8']503+ - program: '.a + .b'504+ input: '{"a": [1,2], "b": [3,4]}'505+ output: ['[1,2,3,4]']506+ - program: '.a + null'507+ input: '{"a": 1}'508+ output: ['1']509+ - program: '.a + 1'510+ input: '{}'511+ output: ['1']512+ - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'513+ input: 'null'514+ output: ['{"a": 42, "b": 2, "c": 3}']515+516+ - title: Subtraction - `-`517+ body: |518+519+ As well as normal arithmetic subtraction on numbers, the `-`520+ operator can be used on arrays to remove all occurences of521+ the second array's elements from the first array.522+523+ examples:524+ - program: '4 - .a'525+ input: '{"a":3}'526+ output: ['1']527+ - program: . - ["xml", "yaml"]528+ input: '["xml", "yaml", "json"]'529+ output: ['["json"]']530+531+ - title: Multiplication, division, modulo - `*`, `/`, and `%`532+ body: |533+534+ These operators only work on numbers, and do the expected.535+536+ Multiplying a string by a number produces the concatenation of537+ that string that many times.538+539+ Dividing a string by another splits the first using the second540+ as separators.541+542+ Multiplying two objects will merge them recursively: this works543+ like addition but if both objects contain a value for the544+ same key, and the values are objects, the two are merged with545+ the same strategy.546+547+ examples:548+ - program: '10 / . * 3'549+ input: 5550+ output: [6]551+ - program: '. / ", "'552+ input: '"a, b,c,d, e"'553+ output: ['["a","b,c,d","e"]']554+ - program: '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'555+ input: 'null'556+ output: ['{"k": {"a": 0, "b": 2, "c": 3}}']557+558+ - title: "`length`"559+ body: |560+561+ The builtin function `length` gets the length of various562+ different types of value:563+564+ - The length of a **string** is the number of Unicode565+ codepoints it contains (which will be the same as its566+ JSON-encoded length in bytes if it's pure ASCII).567+568+ - The length of an **array** is the number of elements.569+570+ - The length of an **object** is the number of key-value pairs.571+572+ - The length of **null** is zero.573+574+ examples:575+ - program: '.[] | length'576+ input: '[[1,2], "string", {"a":2}, null]'577+ output: [2, 6, 1, 0]578+579+ - title: "`keys`"580+ body: |581+582+ The builtin function `keys`, when given an object, returns583+ its keys in an array.584+585+ The keys are sorted "alphabetically", by unicode codepoint586+ order. This is not an order that makes particular sense in587+ any particular language, but you can count on it being the588+ same for any two objects with the same set of keys,589+ regardless of locale settings.590+591+ When `keys` is given an array, it returns the valid indices592+ for that array: the integers from 0 to length-1.593+594+ examples:595+ - program: 'keys'596+ input: '{"abc": 1, "abcd": 2, "Foo": 3}'597+ output: ['["Foo", "abc", "abcd"]']598+ - program: 'keys'599+ input: '[42,3,35]'600+ output: ['[0,1,2]']601+602+ - title: "`has`"603+ body: |604+605+ The builtin function `has` returns whether the input object606+ has the given key, or the input array has an element at the607+ given index.608+609+ `has($key)` has the same effect as checking whether `$key`610+ is a member of the array returned by `keys`, although `has`611+ will be faster.612+613+ examples:614+ - program: 'map(has("foo"))'615+ input: '[{"foo": 42}, {}]'616+ output: ['[true, false]']617+ - program: 'map(has(2))'618+ input: '[[0,1], ["a","b","c"]]'619+ output: ['[false, true]']620+621+ - title: "`del`"622+ body: |623+624+ The builtin function `del` removes a key and its corresponding625+ value from an object.626+627+ examples:628+ - program: 'del(.foo)'629+ input: '{"foo": 42, "bar": 9001, "baz": 42}'630+ output: ['{"bar": 9001, "baz": 42}']631+ - program: 'del(.[1, 2])'632+ input: '["foo", "bar", "baz"]'633+ output: ['["foo"]']634+635+ - title: "`to_entries`, `from_entries`, `with_entries`"636+ body: |637+638+ These functions convert between an object and an array of639+ key-value pairs. If `to_entries` is passed an object, then640+ for each `k: v` entry in the input, the output array641+ includes `{"key": k, "value": v}`.642+643+ `from_entries` does the opposite conversion, and644+ `with_entries(foo)` is a shorthand for `to_entries |645+ map(foo) | from_entries`, useful for doing some operation to646+ all keys and values of an object.647+648+ examples:649+ - program: 'to_entries'650+ input: '{"a": 1, "b": 2}'651+ output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']652+ - program: 'from_entries'653+ input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'654+ output: ['{"a": 1, "b": 2}']655+ - program: 'with_entries(.key |= "KEY_" + .)'656+ input: '{"a": 1, "b": 2}'657+ output: ['{"KEY_a": 1, "KEY_b": 2}']658+659+660+ - title: "`select`"661+ body: |662+663+ The function `select(foo)` produces its input unchanged if664+ `foo` returns true for that input, and produces no output665+ otherwise.666+667+ It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`668+ will give you `[2,3]`.669+670+ examples:671+ - program: 'map(select(. >= 2))'672+ input: '[1,5,3,0,7]'673+ output: ['[5,3,7]']674+675+676+ - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `strings`, `nulls`, `values`, `scalars`"677+ body: |678+679+ These built-ins select only inputs that are arrays, objects,680+ iterables (arrays or objects), booleans, numbers, strings,681+ null, non-null values, and non-iterables, respectively.682+683+ examples:684+ - program: '.[]|numbers'685+ input: '[[],{},1,"foo",null,true,false]'686+ output: ['1']687+688+ - title: "`empty`"689+ body: |690+691+ `empty` returns no results. None at all. Not even `null`.692+693+ It's useful on occasion. You'll know if you need it :)694+695+ examples:696+ - program: '1, empty, 2'697+ input: 'null'698+ output: [1, 2]699+ - program: '[1,2,empty,3]'700+ input: 'null'701+ output: ['[1,2,3]']702+703+ - title: "`map(x)`"704+ body: |705+706+ For any filter `x`, `map(x)` will run that filter for each707+ element of the input array, and produce the outputs a new708+ array. `map(.+1)` will increment each element of an array of numbers.709+710+ `map(x)` is equivalent to `[.[] | x]`. In fact, this is how711+ it's defined.712+713+ examples:714+ - program: 'map(.+1)'715+ input: '[1,2,3]'716+ output: ['[2,3,4]']717+718+ - title: "`paths`"719+ body: |720+721+ Outputs the paths to all the elements in its input (except it722+ does not output the empty list, representing . itself).723+724+ `paths` is equivalent to725+726+ def paths: path(recurse(if (type|. == "array" or . == "object") then .[] else empty end))|select(length > 0);727+728+ examples:729+ - program: '[paths]'730+ input: '[1,[[],{"a":2}]]'731+ output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']732+733+ - title: "`leaf_paths`"734+ body: |735+736+ Outputs the paths to all the leaves (non-array, non-object737+ elements) in its input.738+739+ examples:740+ - program: '[leaf_paths]'741+ input: '[1,[[],{"a":2}]]'742+ output: ['[[0],[1,1,"a"]]']743+744+ - title: "`add`"745+ body: |746+747+ The filter `add` takes as input an array, and produces as748+ output the elements of the array added together. This might749+ mean summed, concatenated or merged depending on the types750+ of the elements of the input array - the rules are the same751+ as those for the `+` operator (described above).752+753+ If the input is an empty array, `add` returns `null`.754+755+ examples:756+ - program: add757+ input: '["a","b","c"]'758+ output: ['"abc"']759+ - program: add760+ input: '[1, 2, 3]'761+ output: [6]762+ - program: add763+ input: '[]'764+ output: ["null"]765+766+ - title: "`any`"767+ body: |768+769+ The filter `any` takes as input an array of boolean values,770+ and produces `true` as output if any of the elements of771+ the array are `true`.772+773+ If the input is an empty array, `any` returns `false`.774+775+ examples:776+ - program: any777+ input: '[true, false]'778+ output: ["true"]779+ - program: any780+ input: '[false, false]'781+ output: ["false"]782+ - program: any783+ input: '[]'784+ output: ["false"]785+786+ - title: "`all`"787+ body: |788+789+ The filter `all` takes as input an array of boolean values,790+ and produces `true` as output if all of the elements of791+ the array are `true`.792+793+ If the input is an empty array, `all` returns `true`.794+795+ examples:796+ - program: all797+ input: '[true, false]'798+ output: ["false"]799+ - program: all800+ input: '[true, true]'801+ output: ["true"]802+ - program: all803+ input: '[]'804+ output: ["true"]805+806+ - title: "`range`"807+ body: |808+809+ The `range` function produces a range of numbers. `range(4;10)`810+ produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers811+ are produced as separate outputs. Use `[range(4;10)]` to get a range as812+ an array.813+814+ examples:815+ - program: 'range(2;4)'816+ input: 'null'817+ output: ['2', '3']818+ - program: '[range(2;4)]'819+ input: 'null'820+ output: ['[2,3]']821+822+ - title: "`floor`"823+ body: |824+825+ The `floor` function returns the floor of its numeric input.826+827+ examples:828+ - program: 'floor'829+ input: '3.14159'830+ output: ['3']831+832+ - title: "`sqrt`"833+ body: |834+835+ The `sqrt` function returns the square root of its numeric input.836+837+ examples:838+ - program: 'sqrt'839+ input: '9'840+ output: ['3']841+842+ - title: "`tonumber`"843+ body: |844+845+ The `tonumber` function parses its input as a number. It846+ will convert correctly-formatted strings to their numeric847+ equivalent, leave numbers alone, and give an error on all other input.848+849+ examples:850+ - program: '.[] | tonumber'851+ input: '[1, "1"]'852+ output: [1, 1]853+854+ - title: "`tostring`"855+ body: |856+857+ The `tostring` function prints its input as a858+ string. Strings are left unchanged, and all other values are859+ JSON-encoded.860+861+ examples:862+ - program: '.[] | tostring'863+ input: '[1, "1", [1]]'864+ output: ['"1"', '"1"', '"[1]"']865+866+ - title: "`type`"867+ body: |868+869+ The `type` function returns the type of its argument as a870+ string, which is one of null, boolean, number, string, array871+ or object.872+873+ examples:874+ - program: 'map(type)'875+ input: '[0, false, [], {}, null, "hello"]'876+ output: ['["number", "boolean", "array", "object", "null", "string"]']877+878+ - title: "`sort, sort_by`"879+ body: |880+881+ The `sort` functions sorts its input, which must be an882+ array. Values are sorted in the following order:883+884+ * `null`885+ * `false`886+ * `true`887+ * numbers888+ * strings, in alphabetical order (by unicode codepoint value)889+ * arrays, in lexical order890+ * objects891+892+ The ordering for objects is a little complex: first they're893+ compared by comparing their sets of keys (as arrays in894+ sorted order), and if their keys are equal then the values895+ are compared key by key.896+897+ `sort_by` may be used to sort by a particular field of an898+ object, or by applying any jq filter. `sort_by(foo)`899+ compares two elements by comparing the result of `foo` on900+ each element.901+902+ examples:903+ - program: 'sort'904+ input: '[8,3,null,6]'905+ output: ['[null,3,6,8]']906+ - program: 'sort_by(.foo)'907+ input: '[{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}]'908+ output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']909+910+ - title: "`group_by`"911+ body: |912+913+ `group_by(.foo)` takes as input an array, groups the914+ elements having the same `.foo` field into separate arrays,915+ and produces all of these arrays as elements of a larger916+ array, sorted by the value of the `.foo` field.917+918+ Any jq expression, not just a field access, may be used in919+ place of `.foo`. The sorting order is the same as described920+ in the `sort` function above.921+922+ examples:923+ - program: 'group_by(.foo)'924+ input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'925+ output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']926+927+ - title: "`min`, `max`, `min_by`, `max_by`"928+ body: |929+930+ Find the minimum or maximum element of the input array. The931+ `_by` versions allow you to specify a particular field or932+ property to examine, e.g. `min_by(.foo)` finds the object933+ with the smallest `foo` field.934+935+ examples:936+ - program: 'min'937+ input: '[5,4,2,7]'938+ output: ['2']939+ - program: 'max_by(.foo)'940+ input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'941+ output: ['{"foo":2, "bar":3}']942+943+ - title: "`unique`"944+ body: |945+946+ The `unique` function takes as input an array and produces947+ an array of the same elements, in sorted order, with948+ duplicates removed.949+950+ examples:951+ - program: 'unique'952+ input: '[1,2,5,3,5,3,1,3]'953+ output: ['[1,2,3,5]']954+955+ - title: "`unique_by`"956+ body: |957+958+ The `unique_by(.foo)` function takes as input an array and produces959+ an array of the same elements, in sorted order, with960+ elqements with a duplicate `.foo` field removed. Think of it as making961+ an array by taking one element out of every group produced by962+ `group_by`.963+964+ examples:965+ - program: 'unique_by(.foo)'966+ input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'967+ output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']968+ - program: 'unique_by(length)'969+ input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'970+ output: ['["bacon", "chunky", "asparagus"]']971+972+973+ - title: "`reverse`"974+ body: |975+976+ This function reverses an array.977+978+ examples:979+ - program: 'reverse'980+ input: '[1,2,3,4]'981+ output: ['[4,3,2,1]']982+983+ - title: "`contains`"984+ body: |985+986+ The filter `contains(b)` will produce true if b is987+ completely contained within the input. A string B is988+ contained in a string A if B is a substring of A. An array B989+ is contained in an array A is all elements in B are990+ contained in any element in A. An object B is contained in991+ object A if all of the values in B are contained in the992+ value in A with the same key. All other types are assumed to993+ be contained in each other if they are equal.994+995+ examples:996+ - program: 'contains("bar")'997+ input: '"foobar"'998+ output: ['true']999+ - program: 'contains(["baz", "bar"])'1000+ input: '["foobar", "foobaz", "blarp"]'1001+ output: ['true']1002+ - program: 'contains(["bazzzzz", "bar"])'1003+ input: '["foobar", "foobaz", "blarp"]'1004+ output: ['false']1005+ - program: 'contains({foo: 12, bar: [{barp: 12}]})'1006+ input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1007+ output: ['true']1008+ - program: 'contains({foo: 12, bar: [{barp: 15}]})'1009+ input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1010+ output: ['false']1011+1012+ - title: "`indices(s)`"1013+ body: |1014+1015+ Outputs an array containing the indices in `.` where `s`1016+ occurs. The input may be an array, in which case if `s` is an1017+ array then the indices output will be those where all elements1018+ in `.` match those of `s`.1019+1020+ examples:1021+ - program: 'indices(", ")'1022+ input: '"a,b, cd, efg, hijk"'1023+ output: ['[3,7,12]']1024+ - program: 'indices(1)'1025+ input: '[0,1,2,1,3,1,4]'1026+ output: ['[1,3,5]']1027+ - program: 'indices([1,2])'1028+ input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1029+ output: ['[1,8]']1030+1031+ - title: "`index(s)`, `rindex(s)`"1032+ body: |1033+1034+ Outputs the index of the first (`index`) or last (`rindex`)1035+ occurrence of `s` in the input.1036+1037+ examples:1038+ - program: 'index(", ")'1039+ input: '"a,b, cd, efg, hijk"'1040+ output: ['3']1041+ - program: 'rindex(", ")'1042+ input: '"a,b, cd, efg, hijk"'1043+ output: ['12']1044+1045+ - title: "`startswith`"1046+ body: |1047+1048+ Outputs `true` if . starts with the given string argument.1049+1050+ examples:1051+ - program: '[.[]|startswith("foo")]'1052+ input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1053+ output: ['[false, true, false, true, false]']1054+1055+ - title: "`endswith`"1056+ body: |1057+1058+ Outputs `true` if . ends with the given string argument.1059+1060+ examples:1061+ - program: '[.[]|endswith("foo")]'1062+ input: '["foobar", "barfoo"]'1063+ output: ['[false, true]']1064+1065+ - title: "`ltrimstr`"1066+ body: |1067+1068+ Outputs its input with the given prefix string removed, if it1069+ starts with it.1070+1071+ examples:1072+ - program: '[.[]|ltrimstr("foo")]'1073+ input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1074+ output: ['["fo","","barfoo","bar","afoo"]']1075+1076+ - title: "`rtrimstr`"1077+ body: |1078+1079+ Outputs its input with the given suffix string removed, if it1080+ starts with it.1081+1082+ examples:1083+ - program: '[.[]|rtrimstr("foo")]'1084+ input: '["fo", "foo", "barfoo", "foobar", "foob"]'1085+ output: ['["fo","","bar","foobar","foob"]']1086+1087+ - title: "`explode`"1088+ body: |1089+1090+ Converts an input string into an array of the string's1091+ codepoint numbers.1092+1093+ examples:1094+ - program: 'explode'1095+ input: '"foobar"'1096+ output: ['[102,111,111,98,97,114]']1097+1098+ - title: "`implode`"1099+ body: |1100+1101+ The inverse of explode.1102+1103+ examples:1104+ - program: 'implode'1105+ input: '[65, 66, 67]'1106+ output: ['"ABC"']1107+1108+ - title: "`split`"1109+ body: |1110+1111+ Splits an input string on the separator argument.1112+1113+ examples:1114+ - program: 'split(", ")'1115+ input: '"a, b,c,d, e"'1116+ output: ['["a","b,c,d","e"]']1117+1118+ - title: "`join`"1119+ body: |1120+1121+ Joins the array of elements given as input, using the1122+ argument as separator. It is the inverse of `split`: that is,1123+ running `split("foo") | join("foo")` over any input string1124+ returns said input string.1125+1126+ examples:1127+ - program: 'join(", ")'1128+ input: '["a","b,c,d","e"]'1129+ output: ['"a, b,c,d, e"']1130+1131+1132+ - title: "`recurse`"1133+ body: |1134+1135+ The `recurse` function allows you to search through a1136+ recursive structure, and extract interesting data from all1137+ levels. Suppose your input represents a filesystem:1138+1139+ {"name": "/", "children": [1140+ {"name": "/bin", "children": [1141+ {"name": "/bin/ls", "children": []},1142+ {"name": "/bin/sh", "children": []}]},1143+ {"name": "/home", "children": [1144+ {"name": "/home/stephen", "children": [1145+ {"name": "/home/stephen/jq", "children": []}]}]}]}1146+1147+ Now suppose you want to extract all of the filenames1148+ present. You need to retrieve `.name`, `.children[].name`,1149+ `.children[].children[].name`, and so on. You can do this1150+ with:1151+1152+ recurse(.children[]) | .name1153+1154+ examples:1155+ - program: 'recurse(.foo[])'1156+ input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'1157+ output:1158+ - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'1159+ - '{"foo":[]}'1160+ - '{"foo":[{"foo":[]}]}'1161+ - '{"foo":[]}'1162+1163+ - title: "`recurse_down`"1164+ body: |1165+1166+ A quieter version of `recurse(.[])`, equivalent to:1167+1168+ def recurse_down: recurse(.[]?);1169+1170+ - title: "`..`"1171+ body: |1172+1173+ Short-hand for `recurse_down`. This is intended to resemble1174+ the XPath `//` operator. Note that `..a` does not work; use1175+ `..|a` instead.1176+1177+ examples:1178+ - program: '..|.a?'1179+ input: '[[{"a":1}]]'1180+ output: ['1']1181+1182+ - title: "String interpolation - `\\(foo)`"1183+ body: |1184+1185+ Inside a string, you can put an expression inside parens1186+ after a backslash. Whatever the expression returns will be1187+ interpolated into the string.1188+1189+ examples:1190+ - program: '"The input was \(.), which is one less than \(.+1)"'1191+ input: '42'1192+ output: ['"The input was 42, which is one less than 43"']1193+1194+ - title: "Convert to/from JSON"1195+ body: |1196+1197+ The `tojson` and `fromjson` builtins dump values as JSON texts1198+ or parse JSON texts into values, respectively. The tojson1199+ builtin differs from tostring in that tostring returns strings1200+ unmodified, while tojson encodes strings as JSON strings.1201+1202+ examples:1203+ - program: '[.[]|tostring]'1204+ input: '[1, "foo", ["foo"]]'1205+ output: ['["1","foo","[\"foo\"]"]']1206+ - program: '[.[]|tojson]'1207+ input: '[1, "foo", ["foo"]]'1208+ output: ['["1","\"foo\"","[\"foo\"]"]']1209+ - program: '[.[]|tojson|fromjson]'1210+ input: '[1, "foo", ["foo"]]'1211+ output: ['[1,"foo",["foo"]]']1212+1213+ - title: "Format strings and escaping"1214+ body: |1215+1216+ The `@foo` syntax is used to format and escape strings,1217+ which is useful for building URLs, documents in a language1218+ like HTML or XML, and so forth. `@foo` can be used as a1219+ filter on its own, the possible escapings are:1220+1221+ * `@text`:1222+1223+ Calls `tostring`, see that function for details.1224+1225+ * `@json`:1226+1227+ Serialises the input as JSON.1228+1229+ * `@html`:1230+1231+ Applies HTML/XML escaping, by mapping the characters1232+ `<>&'"` to their entity equivalents `<`, `>`,1233+ `&`, `'`, `"`.1234+1235+ * `@uri`:1236+1237+ Applies percent-encoding, by mapping all reserved URI1238+ characters to a `%xx` sequence.1239+1240+ * `@csv`:1241+1242+ The input must be an array, and it is rendered as CSV1243+ with double quotes for strings, and quotes escaped by1244+ repetition.1245+1246+ * `@sh`:1247+1248+ The input is escaped suitable for use in a command-line1249+ for a POSIX shell. If the input is an array, the output1250+ will be a series of space-separated strings.1251+1252+ * `@base64`:1253+1254+ The input is converted to base64 as specified by RFC 4648.1255+1256+ This syntax can be combined with string interpolation in a1257+ useful way. You can follow a `@foo` token with a string1258+ literal. The contents of the string literal will *not* be1259+ escaped. However, all interpolations made inside that string1260+ literal will be escaped. For instance,1261+1262+ @uri "https://www.google.com/search?q=\(.search)"1263+1264+ will produce the following output for the input1265+ `{"search":"what is jq?"}`:1266+1267+ "https://www.google.com/search?q=what%20is%20jq%3f"1268+1269+ Note that the slashes, question mark, etc. in the URL are1270+ not escaped, as they were part of the string literal.1271+1272+ examples:1273+ - program: '@html'1274+ input: '"This works if x < y"'1275+ output: ['"This works if x < y"']1276+1277+# - program: '@html "<span>Anonymous said: \(.)</span>"'1278+# input: '"<script>alert(\"lol hax\");</script>"'1279+# output: ["<span>Anonymous said: <script>alert("lol hax");</script></span>"]1280+1281+ - program: '@sh "echo \(.)"'1282+ input: "\"O'Hara's Ale\""1283+ output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]1284+1285+ - title: Conditionals and Comparisons1286+ entries:1287+ - title: "`==`, `!=`"1288+ body: |1289+1290+ The expression 'a == b' will produce 'true' if the result of a and b1291+ are equal (that is, if they represent equivalent JSON documents) and1292+ 'false' otherwise. In particular, strings are never considered equal1293+ to numbers. If you're coming from Javascript, jq's == is like1294+ Javascript's === - considering values equal only when they have the1295+ same type as well as the same value.1296+1297+ != is "not equal", and 'a != b' returns the opposite value of 'a == b'1298+1299+ examples:1300+ - program: '.[] == 1'1301+ input: '[1, 1.0, "1", "banana"]'1302+ output: ['true', 'true', 'false', 'false']1303+ - title: if-then-else1304+ body: |1305+1306+ `if A then B else C end` will act the same as `B` if `A`1307+ produces a value other than false or null, but act the same1308+ as `C` otherwise.1309+1310+ Checking for false or null is a simpler notion of1311+ "truthiness" than is found in Javascript or Python, but it1312+ means that you'll sometimes have to be more explicit about1313+ the condition you want: you can't test whether, e.g. a1314+ string is empty using `if .name then A else B end`, you'll1315+ need something more like `if (.name | length) > 0 then A else1316+ B end` instead.1317+1318+ If the condition `A` produces multiple results, then `B` is evaluated1319+ once for each result that is not false or null, and `C` is evaluated1320+ once for each false or null.1321+1322+ More cases can be added to an if using `elif A then B` syntax.1323+1324+ examples:1325+ - program: |-1326+ if . == 0 then1327+ "zero"1328+ elif . == 1 then1329+ "one"1330+ else1331+ "many"1332+ end1333+ input: 21334+ output: ['"many"']1335+1336+ - title: "`>, >=, <=, <`"1337+ body: |1338+1339+ The comparison operators `>`, `>=`, `<=`, `<` return whether1340+ their left argument is greater than, greater than or equal1341+ to, less than or equal to or less than their right argument1342+ (respectively).1343+1344+ The ordering is the same as that described for `sort`, above.1345+1346+ examples:1347+ - program: '. < 5'1348+ input: 21349+ output: ['true']1350+1351+ - title: and/or/not1352+ body: |1353+1354+ jq supports the normal Boolean operators and/or/not. They have the1355+ same standard of truth as if expressions - false and null are1356+ considered "false values", and anything else is a "true value".1357+1358+ If an operand of one of these operators produces multiple1359+ results, the operator itself will produce a result for each input.1360+1361+ `not` is in fact a builtin function rather than an operator,1362+ so it is called as a filter to which things can be piped1363+ rather than with special syntax, as in `.foo and .bar |1364+ not`.1365+1366+ These three only produce the values "true" and "false", and1367+ so are only useful for genuine Boolean operations, rather1368+ than the common Perl/Python/Ruby idiom of1369+ "value_that_may_be_null or default". If you want to use this1370+ form of "or", picking between two values rather than1371+ evaluating a condition, see the "//" operator below.1372+1373+ examples:1374+ - program: '42 and "a string"'1375+ input: 'null'1376+ output: ['true']1377+ - program: '(true, false) or false'1378+ input: 'null'1379+ output: ['true', 'false']1380+# - program: '(true, false) and (true, false)'1381+# input: 'null'1382+# output: ['true', 'false', 'false', 'false']1383+ - program: '(true, true) and (true, false)'1384+ input: 'null'1385+ output: ['true', 'false', 'true', 'false']1386+ - program: '[true, false | not]'1387+ input: 'null'1388+ output: ['[false, true]']1389+1390+ - title: Alternative operator - `//`1391+ body: |1392+1393+ A filter of the form `a // b` produces the same1394+ results as `a`, if `a` produces results other than `false`1395+ and `null`. Otherwise, `a // b` produces the same results as `b`.1396+1397+ This is useful for providing defaults: `.foo // 1` will1398+ evaluate to `1` if there's no `.foo` element in the1399+ input. It's similar to how `or` is sometimes used in Python1400+ (jq's `or` operator is reserved for strictly Boolean1401+ operations).1402+1403+ examples:1404+ - program: '.foo // 42'1405+ input: '{"foo": 19}'1406+ output: [19]1407+ - program: '.foo // 42'1408+ input: '{}'1409+ output: [42]1410+1411+ - title: Advanced features1412+ body: |1413+ Variables are an absolute necessity in most programming languages, but1414+ they're relegated to an "advanced feature" in jq.1415+1416+ In most languages, variables are the only means of passing around1417+ data. If you calculate a value, and you want to use it more than once,1418+ you'll need to store it in a variable. To pass a value to another part1419+ of the program, you'll need that part of the program to define a1420+ variable (as a function parameter, object member, or whatever) in1421+ which to place the data.1422+1423+ It is also possible to define functions in jq, although this is1424+ is a feature whose biggest use is defining jq's standard library1425+ (many jq functions such as `map` and `find` are in fact written1426+ in jq).1427+1428+ Finally, jq has a `reduce` operation, which is very powerful but a1429+ bit tricky. Again, it's mostly used internally, to define some1430+ useful bits of jq's standard library.1431+1432+ entries:1433+ - title: Variables1434+ body: |1435+1436+ In jq, all filters have an input and an output, so manual1437+ plumbing is not necessary to pass a value from one part of a program1438+ to the next. Many expressions, for instance `a + b`, pass their input1439+ to two distinct subexpressions (here `a` and `b` are both passed the1440+ same input), so variables aren't usually necessary in order to use a1441+ value twice.1442+1443+ For instance, calculating the average value of an array of numbers1444+ requires a few variables in most languages - at least one to hold the1445+ array, perhaps one for each element or for a loop counter. In jq, it's1446+ simply `add / length` - the `add` expression is given the array and1447+ produces its sum, and the `length` expression is given the array and1448+ produces its length.1449+1450+ So, there's generally a cleaner way to solve most problems in jq than1451+ defining variables. Still, sometimes they do make things easier, so jq1452+ lets you define variables using `expression as $variable`. All1453+ variable names start with `$`. Here's a slightly uglier version of the1454+ array-averaging example:1455+1456+ length as $array_length | add / $array_length1457+1458+ We'll need a more complicated problem to find a situation where using1459+ variables actually makes our lives easier.1460+1461+1462+ Suppose we have an array of blog posts, with "author" and "title"1463+ fields, and another object which is used to map author usernames to1464+ real names. Our input looks like:1465+1466+ {"posts": [{"title": "Frist psot", "author": "anon"},1467+ {"title": "A well-written article", "author": "person1"}],1468+ "realnames": {"anon": "Anonymous Coward",1469+ "person1": "Person McPherson"}}1470+1471+ We want to produce the posts with the author field containing a real1472+ name, as in:1473+1474+ {"title": "Frist psot", "author": "Anonymous Coward"}1475+ {"title": "A well-written article", "author": "Person McPherson"}1476+1477+ We use a variable, $names, to store the realnames object, so that we1478+ can refer to it later when looking up author usernames:1479+1480+ .realnames as $names | .posts[] | {title, author: $names[.author]}1481+1482+ The expression `exp as $x | ...` means: for each value of expression1483+ `exp`, run the rest of the pipeline with the entire original input, and1484+ with `$x` set to that value. Thus `as` functions as something of a1485+ foreach loop.1486+1487+ Variables are scoped over the rest of the expression that defines1488+ them, so1489+1490+ .realnames as $names | (.posts[] | {title, author: $names[.author]})1491+1492+ will work, but1493+1494+ (.realnames as $names | .posts[]) | {title, author: $names[.author]}1495+1496+ won't.1497+1498+ examples:1499+ - program: '.bar as $x | .foo | . + $x'1500+ input: '{"foo":10, "bar":200}'1501+ output: ['210']1502+1503+ - title: 'Defining Functions'1504+ body: |1505+1506+ You can give a filter a name using "def" syntax:1507+1508+ def increment: . + 1;1509+1510+ From then on, `increment` is usable as a filter just like a1511+ builtin function (in fact, this is how some of the builtins1512+ are defined). A function may take arguments:1513+1514+ def map(f): [.[] | f];1515+1516+ Arguments are passed as filters, not as values. The1517+ same argument may be referenced multiple times with1518+ different inputs (here `f` is run for each element of the1519+ input array). Arguments to a function work more like1520+ callbacks than like value arguments.1521+1522+ If you want the value-argument behaviour for defining simple1523+ functions, you can just use a variable:1524+1525+ def addvalue(f): f as $value | map(. + $value);1526+1527+ With that definition, `addvalue(.foo)` will add the current1528+ input's `.foo` field to each element of the array.1529+1530+ examples:1531+ - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'1532+ input: '[[1,2],[10,20]]'1533+ output: ['[[1,2,1], [10,20,10]]']1534+ - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'1535+ input: '[[1,2],[10,20]]'1536+ output: ['[[1,2,1,2], [10,20,1,2]]']1537+1538+ - title: Reduce1539+ body: |1540+1541+ The `reduce` syntax in jq allows you to combine all of the1542+ results of an expression by accumulating them into a single1543+ answer. As an example, we'll pass `[3,2,1]` to this expression:1544+1545+ reduce .[] as $item (0; . + $item)1546+1547+ For each result that `.[]` produces, `. + $item` is run to1548+ accumulate a running total, starting from 0. In this1549+ example, `.[]` produces the results 3, 2, and 1, so the1550+ effect is similar to running something like this:1551+1552+ 0 | (3 as $item | . + $item) |1553+ (2 as $item | . + $item) |1554+ (1 as $item | . + $item)1555+1556+ examples:1557+ - program: 'reduce .[] as $item (0; . + $item)'1558+ input: '[10,2,5,3]'1559+ output: ['20']1560+1561+1562+ - title: Assignment1563+ body: |1564+1565+ Assignment works a little differently in jq than in most1566+ programming languages. jq doesn't distinguish between references1567+ to and copies of something - two objects or arrays are either1568+ equal or not equal, without any further notion of being "the1569+ same object" or "not the same object".1570+1571+ If an object has two fields which are arrays, `.foo` and `.bar`,1572+ and you append something to `.foo`, then `.bar` will not get1573+ bigger. Even if you've just set `.bar = .foo`. If you're used to1574+ programming in languages like Python, Java, Ruby, Javascript,1575+ etc. then you can think of it as though jq does a full deep copy1576+ of every object before it does the assignment (for performance,1577+ it doesn't actually do that, but that's the general idea).1578+1579+ entries:1580+ - title: "`=`"1581+ body: |1582+1583+ The filter `.foo = 1` will take as input an object1584+ and produce as output an object with the "foo" field set to1585+ 1. There is no notion of "modifying" or "changing" something1586+ in jq - all jq values are immutable. For instance,1587+1588+ .foo = .bar | .foo.baz = 11589+1590+ will not have the side-effect of setting .bar.baz to be set1591+ to 1, as the similar-looking program in Javascript, Python,1592+ Ruby or other languages would. Unlike these languages (but1593+ like Haskell and some other functional languages), there is1594+ no notion of two arrays or objects being "the same array" or1595+ "the same object". They can be equal, or not equal, but if1596+ we change one of them in no circumstances will the other1597+ change behind our backs.1598+1599+ This means that it's impossible to build circular values in1600+ jq (such as an array whose first element is itself). This is1601+ quite intentional, and ensures that anything a jq program1602+ can produce can be represented in JSON.1603+1604+ - title: "`|=`"1605+ body: |1606+ As well as the assignment operator '=', jq provides the "update"1607+ operator '|=', which takes a filter on the right-hand side and1608+ works out the new value for the property being assigned to by running1609+ the old value through this expression. For instance, .foo |= .+1 will1610+ build an object with the "foo" field set to the input's "foo" plus 1.1611+1612+ This example should show the difference between '=' and '|=':1613+1614+ Provide input '{"a": {"b": 10}, "b": 20}' to the programs:1615+1616+ .a = .b1617+ .a |= .b1618+1619+ The former will set the "a" field of the input to the "b" field of the1620+ input, and produce the output {"a": 20}. The latter will set the "a"1621+ field of the input to the "a" field's "b" field, producing {"a": 10}.1622+1623+ - title: "`+=`, `-=`, `*=`, `/=`, `%=`, `//=`"1624+ body: |1625+1626+ jq has a few operators of the form `a op= b`, which are all1627+ equivalent to `a |= . op b`. So, `+= 1` can be used to increment values.1628+1629+ examples:1630+ - program: .foo += 11631+ input: '{"foo": 42}'1632+ output: ['{"foo": 43}']1633+1634+ - title: Complex assignments1635+ body: |1636+ Lots more things are allowed on the left-hand side of a jq assignment1637+ than in most langauges. We've already seen simple field accesses on1638+ the left hand side, and it's no surprise that array accesses work just1639+ as well:1640+1641+ .posts[0].title = "JQ Manual"1642+1643+ What may come as a surprise is that the expression on the left may1644+ produce multiple results, referring to different points in the input1645+ document:1646+1647+ .posts[].comments |= . + ["this is great"]1648+1649+ That example appends the string "this is great" to the "comments"1650+ array of each post in the input (where the input is an object with a1651+ field "posts" which is an array of posts).1652+1653+ When jq encounters an assignment like 'a = b', it records the "path"1654+ taken to select a part of the input document while executing a. This1655+ path is then used to find which part of the input to change while1656+ executing the assignment. Any filter may be used on the1657+ left-hand side of an equals - whichever paths it selects from the1658+ input will be where the assignment is performed.1659+1660+ This is a very powerful operation. Suppose we wanted to add a comment1661+ to blog posts, using the same "blog" input above. This time, we only1662+ want to comment on the posts written by "stedolan". We can find those1663+ posts using the "select" function described earlier:1664+1665+ .posts[] | select(.author == "stedolan")1666+1667+ The paths provided by this operation point to each of the posts that1668+ "stedolan" wrote, and we can comment on each of them in the same way1669+ that we did before:1670+1671+ (.posts[] | select(.author == "stedolan") | .comments) |=1672+ . + ["terrible."]added:docs/content/manual/v1.5/manual.yml+2878 added
1+---2+headline: jq 1.5 Manual3+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 simple 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 whether or not 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 (object keys)732+ 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 return the outputs in 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 elements of936+ the array are `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 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: "`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, then `B` is evaluated1798+ once for each result that is not false or null, and `C` is evaluated1799+ once for each false or null.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: "`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: "`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: "`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: "`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: "`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: "`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: "`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 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+added:docs/content/manual/v1.6/manual.yml+3287 added
1+---2+headline: jq 1.6 Manual3+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 mode also parses the output of jq without the `--seq`111+ option.112+113+ * `--stream`:114+115+ Parse the input in streaming fashion, outputing arrays of path116+ and leaf values (scalars and empty arrays or empty objects).117+ For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]`118+ becomes `[[0],[]]`, `[[1],"a"]`, and `[[1,0],"b"]`.119+120+ This is useful for processing very large inputs. Use this in121+ conjunction with filtering and the `reduce` and `foreach` syntax122+ to reduce large inputs incrementally.123+124+ * `--slurp`/`-s`:125+126+ Instead of running the filter for each JSON object in the127+ input, read the entire input stream into a large array and run128+ the filter just once.129+130+ * `--raw-input`/`-R`:131+132+ Don't parse the input as JSON. Instead, each line of text is133+ passed to the filter as a string. If combined with `--slurp`,134+ then the entire input is passed to the filter as a single long135+ string.136+137+ * `--null-input`/`-n`:138+139+ Don't read any input at all! Instead, the filter is run once140+ using `null` as the input. This is useful when using jq as a141+ simple calculator or to construct JSON data from scratch.142+143+ * `--compact-output` / `-c`:144+145+ By default, jq pretty-prints JSON output. Using this option146+ will result in more compact output by instead putting each147+ JSON object on a single line.148+149+ * `--tab`:150+151+ Use a tab for each indentation level instead of two spaces.152+153+ * `--indent n`:154+155+ Use the given number of spaces (no more than 8) for indentation.156+157+ * `--color-output` / `-C` and `--monochrome-output` / `-M`:158+159+ By default, jq outputs colored JSON if writing to a160+ terminal. You can force it to produce color even if writing to161+ a pipe or a file using `-C`, and disable color with `-M`.162+163+ Colors can be configured with the `JQ_COLORS` environment164+ variable (see below).165+166+ * `--ascii-output` / `-a`:167+168+ jq usually outputs non-ASCII Unicode codepoints as UTF-8, even169+ if the input specified them as escape sequences (like170+ "\u03bc"). Using this option, you can force jq to produce pure171+ ASCII output with every non-ASCII character replaced with the172+ equivalent escape sequence.173+174+ * `--unbuffered`175+176+ Flush the output after each JSON object is printed (useful if177+ you're piping a slow data source into jq and piping jq's178+ output elsewhere).179+180+ * `--sort-keys` / `-S`:181+182+ Output the fields of each object with the keys in sorted order.183+184+ * `--raw-output` / `-r`:185+186+ With this option, if the filter's result is a string then it187+ will be written directly to standard output rather than being188+ formatted as a JSON string with quotes. This can be useful for189+ making jq filters talk to non-JSON-based systems.190+191+ * `--join-output` / `-j`:192+193+ Like `-r` but jq won't print a newline after each output.194+195+ * `-f filename` / `--from-file filename`:196+197+ Read filter from the file rather than from a command line, like198+ awk's -f option. You can also use '#' to make comments.199+200+ * `-Ldirectory` / `-L directory`:201+202+ Prepend `directory` to the search list for modules. If this203+ option is used then no builtin search list is used. See the204+ section on modules below.205+206+ * `-e` / `--exit-status`:207+208+ Sets the exit status of jq to 0 if the last output values was209+ neither `false` nor `null`, 1 if the last output value was210+ either `false` or `null`, or 4 if no valid result was ever211+ produced. Normally jq exits with 2 if there was any usage212+ problem or system error, 3 if there was a jq program compile213+ error, or 0 if the jq program ran.214+215+ Another way to set the exit status is with the `halt_error`216+ builtin function.217+218+ * `--arg name value`:219+220+ This option passes a value to the jq program as a predefined221+ variable. If you run jq with `--arg foo bar`, then `$foo` is222+ available in the program and has the value `"bar"`. Note that223+ `value` will be treated as a string, so `--arg foo 123` will224+ bind `$foo` to `"123"`.225+226+ Named arguments are also available to the jq program as227+ `$ARGS.named`.228+229+ * `--argjson name JSON-text`:230+231+ This option passes a JSON-encoded value to the jq program as a232+ predefined variable. If you run jq with `--argjson foo 123`, then233+ `$foo` is available in the program and has the value `123`.234+235+ * `--slurpfile variable-name filename`:236+237+ This option reads all the JSON texts in the named file and binds238+ an array of the parsed JSON values to the given global variable.239+ If you run jq with `--slurpfile foo bar`, then `$foo` is available240+ in the program and has an array whose elements correspond to the241+ texts in the file named `bar`.242+243+ * `--rawfile variable-name filename`:244+245+ This option reads in the named file and binds its contents to the given246+ global variable. If you run jq with `--rawfile foo bar`, then `$foo` is247+ available in the program and has a string whose contents are to the texs248+ in the file named `bar`.249+250+ * `--argfile variable-name filename`:251+252+ Do not use. Use `--slurpfile` instead.253+254+ (This option is like `--slurpfile`, but when the file has just255+ one text, then that is used, else an array of texts is used as256+ in `--slurpfile`.)257+258+ * `--args`:259+260+ Remaining arguments are positional string arguments. These are261+ available to the jq program as `$ARGS.positional[]`.262+263+ * `--jsonargs`:264+265+ Remaining arguments are positional JSON text arguments. These266+ are available to the jq program as `$ARGS.positional[]`.267+268+ * `--run-tests [filename]`:269+270+ Runs the tests in the given file or standard input. This must271+ be the last option given and does not honor all preceding272+ options. The input consists of comment lines, empty lines, and273+ program lines followed by one input line, as many lines of274+ output as are expected (one per output), and a terminating empty275+ line. Compilation failure tests start with a line containing276+ only "%%FAIL", then a line containing the program to compile,277+ then a line containing an error message to compare to the278+ actual.279+280+ Be warned that this option can change backwards-incompatibly.281+282+ - title: Basic filters283+ entries:284+ - title: "Identity: `.`"285+ body: |286+287+ The absolute simplest filter is `.` . This is a filter that288+ takes its input and produces it unchanged as output. That is,289+ this is the identity operator.290+291+ Since jq by default pretty-prints all output, this trivial292+ program can be a useful way of formatting JSON output from,293+ say, `curl`.294+295+ examples:296+ - program: '.'297+ input: '"Hello, world!"'298+ output: ['"Hello, world!"']299+300+ - title: "Object Identifier-Index: `.foo`, `.foo.bar`"301+ body: |302+303+ The simplest *useful* filter is `.foo`. When given a304+ JSON object (aka dictionary or hash) as input, it produces305+ the value at the key "foo", or null if there's none present.306+307+ A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.308+309+ This syntax only works for simple, identifier-like keys, that310+ is, keys that are all made of alphanumeric characters and311+ underscore, and which do not start with a digit.312+313+ If the key contains special characters, you need to surround314+ it with double quotes like this: `."foo$"`, or else `.["foo$"]`.315+316+ For example `.["foo::bar"]` and `.["foo.bar"]` work while317+ `.foo::bar` does not, and `.foo.bar` means `.["foo"].["bar"]`.318+319+ examples:320+ - program: '.foo'321+ input: '{"foo": 42, "bar": "less interesting data"}'322+ output: [42]323+ - program: '.foo'324+ input: '{"notfoo": true, "alsonotfoo": false}'325+ output: ['null']326+ - program: '.["foo"]'327+ input: '{"foo": 42}'328+ output: [42]329+330+ - title: "Optional Object Identifier-Index: `.foo?`"331+ body: |332+333+ Just like `.foo`, but does not output even an error when `.`334+ is not an array or an object.335+336+ examples:337+ - program: '.foo?'338+ input: '{"foo": 42, "bar": "less interesting data"}'339+ output: [42]340+ - program: '.foo?'341+ input: '{"notfoo": true, "alsonotfoo": false}'342+ output: ['null']343+ - program: '.["foo"]?'344+ input: '{"foo": 42}'345+ output: [42]346+ - program: '[.foo?]'347+ input: '[1,2]'348+ output: ['[]']349+350+ - title: "Generic Object Index: `.[<string>]`"351+ body: |352+353+ You can also look up fields of an object using syntax like354+ `.["foo"]` (.foo above is a shorthand version of this, but355+ only for identifier-like strings).356+357+ - title: "Array Index: `.[2]`"358+ body: |359+360+ When the index value is an integer, `.[<value>]` can index361+ arrays. Arrays are zero-based, so `.[2]` returns the third362+ element.363+364+ Negative indices are allowed, with -1 referring to the last365+ element, -2 referring to the next to last element, and so on.366+367+ examples:368+ - program: '.[0]'369+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'370+ output: ['{"name":"JSON", "good":true}']371+372+ - program: '.[2]'373+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'374+ output: ['null']375+376+ - program: '.[-2]'377+ input: '[1,2,3]'378+ output: ['2']379+380+ - title: "Array/String Slice: `.[10:15]`"381+ body: |382+383+ The `.[10:15]` syntax can be used to return a subarray of an384+ array or substring of a string. The array returned by385+ `.[10:15]` will be of length 5, containing the elements from386+ index 10 (inclusive) to index 15 (exclusive). Either index may387+ be negative (in which case it counts backwards from the end of388+ the array), or omitted (in which case it refers to the start389+ or end of the array).390+391+ examples:392+ - program: '.[2:4]'393+ input: '["a","b","c","d","e"]'394+ output: ['["c", "d"]']395+396+ - program: '.[2:4]'397+ input: '"abcdefghi"'398+ output: ['"cd"']399+400+ - program: '.[:3]'401+ input: '["a","b","c","d","e"]'402+ output: ['["a", "b", "c"]']403+404+ - program: '.[-2:]'405+ input: '["a","b","c","d","e"]'406+ output: ['["d", "e"]']407+408+ - title: "Array/Object Value Iterator: `.[]`"409+ body: |410+411+ If you use the `.[index]` syntax, but omit the index412+ entirely, it will return *all* of the elements of an413+ array. Running `.[]` with the input `[1,2,3]` will produce the414+ numbers as three separate results, rather than as a single415+ array.416+417+ You can also use this on an object, and it will return all418+ the values of the object.419+420+ examples:421+ - program: '.[]'422+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'423+ output:424+ - '{"name":"JSON", "good":true}'425+ - '{"name":"XML", "good":false}'426+427+ - program: '.[]'428+ input: '[]'429+ output: []430+431+ - program: '.[]'432+ input: '{"a": 1, "b": 1}'433+ output: ['1', '1']434+435+ - title: "`.[]?`"436+ body: |437+438+ Like `.[]`, but no errors will be output if . is not an array439+ or object.440+441+ - title: "Comma: `,`"442+ body: |443+444+ If two filters are separated by a comma, then the445+ same input will be fed into both and the two filters' output446+ value streams will be concatenated in order: first, all of the447+ outputs produced by the left expression, and then all of the448+ outputs produced by the right. For instance, filter `.foo,449+ .bar`, produces both the "foo" fields and "bar" fields as450+ separate outputs.451+452+ examples:453+ - program: '.foo, .bar'454+ input: '{"foo": 42, "bar": "something else", "baz": true}'455+ output: ['42', '"something else"']456+457+ - program: ".user, .projects[]"458+ input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'459+ output: ['"stedolan"', '"jq"', '"wikiflow"']460+461+ - program: '.[4,2]'462+ input: '["a","b","c","d","e"]'463+ output: ['"e"', '"c"']464+465+ - title: "Pipe: `|`"466+ body: |467+468+ The | operator combines two filters by feeding the output(s) of469+ the one on the left into the input of the one on the right. It's470+ pretty much the same as the Unix shell's pipe, if you're used to471+ that.472+473+ If the one on the left produces multiple results, the one on474+ the right will be run for each of those results. So, the475+ expression `.[] | .foo` retrieves the "foo" field of each476+ element of the input array.477+478+ Note that `.a.b.c` is the same as `.a | .b | .c`.479+480+ Note too that `.` is the input value at the particular stage481+ in a "pipeline", specifically: where the `.` expression appears.482+ Thus `.a | . | .b` is the same as `.a.b`, as the `.` in the483+ middle refers to whatever value `.a` produced.484+485+ examples:486+ - program: '.[] | .name'487+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'488+ output: ['"JSON"', '"XML"']489+490+ - title: "Parenthesis"491+ body: |492+493+ Parenthesis work as a grouping operator just as in any typical494+ programming language.495+496+ examples:497+ - program: '(. + 2) * 5'498+ input: '1'499+ output: [15]500+501+ - title: Types and Values502+ body: |503+504+ jq supports the same set of datatypes as JSON - numbers,505+ strings, booleans, arrays, objects (which in JSON-speak are506+ hashes with only string keys), and "null".507+508+ Booleans, null, strings and numbers are written the same way as509+ in javascript. Just like everything else in jq, these simple510+ values take an input and produce an output - `42` is a valid jq511+ expression that takes an input, ignores it, and returns 42512+ instead.513+514+ entries:515+ - title: "Array construction: `[]`"516+ body: |517+518+ As in JSON, `[]` is used to construct arrays, as in519+ `[1,2,3]`. The elements of the arrays can be any jq520+ expression, including a pipeline. All of the results produced521+ by all of the expressions are collected into one big array.522+ You can use it to construct an array out of a known quantity523+ of values (as in `[.foo, .bar, .baz]`) or to "collect" all the524+ results of a filter into an array (as in `[.items[].name]`)525+526+ Once you understand the "," operator, you can look at jq's array527+ syntax in a different light: the expression `[1,2,3]` is not using a528+ built-in syntax for comma-separated arrays, but is instead applying529+ the `[]` operator (collect results) to the expression 1,2,3 (which530+ produces three different results).531+532+ If you have a filter `X` that produces four results,533+ then the expression `[X]` will produce a single result, an534+ array of four elements.535+536+ examples:537+ - program: "[.user, .projects[]]"538+ input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'539+ output: ['["stedolan", "jq", "wikiflow"]']540+ - program: "[ .[] | . * 2]"541+ input: '[1, 2, 3]'542+ output: ['[2, 4, 6]']543+544+ - title: "Object Construction: `{}`"545+ body: |546+547+ Like JSON, `{}` is for constructing objects (aka548+ dictionaries or hashes), as in: `{"a": 42, "b": 17}`.549+550+ If the keys are "identifier-like", then the quotes can be left551+ off, as in `{a:42, b:17}`. Keys generated by expressions need552+ to be parenthesized, e.g., `{("a"+"b"):59}`.553+554+ The value can be any expression (although you may need to555+ wrap it in parentheses if it's a complicated one), which gets556+ applied to the {} expression's input (remember, all filters557+ have an input and an output).558+559+ {foo: .bar}560+561+ will produce the JSON object `{"foo": 42}` if given the JSON562+ object `{"bar":42, "baz":43}` as its input. You can use this563+ to select particular fields of an object: if the input is an564+ object with "user", "title", "id", and "content" fields and565+ you just want "user" and "title", you can write566+567+ {user: .user, title: .title}568+569+ Because that is so common, there's a shortcut syntax for it:570+ `{user, title}`.571+572+ If one of the expressions produces multiple results,573+ multiple dictionaries will be produced. If the input's574+575+ {"user":"stedolan","titles":["JQ Primer", "More JQ"]}576+577+ then the expression578+579+ {user, title: .titles[]}580+581+ will produce two outputs:582+583+ {"user":"stedolan", "title": "JQ Primer"}584+ {"user":"stedolan", "title": "More JQ"}585+586+ Putting parentheses around the key means it will be evaluated as an587+ expression. With the same input as above,588+589+ {(.user): .titles}590+591+ produces592+593+ {"stedolan": ["JQ Primer", "More JQ"]}594+595+ examples:596+ - program: '{user, title: .titles[]}'597+ input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'598+ output:599+ - '{"user":"stedolan", "title": "JQ Primer"}'600+ - '{"user":"stedolan", "title": "More JQ"}'601+ - program: '{(.user): .titles}'602+ input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'603+ output: ['{"stedolan": ["JQ Primer", "More JQ"]}']604+605+ - title: "Recursive Descent: `..`"606+ body: |607+608+ Recursively descends `.`, producing every value. This is the609+ same as the zero-argument `recurse` builtin (see below). This610+ is intended to resemble the XPath `//` operator. Note that611+ `..a` does not work; use `..|.a` instead. In the example612+ below we use `..|.a?` to find all the values of object keys613+ "a" in any object found "below" `.`.614+615+ This is particularly useful in conjunction with `path(EXP)`616+ (also see below) and the `?` operator.617+618+ examples:619+ - program: '..|.a?'620+ input: '[[{"a":1}]]'621+ output: ['1']622+623+ - title: Builtin operators and functions624+ body: |625+626+ Some jq operators (for instance, `+`) do different things627+ depending on the type of their arguments (arrays, numbers,628+ etc.). However, jq never does implicit type conversions. If you629+ try to add a string to an object you'll get an error message and630+ no result.631+632+ entries:633+ - title: "Addition: `+`"634+ body: |635+636+ The operator `+` takes two filters, applies them both637+ to the same input, and adds the results together. What638+ "adding" means depends on the types involved:639+640+ - **Numbers** are added by normal arithmetic.641+642+ - **Arrays** are added by being concatenated into a larger array.643+644+ - **Strings** are added by being joined into a larger string.645+646+ - **Objects** are added by merging, that is, inserting all647+ the key-value pairs from both objects into a single648+ combined object. If both objects contain a value for the649+ same key, the object on the right of the `+` wins. (For650+ recursive merge use the `*` operator.)651+652+ `null` can be added to any value, and returns the other653+ value unchanged.654+655+ examples:656+ - program: '.a + 1'657+ input: '{"a": 7}'658+ output: ['8']659+ - program: '.a + .b'660+ input: '{"a": [1,2], "b": [3,4]}'661+ output: ['[1,2,3,4]']662+ - program: '.a + null'663+ input: '{"a": 1}'664+ output: ['1']665+ - program: '.a + 1'666+ input: '{}'667+ output: ['1']668+ - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'669+ input: 'null'670+ output: ['{"a": 42, "b": 2, "c": 3}']671+672+ - title: "Subtraction: `-`"673+ body: |674+675+ As well as normal arithmetic subtraction on numbers, the `-`676+ operator can be used on arrays to remove all occurrences of677+ the second array's elements from the first array.678+679+ examples:680+ - program: '4 - .a'681+ input: '{"a":3}'682+ output: ['1']683+ - program: . - ["xml", "yaml"]684+ input: '["xml", "yaml", "json"]'685+ output: ['["json"]']686+687+ - title: "Multiplication, division, modulo: `*`, `/`, and `%`"688+ body: |689+690+ These infix operators behave as expected when given two numbers.691+ Division by zero raises an error. `x % y` computes x modulo y.692+693+ Multiplying a string by a number produces the concatenation of694+ that string that many times. `"x" * 0` produces **null**.695+696+ Dividing a string by another splits the first using the second697+ as separators.698+699+ Multiplying two objects will merge them recursively: this works700+ like addition but if both objects contain a value for the701+ same key, and the values are objects, the two are merged with702+ the same strategy.703+704+ examples:705+ - program: '10 / . * 3'706+ input: 5707+ output: [6]708+ - program: '. / ", "'709+ input: '"a, b,c,d, e"'710+ output: ['["a","b,c,d","e"]']711+ - program: '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'712+ input: 'null'713+ output: ['{"k": {"a": 0, "b": 2, "c": 3}}']714+ - program: '.[] | (1 / .)?'715+ input: '[1,0,-1]'716+ output: ['1', '-1']717+718+719+ - title: "`length`"720+ body: |721+722+ The builtin function `length` gets the length of various723+ different types of value:724+725+ - The length of a **string** is the number of Unicode726+ codepoints it contains (which will be the same as its727+ JSON-encoded length in bytes if it's pure ASCII).728+729+ - The length of an **array** is the number of elements.730+731+ - The length of an **object** is the number of key-value pairs.732+733+ - The length of **null** is zero.734+735+ examples:736+ - program: '.[] | length'737+ input: '[[1,2], "string", {"a":2}, null]'738+ output: [2, 6, 1, 0]739+740+741+ - title: "`utf8bytelength`"742+ body: |743+744+ The builtin function `utf8bytelength` outputs the number of745+ bytes used to encode a string in UTF-8.746+747+ examples:748+ - program: 'utf8bytelength'749+ input: '"\u03bc"'750+ output: [2]751+752+ - title: "`keys`, `keys_unsorted`"753+ body: |754+755+ The builtin function `keys`, when given an object, returns756+ its keys in an array.757+758+ The keys are sorted "alphabetically", by unicode codepoint759+ order. This is not an order that makes particular sense in760+ any particular language, but you can count on it being the761+ same for any two objects with the same set of keys,762+ regardless of locale settings.763+764+ When `keys` is given an array, it returns the valid indices765+ for that array: the integers from 0 to length-1.766+767+ The `keys_unsorted` function is just like `keys`, but if768+ the input is an object then the keys will not be sorted,769+ instead the keys will roughly be in insertion order.770+771+ examples:772+ - program: 'keys'773+ input: '{"abc": 1, "abcd": 2, "Foo": 3}'774+ output: ['["Foo", "abc", "abcd"]']775+ - program: 'keys'776+ input: '[42,3,35]'777+ output: ['[0,1,2]']778+779+ - title: "`has(key)`"780+ body: |781+782+ The builtin function `has` returns whether the input object783+ has the given key, or the input array has an element at the784+ given index.785+786+ `has($key)` has the same effect as checking whether `$key`787+ is a member of the array returned by `keys`, although `has`788+ will be faster.789+790+ examples:791+ - program: 'map(has("foo"))'792+ input: '[{"foo": 42}, {}]'793+ output: ['[true, false]']794+ - program: 'map(has(2))'795+ input: '[[0,1], ["a","b","c"]]'796+ output: ['[false, true]']797+798+ - title: "`in`"799+ body: |800+801+ The builtin function `in` returns whether or not the input key is in the802+ given object, or the input index corresponds to an element803+ in the given array. It is, essentially, an inversed version804+ of `has`.805+806+ examples:807+ - program: '.[] | in({"foo": 42})'808+ input: '["foo", "bar"]'809+ output: ['true', 'false']810+ - program: 'map(in([0,1]))'811+ input: '[2, 0]'812+ output: ['[false, true]']813+814+ - title: "`map(x)`, `map_values(x)`"815+ body: |816+817+ For any filter `x`, `map(x)` will run that filter for each818+ element of the input array, and return the outputs in a new819+ array. `map(.+1)` will increment each element of an array of numbers.820+821+ Similarly, `map_values(x)` will run that filter for each element,822+ but it will return an object when an object is passed.823+824+ `map(x)` is equivalent to `[.[] | x]`. In fact, this is how825+ it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`.826+827+ examples:828+ - program: 'map(.+1)'829+ input: '[1,2,3]'830+ output: ['[2,3,4]']831+832+ - program: 'map_values(.+1)'833+ input: '{"a": 1, "b": 2, "c": 3}'834+ output: ['{"a": 2, "b": 3, "c": 4}']835+836+ - title: "`path(path_expression)`"837+ body: |838+839+ Outputs array representations of the given path expression840+ in `.`. The outputs are arrays of strings (object keys)841+ and/or numbers (array indices).842+843+ Path expressions are jq expressions like `.a`, but also `.[]`.844+ There are two types of path expressions: ones that can match845+ exactly, and ones that cannot. For example, `.a.b.c` is an846+ exact match path expression, while `.a[].b` is not.847+848+ `path(exact_path_expression)` will produce the array849+ representation of the path expression even if it does not850+ exist in `.`, if `.` is `null` or an array or an object.851+852+ `path(pattern)` will produce array representations of the853+ paths matching `pattern` if the paths exist in `.`.854+855+ Note that the path expressions are not different from normal856+ expressions. The expression857+ `path(..|select(type=="boolean"))` outputs all the paths to858+ boolean values in `.`, and only those paths.859+860+ examples:861+ - program: 'path(.a[0].b)'862+ input: 'null'863+ output: ['["a",0,"b"]']864+ - program: '[path(..)]'865+ input: '{"a":[{"b":1}]}'866+ output: ['[[],["a"],["a",0],["a",0,"b"]]']867+868+ - title: "`del(path_expression)`"869+ body: |870+871+ The builtin function `del` removes a key and its corresponding872+ value from an object.873+874+ examples:875+ - program: 'del(.foo)'876+ input: '{"foo": 42, "bar": 9001, "baz": 42}'877+ output: ['{"bar": 9001, "baz": 42}']878+ - program: 'del(.[1, 2])'879+ input: '["foo", "bar", "baz"]'880+ output: ['["foo"]']881+882+ - title: "`getpath(PATHS)`"883+ body: |884+885+ The builtin function `getpath` outputs the values in `.` found886+ at each path in `PATHS`.887+888+ examples:889+ - program: 'getpath(["a","b"])'890+ input: 'null'891+ output: ['null']892+ - program: '[getpath(["a","b"], ["a","c"])]'893+ input: '{"a":{"b":0, "c":1}}'894+ output: ['[0, 1]']895+896+ - title: "`setpath(PATHS; VALUE)`"897+ body: |898+899+ The builtin function `setpath` sets the `PATHS` in `.` to `VALUE`.900+901+ examples:902+ - program: 'setpath(["a","b"]; 1)'903+ input: 'null'904+ output: ['{"a": {"b": 1}}']905+ - program: 'setpath(["a","b"]; 1)'906+ input: '{"a":{"b":0}}'907+ output: ['{"a": {"b": 1}}']908+ - program: 'setpath([0,"a"]; 1)'909+ input: 'null'910+ output: ['[{"a":1}]']911+912+ - title: "`delpaths(PATHS)`"913+ body: |914+915+ The builtin function `delpaths` sets the `PATHS` in `.`.916+ `PATHS` must be an array of paths, where each path is an array917+ of strings and numbers.918+919+ examples:920+ - program: 'delpaths([["a","b"]])'921+ input: '{"a":{"b":1},"x":{"y":2}}'922+ output: ['{"a":{},"x":{"y":2}}']923+924+ - title: "`to_entries`, `from_entries`, `with_entries`"925+ body: |926+927+ These functions convert between an object and an array of928+ key-value pairs. If `to_entries` is passed an object, then929+ for each `k: v` entry in the input, the output array930+ includes `{"key": k, "value": v}`.931+932+ `from_entries` does the opposite conversion, and933+ `with_entries(foo)` is a shorthand for `to_entries |934+ map(foo) | from_entries`, useful for doing some operation to935+ all keys and values of an object. `from_entries` accepts key, Key,936+ name, Name, value and Value as keys.937+938+ examples:939+ - program: 'to_entries'940+ input: '{"a": 1, "b": 2}'941+ output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']942+ - program: 'from_entries'943+ input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'944+ output: ['{"a": 1, "b": 2}']945+ - program: 'with_entries(.key |= "KEY_" + .)'946+ input: '{"a": 1, "b": 2}'947+ output: ['{"KEY_a": 1, "KEY_b": 2}']948+949+950+ - title: "`select(boolean_expression)`"951+ body: |952+953+ The function `select(foo)` produces its input unchanged if954+ `foo` returns true for that input, and produces no output955+ otherwise.956+957+ It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`958+ will give you `[2,3]`.959+960+ examples:961+ - program: 'map(select(. >= 2))'962+ input: '[1,5,3,0,7]'963+ output: ['[5,3,7]']964+ - program: '.[] | select(.id == "second")'965+ input: '[{"id": "first", "val": 1}, {"id": "second", "val": 2}]'966+ output: ['{"id": "second", "val": 2}']967+968+969+ - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"970+ body: |971+972+ These built-ins select only inputs that are arrays, objects,973+ iterables (arrays or objects), booleans, numbers, normal974+ numbers, finite numbers, strings, null, non-null values, and975+ non-iterables, respectively.976+977+ examples:978+ - program: '.[]|numbers'979+ input: '[[],{},1,"foo",null,true,false]'980+ output: ['1']981+982+ - title: "`empty`"983+ body: |984+985+ `empty` returns no results. None at all. Not even `null`.986+987+ It's useful on occasion. You'll know if you need it :)988+989+ examples:990+ - program: '1, empty, 2'991+ input: 'null'992+ output: [1, 2]993+ - program: '[1,2,empty,3]'994+ input: 'null'995+ output: ['[1,2,3]']996+997+ - title: "`error(message)`"998+ body: |999+1000+ Produces an error, just like `.a` applied to values other than1001+ null and objects would, but with the given message as the1002+ error's value. Errors can be caught with try/catch; see below.1003+1004+ - title: "`halt`"1005+ body: |1006+1007+ Stops the jq program with no further outputs. jq will exit1008+ with exit status `0`.1009+1010+ - title: "`halt_error`, `halt_error(exit_code)`"1011+ body: |1012+1013+ Stops the jq program with no further outputs. The input will1014+ be printed on `stderr` as raw output (i.e., strings will not1015+ have double quotes) with no decoration, not even a newline.1016+1017+ The given `exit_code` (defaulting to `5`) will be jq's exit1018+ status.1019+1020+ For example, `"Error: somthing went wrong\n"|halt_error(1)`.1021+1022+ - title: "`$__loc__`"1023+ body: |1024+1025+ Produces an object with a "file" key and a "line" key, with1026+ the filename and line number where `$__loc__` occurs, as1027+ values.1028+1029+ examples:1030+ - program: 'try error("\($__loc__)") catch .'1031+ input: 'null'1032+ output: ['"{\"file\":\"<top-level>\",\"line\":1}"']1033+1034+ - title: "`paths`, `paths(node_filter)`, `leaf_paths`"1035+ body: |1036+1037+ `paths` outputs the paths to all the elements in its input1038+ (except it does not output the empty list, representing .1039+ itself).1040+1041+ `paths(f)` outputs the paths to any values for which `f` is true.1042+ That is, `paths(numbers)` outputs the paths to all numeric1043+ values.1044+1045+ `leaf_paths` is an alias of `paths(scalars)`; `leaf_paths` is1046+ *deprecated* and will be removed in the next major release.1047+1048+ examples:1049+ - program: '[paths]'1050+ input: '[1,[[],{"a":2}]]'1051+ output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']1052+ - program: '[paths(scalars)]'1053+ input: '[1,[[],{"a":2}]]'1054+ output: ['[[0],[1,1,"a"]]']1055+1056+ - title: "`add`"1057+ body: |1058+1059+ The filter `add` takes as input an array, and produces as1060+ output the elements of the array added together. This might1061+ mean summed, concatenated or merged depending on the types1062+ of the elements of the input array - the rules are the same1063+ as those for the `+` operator (described above).1064+1065+ If the input is an empty array, `add` returns `null`.1066+1067+ examples:1068+ - program: add1069+ input: '["a","b","c"]'1070+ output: ['"abc"']1071+ - program: add1072+ input: '[1, 2, 3]'1073+ output: [6]1074+ - program: add1075+ input: '[]'1076+ output: ["null"]1077+1078+ - title: "`any`, `any(condition)`, `any(generator; condition)`"1079+ body: |1080+1081+ The filter `any` takes as input an array of boolean values,1082+ and produces `true` as output if any of the elements of1083+ the array are `true`.1084+1085+ If the input is an empty array, `any` returns `false`.1086+1087+ The `any(condition)` form applies the given condition to the1088+ elements of the input array.1089+1090+ The `any(generator; condition)` form applies the given1091+ condition to all the outputs of the given generator.1092+1093+ examples:1094+ - program: any1095+ input: '[true, false]'1096+ output: ["true"]1097+ - program: any1098+ input: '[false, false]'1099+ output: ["false"]1100+ - program: any1101+ input: '[]'1102+ output: ["false"]1103+1104+ - title: "`all`, `all(condition)`, `all(generator; condition)`"1105+ body: |1106+1107+ The filter `all` takes as input an array of boolean values,1108+ and produces `true` as output if all of the elements of1109+ the array are `true`.1110+1111+ The `all(condition)` form applies the given condition to the1112+ elements of the input array.1113+1114+ The `all(generator; condition)` form applies the given1115+ condition to all the outputs of the given generator.1116+1117+ If the input is an empty array, `all` returns `true`.1118+1119+ examples:1120+ - program: all1121+ input: '[true, false]'1122+ output: ["false"]1123+ - program: all1124+ input: '[true, true]'1125+ output: ["true"]1126+ - program: all1127+ input: '[]'1128+ output: ["true"]1129+1130+ - title: "`flatten`, `flatten(depth)`"1131+ body: |1132+1133+ The filter `flatten` takes as input an array of nested arrays,1134+ and produces a flat array in which all arrays inside the original1135+ array have been recursively replaced by their values. You can pass1136+ an argument to it to specify how many levels of nesting to flatten.1137+1138+ `flatten(2)` is like `flatten`, but going only up to two1139+ levels deep.1140+1141+ examples:1142+ - program: flatten1143+ input: '[1, [2], [[3]]]'1144+ output: ["[1, 2, 3]"]1145+ - program: flatten(1)1146+ input: '[1, [2], [[3]]]'1147+ output: ["[1, 2, [3]]"]1148+ - program: flatten1149+ input: '[[]]'1150+ output: ["[]"]1151+ - program: flatten1152+ input: '[{"foo": "bar"}, [{"foo": "baz"}]]'1153+ output: ['[{"foo": "bar"}, {"foo": "baz"}]']1154+1155+ - title: "`range(upto)`, `range(from;upto)` `range(from;upto;by)`"1156+ body: |1157+1158+ The `range` function produces a range of numbers. `range(4;10)`1159+ produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers1160+ are produced as separate outputs. Use `[range(4;10)]` to get a range as1161+ an array.1162+1163+ The one argument form generates numbers from 0 to the given1164+ number, with an increment of 1.1165+1166+ The two argument form generates numbers from `from` to `upto`1167+ with an increment of 1.1168+1169+ The three argument form generates numbers `from` to `upto`1170+ with an increment of `by`.1171+1172+ examples:1173+ - program: 'range(2;4)'1174+ input: 'null'1175+ output: ['2', '3']1176+ - program: '[range(2;4)]'1177+ input: 'null'1178+ output: ['[2,3]']1179+ - program: '[range(4)]'1180+ input: 'null'1181+ output: ['[0,1,2,3]']1182+ - program: '[range(0;10;3)]'1183+ input: 'null'1184+ output: ['[0,3,6,9]']1185+ - program: '[range(0;10;-1)]'1186+ input: 'null'1187+ output: ['[]']1188+ - program: '[range(0;-5;-1)]'1189+ input: 'null'1190+ output: ['[0,-1,-2,-3,-4]']1191+1192+ - title: "`floor`"1193+ body: |1194+1195+ The `floor` function returns the floor of its numeric input.1196+1197+ examples:1198+ - program: 'floor'1199+ input: '3.14159'1200+ output: ['3']1201+1202+ - title: "`sqrt`"1203+ body: |1204+1205+ The `sqrt` function returns the square root of its numeric input.1206+1207+ examples:1208+ - program: 'sqrt'1209+ input: '9'1210+ output: ['3']1211+1212+ - title: "`tonumber`"1213+ body: |1214+1215+ The `tonumber` function parses its input as a number. It1216+ will convert correctly-formatted strings to their numeric1217+ equivalent, leave numbers alone, and give an error on all other input.1218+1219+ examples:1220+ - program: '.[] | tonumber'1221+ input: '[1, "1"]'1222+ output: [1, 1]1223+1224+ - title: "`tostring`"1225+ body: |1226+1227+ The `tostring` function prints its input as a1228+ string. Strings are left unchanged, and all other values are1229+ JSON-encoded.1230+1231+ examples:1232+ - program: '.[] | tostring'1233+ input: '[1, "1", [1]]'1234+ output: ['"1"', '"1"', '"[1]"']1235+1236+ - title: "`type`"1237+ body: |1238+1239+ The `type` function returns the type of its argument as a1240+ string, which is one of null, boolean, number, string, array1241+ or object.1242+1243+ examples:1244+ - program: 'map(type)'1245+ input: '[0, false, [], {}, null, "hello"]'1246+ output: ['["number", "boolean", "array", "object", "null", "string"]']1247+1248+ - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1249+ body: |1250+1251+ Some arithmetic operations can yield infinities and "not a1252+ number" (NaN) values. The `isinfinite` builtin returns `true`1253+ if its input is infinite. The `isnan` builtin returns `true`1254+ if its input is a NaN. The `infinite` builtin returns a1255+ positive infinite value. The `nan` builtin returns a NaN.1256+ The `isnormal` builtin returns true if its input is a normal1257+ number.1258+1259+ Note that division by zero raises an error.1260+1261+ Currently most arithmetic operations operating on infinities,1262+ NaNs, and sub-normals do not raise errors.1263+1264+ examples:1265+ - program: '.[] | (infinite * .) < 0'1266+ input: '[-1, 1]'1267+ output: ['true', 'false']1268+ - program: 'infinite, nan | type'1269+ input: 'null'1270+ output: ['"number"', '"number"']1271+1272+ - title: "`sort, sort_by(path_expression)`"1273+ body: |1274+1275+ The `sort` functions sorts its input, which must be an1276+ array. Values are sorted in the following order:1277+1278+ * `null`1279+ * `false`1280+ * `true`1281+ * numbers1282+ * strings, in alphabetical order (by unicode codepoint value)1283+ * arrays, in lexical order1284+ * objects1285+1286+ The ordering for objects is a little complex: first they're1287+ compared by comparing their sets of keys (as arrays in1288+ sorted order), and if their keys are equal then the values1289+ are compared key by key.1290+1291+ `sort` may be used to sort by a particular field of an1292+ object, or by applying any jq filter.1293+1294+ `sort_by(foo)` compares two elements by comparing the result of1295+ `foo` on each element.1296+1297+ examples:1298+ - program: 'sort'1299+ input: '[8,3,null,6]'1300+ output: ['[null,3,6,8]']1301+ - program: 'sort_by(.foo)'1302+ input: '[{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}]'1303+ output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']1304+1305+ - title: "`group_by(path_expression)`"1306+ body: |1307+1308+ `group_by(.foo)` takes as input an array, groups the1309+ elements having the same `.foo` field into separate arrays,1310+ and produces all of these arrays as elements of a larger1311+ array, sorted by the value of the `.foo` field.1312+1313+ Any jq expression, not just a field access, may be used in1314+ place of `.foo`. The sorting order is the same as described1315+ in the `sort` function above.1316+1317+ examples:1318+ - program: 'group_by(.foo)'1319+ input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'1320+ output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']1321+1322+ - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1323+ body: |1324+1325+ Find the minimum or maximum element of the input array.1326+1327+ The `min_by(path_exp)` and `max_by(path_exp)` functions allow1328+ you to specify a particular field or property to examine, e.g.1329+ `min_by(.foo)` finds the object with the smallest `foo` field.1330+1331+ examples:1332+ - program: 'min'1333+ input: '[5,4,2,7]'1334+ output: ['2']1335+ - program: 'max_by(.foo)'1336+ input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'1337+ output: ['{"foo":2, "bar":3}']1338+1339+ - title: "`unique`, `unique_by(path_exp)`"1340+ body: |1341+1342+ The `unique` function takes as input an array and produces1343+ an array of the same elements, in sorted order, with1344+ duplicates removed.1345+1346+ The `unique_by(path_exp)` function will keep only one element1347+ for each value obtained by applying the argument. Think of it1348+ as making an array by taking one element out of every group1349+ produced by `group`.1350+1351+ examples:1352+ - program: 'unique'1353+ input: '[1,2,5,3,5,3,1,3]'1354+ output: ['[1,2,3,5]']1355+ - program: 'unique_by(.foo)'1356+ input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'1357+ output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']1358+ - program: 'unique_by(length)'1359+ input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'1360+ output: ['["bacon", "chunky", "asparagus"]']1361+1362+ - title: "`reverse`"1363+ body: |1364+1365+ This function reverses an array.1366+1367+ examples:1368+ - program: 'reverse'1369+ input: '[1,2,3,4]'1370+ output: ['[4,3,2,1]']1371+1372+ - title: "`contains(element)`"1373+ body: |1374+1375+ The filter `contains(b)` will produce true if b is1376+ completely contained within the input. A string B is1377+ contained in a string A if B is a substring of A. An array B1378+ is contained in an array A if all elements in B are1379+ contained in any element in A. An object B is contained in1380+ object A if all of the values in B are contained in the1381+ value in A with the same key. All other types are assumed to1382+ be contained in each other if they are equal.1383+1384+ examples:1385+ - program: 'contains("bar")'1386+ input: '"foobar"'1387+ output: ['true']1388+ - program: 'contains(["baz", "bar"])'1389+ input: '["foobar", "foobaz", "blarp"]'1390+ output: ['true']1391+ - program: 'contains(["bazzzzz", "bar"])'1392+ input: '["foobar", "foobaz", "blarp"]'1393+ output: ['false']1394+ - program: 'contains({foo: 12, bar: [{barp: 12}]})'1395+ input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1396+ output: ['true']1397+ - program: 'contains({foo: 12, bar: [{barp: 15}]})'1398+ input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1399+ output: ['false']1400+1401+ - title: "`indices(s)`"1402+ body: |1403+1404+ Outputs an array containing the indices in `.` where `s`1405+ occurs. The input may be an array, in which case if `s` is an1406+ array then the indices output will be those where all elements1407+ in `.` match those of `s`.1408+1409+ examples:1410+ - program: 'indices(", ")'1411+ input: '"a,b, cd, efg, hijk"'1412+ output: ['[3,7,12]']1413+ - program: 'indices(1)'1414+ input: '[0,1,2,1,3,1,4]'1415+ output: ['[1,3,5]']1416+ - program: 'indices([1,2])'1417+ input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1418+ output: ['[1,8]']1419+1420+ - title: "`index(s)`, `rindex(s)`"1421+ body: |1422+1423+ Outputs the index of the first (`index`) or last (`rindex`)1424+ occurrence of `s` in the input.1425+1426+ examples:1427+ - program: 'index(", ")'1428+ input: '"a,b, cd, efg, hijk"'1429+ output: ['3']1430+ - program: 'rindex(", ")'1431+ input: '"a,b, cd, efg, hijk"'1432+ output: ['12']1433+1434+ - title: "`inside`"1435+ body: |1436+1437+ The filter `inside(b)` will produce true if the input is1438+ completely contained within b. It is, essentially, an1439+ inversed version of `contains`.1440+1441+ examples:1442+ - program: 'inside("foobar")'1443+ input: '"bar"'1444+ output: ['true']1445+ - program: 'inside(["foobar", "foobaz", "blarp"])'1446+ input: '["baz", "bar"]'1447+ output: ['true']1448+ - program: 'inside(["foobar", "foobaz", "blarp"])'1449+ input: '["bazzzzz", "bar"]'1450+ output: ['false']1451+ - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1452+ input: '{"foo": 12, "bar": [{"barp": 12}]}'1453+ output: ['true']1454+ - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1455+ input: '{"foo": 12, "bar": [{"barp": 15}]}'1456+ output: ['false']1457+1458+ - title: "`startswith(str)`"1459+ body: |1460+1461+ Outputs `true` if . starts with the given string argument.1462+1463+ examples:1464+ - program: '[.[]|startswith("foo")]'1465+ input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1466+ output: ['[false, true, false, true, false]']1467+1468+ - title: "`endswith(str)`"1469+ body: |1470+1471+ Outputs `true` if . ends with the given string argument.1472+1473+ examples:1474+ - program: '[.[]|endswith("foo")]'1475+ input: '["foobar", "barfoo"]'1476+ output: ['[false, true]']1477+1478+ - title: "`combinations`, `combinations(n)`"1479+ body: |1480+1481+ Outputs all combinations of the elements of the arrays in the1482+ input array. If given an argument `n`, it outputs all combinations1483+ of `n` repetitions of the input array.1484+1485+ examples:1486+ - program: 'combinations'1487+ input: '[[1,2], [3, 4]]'1488+ output: ['[1, 3]', '[1, 4]', '[2, 3]', '[2, 4]']1489+ - program: 'combinations(2)'1490+ input: '[0, 1]'1491+ output: ['[0, 0]', '[0, 1]', '[1, 0]', '[1, 1]']1492+1493+ - title: "`ltrimstr(str)`"1494+ body: |1495+1496+ Outputs its input with the given prefix string removed, if it1497+ starts with it.1498+1499+ examples:1500+ - program: '[.[]|ltrimstr("foo")]'1501+ input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1502+ output: ['["fo","","barfoo","bar","afoo"]']1503+1504+ - title: "`rtrimstr(str)`"1505+ body: |1506+1507+ Outputs its input with the given suffix string removed, if it1508+ ends with it.1509+1510+ examples:1511+ - program: '[.[]|rtrimstr("foo")]'1512+ input: '["fo", "foo", "barfoo", "foobar", "foob"]'1513+ output: ['["fo","","bar","foobar","foob"]']1514+1515+ - title: "`explode`"1516+ body: |1517+1518+ Converts an input string into an array of the string's1519+ codepoint numbers.1520+1521+ examples:1522+ - program: 'explode'1523+ input: '"foobar"'1524+ output: ['[102,111,111,98,97,114]']1525+1526+ - title: "`implode`"1527+ body: |1528+1529+ The inverse of explode.1530+1531+ examples:1532+ - program: 'implode'1533+ input: '[65, 66, 67]'1534+ output: ['"ABC"']1535+1536+ - title: "`split(str)`"1537+ body: |1538+1539+ Splits an input string on the separator argument.1540+1541+ examples:1542+ - program: 'split(", ")'1543+ input: '"a, b,c,d, e, "'1544+ output: ['["a","b,c,d","e",""]']1545+1546+ - title: "`join(str)`"1547+ body: |1548+1549+ Joins the array of elements given as input, using the1550+ argument as separator. It is the inverse of `split`: that is,1551+ running `split("foo") | join("foo")` over any input string1552+ returns said input string.1553+1554+ Numbers and booleans in the input are converted to strings.1555+ Null values are treated as empty strings. Arrays and objects1556+ in the input are not supported.1557+1558+ examples:1559+ - program: 'join(", ")'1560+ input: '["a","b,c,d","e"]'1561+ output: ['"a, b,c,d, e"']1562+ - program: 'join(" ")'1563+ input: '["a",1,2.3,true,null,false]'1564+ output: ['"a 1 2.3 true false"']1565+1566+ - title: "`ascii_downcase`, `ascii_upcase`"1567+ body: |1568+1569+ Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1570+ converted to the specified case.1571+1572+ example:1573+ - program: 'ascii_upcase'1574+ input: '"useful but not for é"'1575+ output: '"USEFUL BUT NOT FOR é"'1576+1577+ - title: "`while(cond; update)`"1578+ body: |1579+1580+ The `while(cond; update)` function allows you to repeatedly1581+ apply an update to `.` until `cond` is false.1582+1583+ Note that `while(cond; update)` is internally defined as a1584+ recursive jq function. Recursive calls within `while` will1585+ not consume additional memory if `update` produces at most one1586+ output for each input. See advanced topics below.1587+1588+ examples:1589+ - program: '[while(.<100; .*2)]'1590+ input: '1'1591+ output: ['[1,2,4,8,16,32,64]']1592+1593+ - title: "`until(cond; next)`"1594+ body: |1595+1596+ The `until(cond; next)` function allows you to repeatedly1597+ apply the expression `next`, initially to `.` then to its own1598+ output, until `cond` is true. For example, this can be used1599+ to implement a factorial function (see below).1600+1601+ Note that `until(cond; next)` is internally defined as a1602+ recursive jq function. Recursive calls within `until()` will1603+ not consume additional memory if `next` produces at most one1604+ output for each input. See advanced topics below.1605+1606+ examples:1607+ - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1608+ input: '4'1609+ output: ['24']1610+1611+1612+ - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`, `recurse_down`"1613+ body: |1614+1615+ The `recurse(f)` function allows you to search through a1616+ recursive structure, and extract interesting data from all1617+ levels. Suppose your input represents a filesystem:1618+1619+ {"name": "/", "children": [1620+ {"name": "/bin", "children": [1621+ {"name": "/bin/ls", "children": []},1622+ {"name": "/bin/sh", "children": []}]},1623+ {"name": "/home", "children": [1624+ {"name": "/home/stephen", "children": [1625+ {"name": "/home/stephen/jq", "children": []}]}]}]}1626+1627+ Now suppose you want to extract all of the filenames1628+ present. You need to retrieve `.name`, `.children[].name`,1629+ `.children[].children[].name`, and so on. You can do this1630+ with:1631+1632+ recurse(.children[]) | .name1633+1634+ When called without an argument, `recurse` is equivalent to1635+ `recurse(.[]?)`.1636+1637+ `recurse(f)` is identical to `recurse(f; . != null)` and can be1638+ used without concerns about recursion depth.1639+1640+ `recurse(f; condition)` is a generator which begins by1641+ emitting . and then emits in turn .|f, .|f|f, .|f|f|f, ... so long1642+ as the computed value satisfies the condition. For example,1643+ to generate all the integers, at least in principle, one1644+ could write `recurse(.+1; true)`.1645+1646+ For legacy reasons, `recurse_down` exists as an alias to1647+ calling `recurse` without arguments. This alias is considered1648+ *deprecated* and will be removed in the next major release.1649+1650+ The recursive calls in `recurse` will not consume additional1651+ memory whenever `f` produces at most a single output for each1652+ input.1653+1654+ examples:1655+ - program: 'recurse(.foo[])'1656+ input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'1657+ output:1658+ - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'1659+ - '{"foo":[]}'1660+ - '{"foo":[{"foo":[]}]}'1661+ - '{"foo":[]}'1662+1663+ - program: 'recurse'1664+ input: '{"a":0,"b":[1]}'1665+ output:1666+ - '{"a":0,"b":[1]}'1667+ - '0'1668+ - '[1]'1669+ - '1'1670+1671+ - program: 'recurse(. * .; . < 20)'1672+ input: 21673+ output:1674+ - 21675+ - 41676+ - 161677+1678+ - title: "`walk(f)`"1679+ body: |1680+1681+ The `walk(f)` function applies f recursively to every1682+ component of the input entity. When an array is1683+ encountered, f is first applied to its elements and then to1684+ the array itself; when an object is encountered, f is first1685+ applied to all the values and then to the object. In1686+ practice, f will usually test the type of its input, as1687+ illustrated in the following examples. The first example1688+ highlights the usefulness of processing the elements of an1689+ array of arrays before processing the array itself. The second1690+ example shows how all the keys of all the objects within the1691+ input can be considered for alteration.1692+1693+ examples:1694+ - program: 'walk(if type == "array" then sort else . end)'1695+ input: '[[4, 1, 7], [8, 5, 2], [3, 6, 9]]'1696+ output:1697+ - '[[1,4,7],[2,5,8],[3,6,9]]'1698+1699+ - program: 'walk( if type == "object" then with_entries( .key |= sub( "^_+"; "") ) else . end )'1700+ input: '[ { "_a": { "__b": 2 } } ]'1701+ output:1702+ - '[{"a":{"b":2}}]'1703+1704+ - title: "`$ENV`, `env`"1705+ body: |1706+1707+ `$ENV` is an object representing the environment variables as1708+ set when the jq program started.1709+1710+ `env` outputs an object representing jq's current environment.1711+1712+ At the moment there is no builtin for setting environment1713+ variables.1714+1715+ examples:1716+ - program: '$ENV.PAGER'1717+ input: 'null'1718+ output: ['"less"']1719+1720+ - program: 'env.PAGER'1721+ input: 'null'1722+ output: ['"less"']1723+1724+ - title: "`transpose`"1725+ body: |1726+1727+ Transpose a possibly jagged matrix (an array of arrays).1728+ Rows are padded with nulls so the result is always rectangular.1729+1730+ examples:1731+ - program: 'transpose'1732+ input: '[[1], [2,3]]'1733+ output: ['[[1,2],[null,3]]']1734+1735+ - title: "`bsearch(x)`"1736+ body: |1737+1738+ bsearch(x) conducts a binary search for x in the input1739+ array. If the input is sorted and contains x, then1740+ bsearch(x) will return its index in the array; otherwise, if1741+ the array is sorted, it will return (-1 - ix) where ix is an1742+ insertion point such that the array would still be sorted1743+ after the insertion of x at ix. If the array is not sorted,1744+ bsearch(x) will return an integer that is probably of no1745+ interest.1746+1747+ examples:1748+ - program: 'bsearch(0)'1749+ input: '[0,1]'1750+ output: ['0']1751+ - program: 'bsearch(0)'1752+ input: '[1,2,3]'1753+ output: ['-1']1754+ - program: 'bsearch(4) as $ix | if $ix < 0 then .[-(1+$ix)] = 4 else . end'1755+ input: '[1,2,3]'1756+ output: ['[1,2,3,4]']1757+1758+ - title: "String interpolation - `\\(foo)`"1759+ body: |1760+1761+ Inside a string, you can put an expression inside parens1762+ after a backslash. Whatever the expression returns will be1763+ interpolated into the string.1764+1765+ examples:1766+ - program: '"The input was \(.), which is one less than \(.+1)"'1767+ input: '42'1768+ output: ['"The input was 42, which is one less than 43"']1769+1770+ - title: "Convert to/from JSON"1771+ body: |1772+1773+ The `tojson` and `fromjson` builtins dump values as JSON texts1774+ or parse JSON texts into values, respectively. The tojson1775+ builtin differs from tostring in that tostring returns strings1776+ unmodified, while tojson encodes strings as JSON strings.1777+1778+ examples:1779+ - program: '[.[]|tostring]'1780+ input: '[1, "foo", ["foo"]]'1781+ output: ['["1","foo","[\"foo\"]"]']1782+ - program: '[.[]|tojson]'1783+ input: '[1, "foo", ["foo"]]'1784+ output: ['["1","\"foo\"","[\"foo\"]"]']1785+ - program: '[.[]|tojson|fromjson]'1786+ input: '[1, "foo", ["foo"]]'1787+ output: ['[1,"foo",["foo"]]']1788+1789+ - title: "Format strings and escaping"1790+ body: |1791+1792+ The `@foo` syntax is used to format and escape strings,1793+ which is useful for building URLs, documents in a language1794+ like HTML or XML, and so forth. `@foo` can be used as a1795+ filter on its own, the possible escapings are:1796+1797+ * `@text`:1798+1799+ Calls `tostring`, see that function for details.1800+1801+ * `@json`:1802+1803+ Serializes the input as JSON.1804+1805+ * `@html`:1806+1807+ Applies HTML/XML escaping, by mapping the characters1808+ `<>&'"` to their entity equivalents `<`, `>`,1809+ `&`, `'`, `"`.1810+1811+ * `@uri`:1812+1813+ Applies percent-encoding, by mapping all reserved URI1814+ characters to a `%XX` sequence.1815+1816+ * `@csv`:1817+1818+ The input must be an array, and it is rendered as CSV1819+ with double quotes for strings, and quotes escaped by1820+ repetition.1821+1822+ * `@tsv`:1823+1824+ The input must be an array, and it is rendered as TSV1825+ (tab-separated values). Each input array will be printed as1826+ a single line. Fields are separated by a single1827+ tab (ascii `0x09`). Input characters line-feed (ascii `0x0a`),1828+ carriage-return (ascii `0x0d`), tab (ascii `0x09`) and1829+ backslash (ascii `0x5c`) will be output as escape sequences1830+ `\n`, `\r`, `\t`, `\\` respectively.1831+1832+ * `@sh`:1833+1834+ The input is escaped suitable for use in a command-line1835+ for a POSIX shell. If the input is an array, the output1836+ will be a series of space-separated strings.1837+1838+ * `@base64`:1839+1840+ The input is converted to base64 as specified by RFC 4648.1841+1842+ * `@base64d`:1843+1844+ The inverse of `@base64`, input is decoded as specified by RFC 4648.1845+ Note\: If the decoded string is not UTF-8, the results are undefined.1846+1847+ This syntax can be combined with string interpolation in a1848+ useful way. You can follow a `@foo` token with a string1849+ literal. The contents of the string literal will *not* be1850+ escaped. However, all interpolations made inside that string1851+ literal will be escaped. For instance,1852+1853+ @uri "https://www.google.com/search?q=\(.search)"1854+1855+ will produce the following output for the input1856+ `{"search":"what is jq?"}`:1857+1858+ "https://www.google.com/search?q=what%20is%20jq%3F"1859+1860+ Note that the slashes, question mark, etc. in the URL are1861+ not escaped, as they were part of the string literal.1862+1863+ examples:1864+ - program: '@html'1865+ input: '"This works if x < y"'1866+ output: ['"This works if x < y"']1867+1868+# - program: '@html "<span>Anonymous said: \(.)</span>"'1869+# input: '"<script>alert(\"lol hax\");</script>"'1870+# output: ["<span>Anonymous said: <script>alert("lol hax");</script></span>"]1871+1872+ - program: '@sh "echo \(.)"'1873+ input: "\"O'Hara's Ale\""1874+ output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]1875+1876+ - program: '@base64'1877+ input: '"This is a message"'1878+ output: ['"VGhpcyBpcyBhIG1lc3NhZ2U="']1879+1880+ - program: '@base64d'1881+ input: '"VGhpcyBpcyBhIG1lc3NhZ2U="'1882+ output: ['"This is a message"']1883+1884+ - title: "Dates"1885+ body: |1886+1887+ jq provides some basic date handling functionality, with some1888+ high-level and low-level builtins. In all cases these1889+ builtins deal exclusively with time in UTC.1890+1891+ The `fromdateiso8601` builtin parses datetimes in the ISO 86011892+ format to a number of seconds since the Unix epoch1893+ (1970-01-01T00:00:00Z). The `todateiso8601` builtin does the1894+ inverse.1895+1896+ The `fromdate` builtin parses datetime strings. Currently1897+ `fromdate` only supports ISO 8601 datetime strings, but in the1898+ future it will attempt to parse datetime strings in more1899+ formats.1900+1901+ The `todate` builtin is an alias for `todateiso8601`.1902+1903+ The `now` builtin outputs the current time, in seconds since1904+ the Unix epoch.1905+1906+ Low-level jq interfaces to the C-library time functions are1907+ also provided: `strptime`, `strftime`, `strflocaltime`,1908+ `mktime`, `gmtime`, and `localtime`. Refer to your host1909+ operating system's documentation for the format strings used1910+ by `strptime` and `strftime`. Note: these are not necessarily1911+ stable interfaces in jq, particularly as to their localization1912+ functionality.1913+1914+ The `gmtime` builtin consumes a number of seconds since the1915+ Unix epoch and outputs a "broken down time" representation of1916+ Greenwhich Meridian time as an array of numbers representing1917+ (in this order): the year, the month (zero-based), the day of1918+ the month (one-based), the hour of the day, the minute of the1919+ hour, the second of the minute, the day of the week, and the1920+ day of the year -- all one-based unless otherwise stated. The1921+ day of the week number may be wrong on some systems for dates1922+ before March 1st 1900, or after December 31 2099.1923+1924+ The `localtime` builtin works like the `gmtime` builtin, but1925+ using the local timezone setting.1926+1927+ The `mktime` builtin consumes "broken down time"1928+ representations of time output by `gmtime` and `strptime`.1929+1930+ The `strptime(fmt)` builtin parses input strings matching the1931+ `fmt` argument. The output is in the "broken down time"1932+ representation consumed by `gmtime` and output by `mktime`.1933+1934+ The `strftime(fmt)` builtin formats a time (GMT) with the1935+ given format. The `strflocaltime` does the same, but using1936+ the local timezone setting.1937+1938+ The format strings for `strptime` and `strftime` are described1939+ in typical C library documentation. The format string for ISO1940+ 8601 datetime is `"%Y-%m-%dT%H:%M:%SZ"`.1941+1942+ jq may not support some or all of this date functionality on1943+ some systems. In particular, the `%u` and `%j` specifiers for1944+ `strptime(fmt)` are not supported on macOS.1945+1946+ examples:1947+ - program: 'fromdate'1948+ input: '"2015-03-05T23:51:47Z"'1949+ output: ['1425599507']1950+1951+ - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")'1952+ input: '"2015-03-05T23:51:47Z"'1953+ output: ['[2015,2,5,23,51,47,4,63]']1954+1955+ - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'1956+ input: '"2015-03-05T23:51:47Z"'1957+ output: ['1425599507']1958+1959+ - title: "SQL-Style Operators"1960+ body: |1961+1962+ jq provides a few SQL-style operators.1963+1964+ * INDEX(stream; index_expression):1965+1966+ This builtin produces an object whose keys are computed by1967+ the given index expression applied to each value from the1968+ given stream.1969+1970+ * JOIN($idx; stream; idx_expr; join_expr):1971+1972+ This builtin joins the values from the given stream to the1973+ given index. The index's keys are computed by applying the1974+ given index expression to each value from the given stream.1975+ An array of the value in the stream and the corresponding1976+ value from the index is fed to the given join expression to1977+ produce each result.1978+1979+ * JOIN($idx; stream; idx_expr):1980+1981+ Same as `JOIN($idx; stream; idx_expr; .)`.1982+1983+ * JOIN($idx; idx_expr):1984+1985+ This builtin joins the input `.` to the given index, applying1986+ the given index expression to `.` to compute the index key.1987+ The join operation is as described above.1988+1989+ * IN(s):1990+1991+ This builtin outputs `true` if `.` appears in the given1992+ stream, otherwise it outputs `false`.1993+1994+ * IN(source; s):1995+1996+ This builtin outputs `true` if any value in the source stream1997+ appears in the second stream, otherwise it outputs `false`.1998+1999+ - title: "`builtins`"2000+ body: |2001+2002+ Returns a list of all builtin functions in the format `name/arity`.2003+ Since functions with the same name but different arities are considered2004+ separate functions, `all/0`, `all/1`, and `all/2` would all be present2005+ in the list.2006+2007+ - title: Conditionals and Comparisons2008+ entries:2009+ - title: "`==`, `!=`"2010+ body: |2011+2012+ The expression 'a == b' will produce 'true' if the result of a and b2013+ are equal (that is, if they represent equivalent JSON documents) and2014+ 'false' otherwise. In particular, strings are never considered equal2015+ to numbers. If you're coming from Javascript, jq's == is like2016+ Javascript's === - considering values equal only when they have the2017+ same type as well as the same value.2018+2019+ != is "not equal", and 'a != b' returns the opposite value of 'a == b'2020+2021+ examples:2022+ - program: '.[] == 1'2023+ input: '[1, 1.0, "1", "banana"]'2024+ output: ['true', 'true', 'false', 'false']2025+2026+ - title: if-then-else2027+ body: |2028+2029+ `if A then B else C end` will act the same as `B` if `A`2030+ produces a value other than false or null, but act the same2031+ as `C` otherwise.2032+2033+ Checking for false or null is a simpler notion of2034+ "truthiness" than is found in Javascript or Python, but it2035+ means that you'll sometimes have to be more explicit about2036+ the condition you want: you can't test whether, e.g. a2037+ string is empty using `if .name then A else B end`, you'll2038+ need something more like `if (.name | length) > 0 then A else2039+ B end` instead.2040+2041+ If the condition `A` produces multiple results, then `B` is evaluated2042+ once for each result that is not false or null, and `C` is evaluated2043+ once for each false or null.2044+2045+ More cases can be added to an if using `elif A then B` syntax.2046+2047+ examples:2048+ - program: |-2049+ if . == 0 then2050+ "zero"2051+ elif . == 1 then2052+ "one"2053+ else2054+ "many"2055+ end2056+ input: 22057+ output: ['"many"']2058+2059+ - title: "`>, >=, <=, <`"2060+ body: |2061+2062+ The comparison operators `>`, `>=`, `<=`, `<` return whether2063+ their left argument is greater than, greater than or equal2064+ to, less than or equal to or less than their right argument2065+ (respectively).2066+2067+ The ordering is the same as that described for `sort`, above.2068+2069+ examples:2070+ - program: '. < 5'2071+ input: 22072+ output: ['true']2073+2074+ - title: and/or/not2075+ body: |2076+2077+ jq supports the normal Boolean operators and/or/not. They have the2078+ same standard of truth as if expressions - false and null are2079+ considered "false values", and anything else is a "true value".2080+2081+ If an operand of one of these operators produces multiple2082+ results, the operator itself will produce a result for each input.2083+2084+ `not` is in fact a builtin function rather than an operator,2085+ so it is called as a filter to which things can be piped2086+ rather than with special syntax, as in `.foo and .bar |2087+ not`.2088+2089+ These three only produce the values "true" and "false", and2090+ so are only useful for genuine Boolean operations, rather2091+ than the common Perl/Python/Ruby idiom of2092+ "value_that_may_be_null or default". If you want to use this2093+ form of "or", picking between two values rather than2094+ evaluating a condition, see the "//" operator below.2095+2096+ examples:2097+ - program: '42 and "a string"'2098+ input: 'null'2099+ output: ['true']2100+ - program: '(true, false) or false'2101+ input: 'null'2102+ output: ['true', 'false']2103+# - program: '(true, false) and (true, false)'2104+# input: 'null'2105+# output: ['true', 'false', 'false', 'false']2106+ - program: '(true, true) and (true, false)'2107+ input: 'null'2108+ output: ['true', 'false', 'true', 'false']2109+ - program: '[true, false | not]'2110+ input: 'null'2111+ output: ['[false, true]']2112+2113+ - title: "Alternative operator: `//`"2114+ body: |2115+2116+ A filter of the form `a // b` produces the same2117+ results as `a`, if `a` produces results other than `false`2118+ and `null`. Otherwise, `a // b` produces the same results as `b`.2119+2120+ This is useful for providing defaults: `.foo // 1` will2121+ evaluate to `1` if there's no `.foo` element in the2122+ input. It's similar to how `or` is sometimes used in Python2123+ (jq's `or` operator is reserved for strictly Boolean2124+ operations).2125+2126+ examples:2127+ - program: '.foo // 42'2128+ input: '{"foo": 19}'2129+ output: [19]2130+ - program: '.foo // 42'2131+ input: '{}'2132+ output: [42]2133+2134+ - title: try-catch2135+ body: |2136+2137+ Errors can be caught by using `try EXP catch EXP`. The first2138+ expression is executed, and if it fails then the second is2139+ executed with the error message. The output of the handler,2140+ if any, is output as if it had been the output of the2141+ expression to try.2142+2143+ The `try EXP` form uses `empty` as the exception handler.2144+2145+ examples:2146+ - program: 'try .a catch ". is not an object"'2147+ input: 'true'2148+ output: ['". is not an object"']2149+ - program: '[.[]|try .a]'2150+ input: '[{}, true, {"a":1}]'2151+ output: ['[null, 1]']2152+ - program: 'try error("some exception") catch .'2153+ input: 'true'2154+ output: ['"some exception"']2155+2156+ - title: Breaking out of control structures2157+ body: |2158+2159+ A convenient use of try/catch is to break out of control2160+ structures like `reduce`, `foreach`, `while`, and so on.2161+2162+ For example:2163+2164+ # Repeat an expression until it raises "break" as an2165+ # error, then stop repeating without re-raising the error.2166+ # But if the error caught is not "break" then re-raise it.2167+ try repeat(exp) catch .=="break" then empty else error;2168+2169+ jq has a syntax for named lexical labels to "break" or "go (back) to":2170+2171+ label $out | ... break $out ...2172+2173+ The `break $label_name` expression will cause the program to2174+ to act as though the nearest (to the left) `label $label_name`2175+ produced `empty`.2176+2177+ The relationship between the `break` and corresponding `label`2178+ is lexical: the label has to be "visible" from the break.2179+2180+ To break out of a `reduce`, for example:2181+2182+ label $out | reduce .[] as $item (null; if .==false then break $out else ... end)2183+2184+ The following jq program produces a syntax error:2185+2186+ break $out2187+2188+ because no label `$out` is visible.2189+2190+ - title: "Error Suppression / Optional Operator: `?`"2191+ body: |2192+2193+ The `?` operator, used as `EXP?`, is shorthand for `try EXP`.2194+2195+ examples:2196+ - program: '[.[]|(.a)?]'2197+ input: '[{}, true, {"a":1}]'2198+ output: ['[null, 1]']2199+2200+2201+ - title: Regular expressions (PCRE)2202+ body: |2203+2204+ jq uses the Oniguruma regular expression library, as do php,2205+ ruby, TextMate, Sublime Text, etc, so the description here2206+ will focus on jq specifics.2207+2208+ The jq regex filters are defined so that they can be used using2209+ one of these patterns:2210+2211+ STRING | FILTER( REGEX )2212+ STRING | FILTER( REGEX; FLAGS )2213+ STRING | FILTER( [REGEX] )2214+ STRING | FILTER( [REGEX, FLAGS] )2215+2216+ where:2217+ * STRING, REGEX and FLAGS are jq strings and subject to jq string interpolation;2218+ * REGEX, after string interpolation, should be a valid PCRE regex;2219+ * FILTER is one of `test`, `match`, or `capture`, as described below.2220+2221+ FLAGS is a string consisting of one of more of the supported flags:2222+2223+ * `g` - Global search (find all matches, not just the first)2224+ * `i` - Case insensitive search2225+ * `m` - Multi line mode ('.' will match newlines)2226+ * `n` - Ignore empty matches2227+ * `p` - Both s and m modes are enabled2228+ * `s` - Single line mode ('^' -> '\A', '$' -> '\Z')2229+ * `l` - Find longest possible matches2230+ * `x` - Extended regex format (ignore whitespace and comments)2231+2232+ To match whitespace in an x pattern use an escape such as \s, e.g.2233+2234+ * test( "a\\sb", "x" ).2235+2236+ Note that certain flags may also be specified within REGEX, e.g.2237+2238+ * jq -n '("test", "TEst", "teST", "TEST") | test( "(?i)te(?-i)st" )'2239+2240+ evaluates to: true, true, false, false.2241+2242+ entries:2243+ - title: "`test(val)`, `test(regex; flags)`"2244+ body: |2245+2246+ Like `match`, but does not return match objects, only `true` or `false`2247+ for whether or not the regex matches the input.2248+2249+ examples:2250+ - program: 'test("foo")'2251+ input: '"foo"'2252+ output: ['true']2253+ - program: '.[] | test("a b c # spaces are ignored"; "ix")'2254+ input: '["xabcd", "ABC"]'2255+ output: ['true', 'true']2256+2257+ - title: "`match(val)`, `match(regex; flags)`"2258+ body: |2259+2260+ **match** outputs an object for each match it finds. Matches have2261+ the following fields:2262+2263+ * `offset` - offset in UTF-8 codepoints from the beginning of the input2264+ * `length` - length in UTF-8 codepoints of the match2265+ * `string` - the string that it matched2266+ * `captures` - an array of objects representing capturing groups.2267+2268+ Capturing group objects have the following fields:2269+2270+ * `offset` - offset in UTF-8 codepoints from the beginning of the input2271+ * `length` - length in UTF-8 codepoints of this capturing group2272+ * `string` - the string that was captured2273+ * `name` - the name of the capturing group (or `null` if it was unnamed)2274+2275+ Capturing groups that did not match anything return an offset of -12276+2277+ examples:2278+ - program: 'match("(abc)+"; "g")'2279+ input: '"abc abc"'2280+ output:2281+ - '{"offset": 0, "length": 3, "string": "abc", "captures": [{"offset": 0, "length": 3, "string": "abc", "name": null}]}'2282+ - '{"offset": 4, "length": 3, "string": "abc", "captures": [{"offset": 4, "length": 3, "string": "abc", "name": null}]}'2283+ - program: 'match("foo")'2284+ input: '"foo bar foo"'2285+ output: ['{"offset": 0, "length": 3, "string": "foo", "captures": []}']2286+ - program: 'match(["foo", "ig"])'2287+ input: '"foo bar FOO"'2288+ output:2289+ - '{"offset": 0, "length": 3, "string": "foo", "captures": []}'2290+ - '{"offset": 8, "length": 3, "string": "FOO", "captures": []}'2291+ - program: 'match("foo (?<bar123>bar)? foo"; "ig")'2292+ input: '"foo bar foo foo foo"'2293+ output:2294+ - '{"offset": 0, "length": 11, "string": "foo bar foo", "captures": [{"offset": 4, "length": 3, "string": "bar", "name": "bar123"}]}'2295+ - '{"offset": 12, "length": 8, "string": "foo foo", "captures": [{"offset": -1, "length": 0, "string": null, "name": "bar123"}]}'2296+2297+ - program: '[ match("."; "g")] | length'2298+ input: '"abc"'2299+ output: [3]2300+2301+2302+ - title: "`capture(val)`, `capture(regex; flags)`"2303+ body: |2304+2305+ Collects the named captures in a JSON object, with the name2306+ of each capture as the key, and the matched string as the2307+ corresponding value.2308+2309+ examples:2310+ - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2311+ input: '"xyzzy-14"'2312+ output: ['{ "a": "xyzzy", "n": "14" }']2313+2314+ - title: "`scan(regex)`, `scan(regex; flags)`"2315+ body: |2316+2317+ Emit a stream of the non-overlapping substrings of the input2318+ that match the regex in accordance with the flags, if any2319+ have been specified. If there is no match, the stream is empty.2320+ To capture all the matches for each input string, use the idiom2321+ `[ expr ]`, e.g. `[ scan(regex) ]`.2322+2323+ example:2324+ - program: 'scan("c")'2325+ input: '"abcdefabc"'2326+ output: ['"c"', '"c"']2327+2328+ - program: 'scan("b")'2329+ input: ("", "")2330+ output: ['[]', '[]']2331+2332+ - title: "`split(regex; flags)`"2333+ body: |2334+2335+ For backwards compatibility, `split` splits on a string, not a regex.2336+2337+ example:2338+ - program: 'split(", *"; null)'2339+ input: '"ab,cd, ef"'2340+ output: ['"ab","cd","ef"']2341+2342+2343+ - title: "`splits(regex)`, `splits(regex; flags)`"2344+ body: |2345+2346+ These provide the same results as their `split` counterparts,2347+ but as a stream instead of an array.2348+2349+ example:2350+ - program: 'splits(", *")'2351+ input: '("ab,cd", "ef, gh")'2352+ output: ['"ab"', '"cd"', '"ef"', '"gh"']2353+2354+ - title: "`sub(regex; tostring)` `sub(regex; string; flags)`"2355+ body: |2356+2357+ Emit the string obtained by replacing the first match of regex in the2358+ input string with `tostring`, after interpolation. `tostring` should2359+ be a jq string, and may contain references to named captures. The2360+ named captures are, in effect, presented as a JSON object (as2361+ constructed by `capture`) to `tostring`, so a reference to a captured2362+ variable named "x" would take the form: "\(.x)".2363+2364+ example:2365+ - program: 'sub("^[^a-z]*(?<x>[a-z]*).*")'2366+ input: '"123abc456"'2367+ output: '"ZabcZabc"'2368+2369+2370+ - title: "`gsub(regex; string)`, `gsub(regex; string; flags)`"2371+ body: |2372+2373+ `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2374+ replaced by the string, after interpolation.2375+2376+ example:2377+ - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2378+ input: '"Abcabc"'2379+ output: '"+A-+a-"'2380+2381+2382+ - title: Advanced features2383+ body: |2384+ Variables are an absolute necessity in most programming languages, but2385+ they're relegated to an "advanced feature" in jq.2386+2387+ In most languages, variables are the only means of passing around2388+ data. If you calculate a value, and you want to use it more than once,2389+ you'll need to store it in a variable. To pass a value to another part2390+ of the program, you'll need that part of the program to define a2391+ variable (as a function parameter, object member, or whatever) in2392+ which to place the data.2393+2394+ It is also possible to define functions in jq, although this is2395+ is a feature whose biggest use is defining jq's standard library2396+ (many jq functions such as `map` and `find` are in fact written2397+ in jq).2398+2399+ jq has reduction operators, which are very powerful but a bit2400+ tricky. Again, these are mostly used internally, to define some2401+ useful bits of jq's standard library.2402+2403+ It may not be obvious at first, but jq is all about generators2404+ (yes, as often found in other languages). Some utilities are2405+ provided to help deal with generators.2406+2407+ Some minimal I/O support (besides reading JSON from standard2408+ input, and writing JSON to standard output) is available.2409+2410+ Finally, there is a module/library system.2411+2412+ entries:2413+ - title: "Variable / Symbolic Binding Operator: `... as $identifier | ...`"2414+ body: |2415+2416+ In jq, all filters have an input and an output, so manual2417+ plumbing is not necessary to pass a value from one part of a program2418+ to the next. Many expressions, for instance `a + b`, pass their input2419+ to two distinct subexpressions (here `a` and `b` are both passed the2420+ same input), so variables aren't usually necessary in order to use a2421+ value twice.2422+2423+ For instance, calculating the average value of an array of numbers2424+ requires a few variables in most languages - at least one to hold the2425+ array, perhaps one for each element or for a loop counter. In jq, it's2426+ simply `add / length` - the `add` expression is given the array and2427+ produces its sum, and the `length` expression is given the array and2428+ produces its length.2429+2430+ So, there's generally a cleaner way to solve most problems in jq than2431+ defining variables. Still, sometimes they do make things easier, so jq2432+ lets you define variables using `expression as $variable`. All2433+ variable names start with `$`. Here's a slightly uglier version of the2434+ array-averaging example:2435+2436+ length as $array_length | add / $array_length2437+2438+ We'll need a more complicated problem to find a situation where using2439+ variables actually makes our lives easier.2440+2441+2442+ Suppose we have an array of blog posts, with "author" and "title"2443+ fields, and another object which is used to map author usernames to2444+ real names. Our input looks like:2445+2446+ {"posts": [{"title": "Frist psot", "author": "anon"},2447+ {"title": "A well-written article", "author": "person1"}],2448+ "realnames": {"anon": "Anonymous Coward",2449+ "person1": "Person McPherson"}}2450+2451+ We want to produce the posts with the author field containing a real2452+ name, as in:2453+2454+ {"title": "Frist psot", "author": "Anonymous Coward"}2455+ {"title": "A well-written article", "author": "Person McPherson"}2456+2457+ We use a variable, $names, to store the realnames object, so that we2458+ can refer to it later when looking up author usernames:2459+2460+ .realnames as $names | .posts[] | {title, author: $names[.author]}2461+2462+ The expression `exp as $x | ...` means: for each value of expression2463+ `exp`, run the rest of the pipeline with the entire original input, and2464+ with `$x` set to that value. Thus `as` functions as something of a2465+ foreach loop.2466+2467+ Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2468+ `{$foo}` is a handy way of writing `{foo:$foo}`.2469+2470+ Multiple variables may be declared using a single `as` expression by2471+ providing a pattern that matches the structure of the input2472+ (this is known as "destructuring"):2473+2474+ . as {realnames: $names, posts: [$first, $second]} | ...2475+2476+ The variable declarations in array patterns (e.g., `. as2477+ [$first, $second]`) bind to the elements of the array in from2478+ the element at index zero on up, in order. When there is no2479+ value at the index for an array pattern element, `null` is2480+ bound to that variable.2481+2482+ Variables are scoped over the rest of the expression that defines2483+ them, so2484+2485+ .realnames as $names | (.posts[] | {title, author: $names[.author]})2486+2487+ will work, but2488+2489+ (.realnames as $names | .posts[]) | {title, author: $names[.author]}2490+2491+ won't.2492+2493+ For programming language theorists, it's more accurate to2494+ say that jq variables are lexically-scoped bindings. In2495+ particular there's no way to change the value of a binding;2496+ one can only setup a new binding with the same name, but which2497+ will not be visible where the old one was.2498+2499+ examples:2500+ - program: '.bar as $x | .foo | . + $x'2501+ input: '{"foo":10, "bar":200}'2502+ output: ['210']2503+ - program: '. as $i|[(.*2|. as $i| $i), $i]'2504+ input: '5'2505+ output: ['[10,5]']2506+ - program: '. as [$a, $b, {c: $c}] | $a + $b + $c'2507+ input: '[2, 3, {"c": 4, "d": 5}]'2508+ output: ['9']2509+ - program: '.[] as [$a, $b] | {a: $a, b: $b}'2510+ input: '[[0], [0, 1], [2, 1, 0]]'2511+ output: ['{"a":0,"b":null}', '{"a":0,"b":1}', '{"a":2,"b":1}']2512+2513+ - title: 'Destructuring Alternative Operator: `?//`'2514+ body: |2515+ 2516+ The destructuring alternative operator provides a concise mechanism2517+ for destructuring an input that can take one of several forms.2518+2519+ Suppose we have an API that returns a list of resources and events2520+ associated with them, and we want to get the user_id and timestamp of2521+ the first event for each resource. The API (having been clumsily2522+ converted from XML) will only wrap the events in an array if the resource2523+ has multiple events:2524+ 2525+ {"resources": [{"id": 1, "kind": "widget", "events": {"action": "create", "user_id": 1, "ts": 13}},2526+ {"id": 2, "kind": "widget", "events": [{"action": "create", "user_id": 1, "ts": 14}, {"action": "destroy", "user_id": 1, "ts": 15}]}]}2527+ 2528+ We can use the destructuring alternative operator to handle this structural change simply:2529+2530+ .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$user_id, $ts}]} | {$user_id, $kind, $id, $ts}2531+2532+ Or, if we aren't sure if the input is an array of values or an object:2533+2534+ .[] as [$id, $kind, $user_id, $ts] ?// {$id, $kind, $user_id, $ts} | ...2535+2536+ Each alternative need not define all of the same variables, but all named2537+ variables will be available to the subsequent expression. Variables not2538+ matched in the alternative that succeeded will be `null`:2539+2540+ .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$first_user_id, $first_ts}]} | {$user_id, $first_user_id, $kind, $id, $ts, $first_ts}2541+2542+ Additionally, if the subsequent expression returns an error, the2543+ alternative operator will attempt to try the next binding. Errors2544+ that occur during the final alternative are passed through.2545+2546+ [[3]] | .[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end2547+2548+ examples:2549+ - program: '.[] as {$a, $b, c: {$d, $e}} ?// {$a, $b, c: [{$d, $e}]} | {$a, $b, $d, $e}'2550+ input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2551+ output: ['{"a":1,"b":2,"d":3,"e":4}', '{"a":1,"b":2,"d":3,"e":4}']2552+ - program: '.[] as {$a, $b, c: {$d}} ?// {$a, $b, c: [{$e}]} | {$a, $b, $d, $e}'2553+ input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2554+ output: ['{"a":1,"b":2,"d":3,"e":null}', '{"a":1,"b":2,"d":null,"e":4}']2555+ - program: '.[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end'2556+ input: '[[3]]'2557+ output: ['{"a":null,"b":3}']2558+2559+ - title: 'Defining Functions'2560+ body: |2561+2562+ You can give a filter a name using "def" syntax:2563+2564+ def increment: . + 1;2565+2566+ From then on, `increment` is usable as a filter just like a2567+ builtin function (in fact, this is how many of the builtins2568+ are defined). A function may take arguments:2569+2570+ def map(f): [.[] | f];2571+2572+ Arguments are passed as _filters_ (functions with no2573+ arguments), _not_ as values. The same argument may be2574+ referenced multiple times with different inputs (here `f` is2575+ run for each element of the input array). Arguments to a2576+ function work more like callbacks than like value arguments.2577+ This is important to understand. Consider:2578+2579+ def foo(f): f|f;2580+ 5|foo(.*2)2581+2582+ The result will be 20 because `f` is `.*2`, and during the2583+ first invocation of `f` `.` will be 5, and the second time it2584+ will be 10 (5 * 2), so the result will be 20. Function2585+ arguments are filters, and filters expect an input when2586+ invoked.2587+2588+ If you want the value-argument behaviour for defining simple2589+ functions, you can just use a variable:2590+2591+ def addvalue(f): f as $f | map(. + $f);2592+2593+ Or use the short-hand:2594+2595+ def addvalue($f): ...;2596+2597+ With either definition, `addvalue(.foo)` will add the current2598+ input's `.foo` field to each element of the array. Do note2599+ that calling `addvalue(.[])` will cause the `map(. + $f)` part2600+ to be evaluated once per value in the value of `.` at the call2601+ site.2602+2603+ Multiple definitions using the same function name are allowed.2604+ Each re-definition replaces the previous one for the same2605+ number of function arguments, but only for references from2606+ functions (or main program) subsequent to the re-definition.2607+ See also the section below on scoping.2608+2609+ examples:2610+ - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'2611+ input: '[[1,2],[10,20]]'2612+ output: ['[[1,2,1], [10,20,10]]']2613+ - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'2614+ input: '[[1,2],[10,20]]'2615+ output: ['[[1,2,1,2], [10,20,1,2]]']2616+2617+ - title: 'Scoping'2618+ body: |2619+2620+ There are two types of symbols in jq: value bindings (a.k.a.,2621+ "variables"), and functions. Both are scoped lexically,2622+ with expressions being able to refer only to symbols that2623+ have been defined "to the left" of them. The only exception2624+ to this rule is that functions can refer to themselves so as2625+ to be able to create recursive functions.2626+2627+ For example, in the following expression there is a binding2628+ which is visible "to the right" of it, `... | .*3 as2629+ $times_three | [. + $times_three] | ...`, but not "to the2630+ left". Consider this expression now, `... | (.*3 as2631+ $times_three | [.+ $times_three]) | ...`: here the binding2632+ `$times_three` is _not_ visible past the closing parenthesis.2633+2634+ - title: Reduce2635+ body: |2636+2637+ The `reduce` syntax in jq allows you to combine all of the2638+ results of an expression by accumulating them into a single2639+ answer. As an example, we'll pass `[3,2,1]` to this expression:2640+2641+ reduce .[] as $item (0; . + $item)2642+2643+ For each result that `.[]` produces, `. + $item` is run to2644+ accumulate a running total, starting from 0. In this2645+ example, `.[]` produces the results 3, 2, and 1, so the2646+ effect is similar to running something like this:2647+2648+ 0 | (3 as $item | . + $item) |2649+ (2 as $item | . + $item) |2650+ (1 as $item | . + $item)2651+2652+ examples:2653+ - program: 'reduce .[] as $item (0; . + $item)'2654+ input: '[10,2,5,3]'2655+ output: ['20']2656+2657+ - title: "`isempty(exp)`"2658+ body: |2659+2660+ Returns true if `exp` produces no outputs, false otherwise.2661+2662+ examples:2663+ - program: 'isempty(empty)'2664+ input: 'null'2665+ output: ['true']2666+2667+ - title: "`limit(n; exp)`"2668+ body: |2669+2670+ The `limit` function extracts up to `n` outputs from `exp`.2671+2672+ examples:2673+ - program: '[limit(3;.[])]'2674+ input: '[0,1,2,3,4,5,6,7,8,9]'2675+ output: ['[0,1,2]']2676+2677+ - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"2678+ body: |2679+2680+ The `first(expr)` and `last(expr)` functions extract the first2681+ and last values from `expr`, respectively.2682+2683+ The `nth(n; expr)` function extracts the nth value output by2684+ `expr`. This can be defined as `def nth(n; expr):2685+ last(limit(n + 1; expr));`. Note that `nth(n; expr)` doesn't2686+ support negative values of `n`.2687+2688+ examples:2689+ - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'2690+ input: '10'2691+ output: ['[0,9,5]']2692+2693+ - title: "`first`, `last`, `nth(n)`"2694+ body: |2695+2696+ The `first` and `last` functions extract the first2697+ and last values from any array at `.`.2698+2699+ The `nth(n)` function extracts the nth value of any array at `.`.2700+2701+ examples:2702+ - program: '[range(.)]|[first, last, nth(5)]'2703+ input: '10'2704+ output: ['[0,9,5]']2705+2706+ - title: "`foreach`"2707+ body: |2708+2709+ The `foreach` syntax is similar to `reduce`, but intended to2710+ allow the construction of `limit` and reducers that produce2711+ intermediate results (see example).2712+2713+ The form is `foreach EXP as $var (INIT; UPDATE; EXTRACT)`.2714+ Like `reduce`, `INIT` is evaluated once to produce a state2715+ value, then each output of `EXP` is bound to `$var`, `UPDATE`2716+ is evaluated for each output of `EXP` with the current state2717+ and with `$var` visible. Each value output by `UPDATE`2718+ replaces the previous state. Finally, `EXTRACT` is evaluated2719+ for each new state to extract an output of `foreach`.2720+2721+ This is mostly useful only for constructing `reduce`- and2722+ `limit`-like functions. But it is much more general, as it2723+ allows for partial reductions (see the example below).2724+2725+ examples:2726+ - program: '[foreach .[] as $item2727+ ([[],[]];2728+ if $item == null then [[],.[0]] else [(.[0] + [$item]),[]] end;2729+ if $item == null then .[1] else empty end)]'2730+ input: '[1,2,3,4,null,"a","b",null]'2731+ output: ['[[1,2,3,4],["a","b"]]']2732+2733+ - title: Recursion2734+ body: |2735+2736+ As described above, `recurse` uses recursion, and any jq2737+ function can be recursive. The `while` builtin is also2738+ implemented in terms of recursion.2739+2740+ Tail calls are optimized whenever the expression to the left of2741+ the recursive call outputs its last value. In practice this2742+ means that the expression to the left of the recursive call2743+ should not produce more than one output for each input.2744+2745+ For example:2746+2747+ def recurse(f): def r: ., (f | select(. != null) | r); r;2748+2749+ def while(cond; update):2750+ def _while:2751+ if cond then ., (update | _while) else empty end;2752+ _while;2753+2754+ def repeat(exp):2755+ def _repeat:2756+ exp, _repeat;2757+ _repeat;2758+2759+ - title: Generators and iterators2760+ body: |2761+2762+ Some jq operators and functions are actually generators in2763+ that they can produce zero, one, or more values for each2764+ input, just as one might expect in other programming2765+ languages that have generators. For example, `.[]`2766+ generates all the values in its input (which must be an2767+ array or an object), `range(0; 10)` generates the integers2768+ between 0 and 10, and so on.2769+2770+ Even the comma operator is a generator, generating first the2771+ values generated by the expression to the left of the comma,2772+ then for each of those, the values generate by the2773+ expression on the right of the comma.2774+2775+ The `empty` builtin is the generator that produces zero2776+ outputs. The `empty` builtin backtracks to the preceding2777+ generator expression.2778+2779+ All jq functions can be generators just by using builtin2780+ generators. It is also possible to define new generators2781+ using only recursion and the comma operator. If the2782+ recursive call(s) is(are) "in tail position" then the2783+ generator will be efficient. In the example below the2784+ recursive call by `_range` to itself is in tail position.2785+ The example shows off three advanced topics: tail recursion,2786+ generator construction, and sub-functions.2787+2788+ examples:2789+ - program: 'def range(init; upto; by):2790+ def _range:2791+ if (by > 0 and . < upto) or (by < 0 and . > upto)2792+ then ., ((.+by)|_range)2793+ else . end;2794+ if by == 0 then init else init|_range end |2795+ select((by > 0 and . < upto) or (by < 0 and . > upto));2796+ range(0; 10; 3)'2797+ input: 'null'2798+ output: ['0', '3', '6', '9']2799+ - program: 'def while(cond; update):2800+ def _while:2801+ if cond then ., (update | _while) else empty end;2802+ _while;2803+ [while(.<100; .*2)]'2804+ input: '1'2805+ output: ['[1,2,4,8,16,32,64]']2806+2807+ - title: 'Math'2808+ body: |2809+2810+ jq currently only has IEEE754 double-precision (64-bit) floating2811+ point number support.2812+2813+ Besides simple arithmetic operators such as `+`, jq also has most2814+ standard math functions from the C math library. C math functions2815+ that take a single input argument (e.g., `sin()`) are available as2816+ zero-argument jq functions. C math functions that take two input2817+ arguments (e.g., `pow()`) are available as two-argument jq2818+ functions that ignore `.`. C math functions that take three input2819+ arguments are available as three-argument jq functions that ignore2820+ `.`.2821+2822+ Availability of standard math functions depends on the2823+ availability of the corresponding math functions in your operating2824+ system and C math library. Unavailable math functions will be2825+ defined but will raise an error.2826+2827+ One-input C math functions: `acos` `acosh` `asin` `asinh` `atan`2828+ `atanh` `cbrt` `ceil` `cos` `cosh` `erf` `erfc` `exp` `exp10`2829+ `exp2` `expm1` `fabs` `floor` `gamma` `j0` `j1` `lgamma` `log`2830+ `log10` `log1p` `log2` `logb` `nearbyint` `pow10` `rint` `round`2831+ `significand` `sin` `sinh` `sqrt` `tan` `tanh` `tgamma` `trunc`2832+ `y0` `y1`.2833+2834+ Two-input C math functions: `atan2` `copysign` `drem` `fdim`2835+ `fmax` `fmin` `fmod` `frexp` `hypot` `jn` `ldexp` `modf`2836+ `nextafter` `nexttoward` `pow` `remainder` `scalb` `scalbln` `yn`.2837+2838+ Three-input C math functions: `fma`.2839+2840+ See your system's manual for more information on each of these.2841+2842+ - title: 'I/O'2843+ body: |2844+2845+ At this time jq has minimal support for I/O, mostly in the2846+ form of control over when inputs are read. Two builtins functions2847+ are provided for this, `input` and `inputs`, that read from the2848+ same sources (e.g., `stdin`, files named on the command-line) as2849+ jq itself. These two builtins, and jq's own reading actions, can2850+ be interleaved with each other.2851+2852+ Two builtins provide minimal output capabilities, `debug`, and2853+ `stderr`. (Recall that a jq program's output values are always2854+ output as JSON texts on `stdout`.) The `debug` builtin can have2855+ application-specific behavior, such as for executables that use2856+ the libjq C API but aren't the jq executable itself. The `stderr`2857+ builtin outputs its input in raw mode to stder with no additional2858+ decoration, not even a newline.2859+2860+ Most jq builtins are referentially transparent, and yield constant2861+ and repeatable value streams when applied to constant inputs.2862+ This is not true of I/O builtins.2863+2864+ entries:2865+ - title: "`input`"2866+ body: |2867+2868+ Outputs one new input.2869+2870+ - title: "`inputs`"2871+ body: |2872+2873+ Outputs all remaining inputs, one by one.2874+2875+ This is primarily useful for reductions over a program's2876+ inputs.2877+2878+ - title: "`debug`"2879+ body: |2880+2881+ Causes a debug message based on the input value to be2882+ produced. The jq executable wraps the input value with2883+ `["DEBUG:", <input-value>]` and prints that and a newline on2884+ stderr, compactly. This may change in the future.2885+2886+ - title: "`stderr`"2887+ body: |2888+2889+ Prints its input in raw and compact mode to stderr with no2890+ additional decoration, not even a newline.2891+2892+ - title: "`input_filename`"2893+ body: |2894+2895+ Returns the name of the file whose input is currently being2896+ filtered. Note that this will not work well unless jq is2897+ running in a UTF-8 locale.2898+2899+ - title: "`input_line_number`"2900+ body: |2901+2902+ Returns the line number of the input currently being filtered.2903+2904+ - title: 'Streaming'2905+ body: |2906+2907+ With the `--stream` option jq can parse input texts in a streaming2908+ fashion, allowing jq programs to start processing large JSON texts2909+ immediately rather than after the parse completes. If you have a2910+ single JSON text that is 1GB in size, streaming it will allow you2911+ to process it much more quickly.2912+2913+ However, streaming isn't easy to deal with as the jq program will2914+ have `[<path>, <leaf-value>]` (and a few other forms) as inputs.2915+2916+ Several builtins are provided to make handling streams easier.2917+2918+ The examples below use the streamed form of `[0,[1]]`, which is2919+ `[[0],0],[[1,0],1],[[1,0]],[[1]]`.2920+2921+ Streaming forms include `[<path>, <leaf-value>]` (to indicate any2922+ scalar value, empty array, or empty object), and `[<path>]` (to2923+ indicate the end of an array or object). Future versions of jq2924+ run with `--stream` and `-seq` may output additional forms such as2925+ `["error message"]` when an input text fails to parse.2926+2927+ entries:2928+ - title: "`truncate_stream(stream_expression)`"2929+ body: |2930+2931+ Consumes a number as input and truncates the corresponding2932+ number of path elements from the left of the outputs of the2933+ given streaming expression.2934+2935+ examples:2936+ - program: '[1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]'2937+ input: '1'2938+ output: ['[[[0],2],[[0]]]']2939+2940+ - title: "`fromstream(stream_expression)`"2941+ body: |2942+2943+ Outputs values corresponding to the stream expression's2944+ outputs.2945+2946+ examples:2947+ - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'2948+ input: 'null'2949+ output: ['[2]']2950+2951+ - title: "`tostream`"2952+ body: |2953+2954+ The `tostream` builtin outputs the streamed form of its input.2955+2956+ examples:2957+ - program: '. as $dot|fromstream($dot|tostream)|.==$dot'2958+ input: '[0,[1,{"a":1},{"b":2}]]'2959+ output: ['true']2960+2961+ - title: Assignment2962+ body: |2963+ Assignment works a little differently in jq than in most2964+ programming languages. jq doesn't distinguish between references2965+ to and copies of something - two objects or arrays are either2966+ equal or not equal, without any further notion of being "the2967+ same object" or "not the same object".2968+2969+ If an object has two fields which are arrays, `.foo` and `.bar`,2970+ and you append something to `.foo`, then `.bar` will not get2971+ bigger, even if you've previously set `.bar = .foo`. If you're2972+ used to programming in languages like Python, Java, Ruby,2973+ Javascript, etc. then you can think of it as though jq does a full2974+ deep copy of every object before it does the assignment (for2975+ performance it doesn't actually do that, but that's the general2976+ idea).2977+2978+ This means that it's impossible to build circular values in jq2979+ (such as an array whose first element is itself). This is quite2980+ intentional, and ensures that anything a jq program can produce2981+ can be represented in JSON.2982+2983+ All the assignment operators in jq have path expressions on the2984+ left-hand side (LHS). The right-hand side (RHS) provides values2985+ to set to the paths named by the LHS path expressions.2986+2987+ Values in jq are always immutable. Internally, assignment works2988+ by using a reduction to compute new, replacement values for `.` that2989+ have had all the desired assignments applied to `.`, then2990+ outputting the modified value. This might be made clear by this2991+ example: `{a:{b:{c:1}}} | (.a.b|=3), .`. This will output2992+ `{"a":{"b":3}}` and `{"a":{"b":{"c":1}}}` because the last2993+ sub-expression, `.`, sees the original value, not the modified2994+ value.2995+2996+ Most users will want to use modification assignment operators,2997+ such as `|=` or `+=`, rather than `=`.2998+2999+ Note that the LHS of assignment operators refers to a value in3000+ `.`. Thus `$var.foo = 1` won't work as expected (`$var.foo` is3001+ not a valid or useful path expression in `.`); use `$var | .foo =3002+ 1` instead.3003+3004+ Note too that `.a,.b=0` does not set `.a` and `.b`, but3005+ `(.a,.b)=0` sets both.3006+3007+ entries:3008+ - title: "Update-assignment: `|=`"3009+ body: |3010+ This is the "update" operator '|='. It takes a filter on the3011+ right-hand side and works out the new value for the property3012+ of `.` being assigned to by running the old value through this3013+ expression. For instance, (.foo, .bar) |= .+1 will build an3014+ object with the "foo" field set to the input's "foo" plus 1,3015+ and the "bar" field set to the input's "bar" plus 1.3016+3017+ The left-hand side can be any general path expression; see `path()`.3018+3019+ Note that the left-hand side of '|=' refers to a value in `.`.3020+ Thus `$var.foo |= . + 1` won't work as expected (`$var.foo` is3021+ not a valid or useful path expression in `.`); use `$var |3022+ .foo |= . + 1` instead.3023+3024+ If the right-hand side outputs no values (i.e., `empty`), then3025+ the left-hand side path will be deleted, as with `del(path)`.3026+3027+ If the right-hand side outputs multiple values, only the first3028+ one will be used (COMPATIBILITY NOTE: in jq 1.5 and earlier3029+ releases, it used to be that only the last one was used).3030+3031+ examples:3032+ - program: '(..|select(type=="boolean")) |= if . then 1 else 0 end'3033+ input: '[true,false,[5,true,[true,[false]],false]]'3034+ output: ['[1,0,[5,1,[1,[0]],0]]']3035+3036+ - title: "Arithmetic update-assignment: `+=`, `-=`, `*=`, `/=`, `%=`, `//=`"3037+ body: |3038+3039+ jq has a few operators of the form `a op= b`, which are all3040+ equivalent to `a |= . op b`. So, `+= 1` can be used to3041+ increment values, being the same as `|= . + 1`.3042+3043+ examples:3044+ - program: .foo += 13045+ input: '{"foo": 42}'3046+ output: ['{"foo": 43}']3047+3048+ - title: "Plain assignment: `=`"3049+ body: |3050+3051+ This is the plain assignment operator. Unlike the others, the3052+ input to the right-hand-side (RHS) is the same as the input to3053+ the left-hand-side (LHS) rather than the value at the LHS3054+ path, and all values output by the RHS will be used (as shown3055+ below).3056+3057+ If the RHS of '=' produces multiple values, then for each such3058+ value jq will set the paths on the left-hand side to the value3059+ and then it will output the modified `.`. For example,3060+ `(.a,.b)=range(2)` outputs `{"a":0,"b":0}`, then3061+ `{"a":1,"b":1}`. The "update" assignment forms (see above) do3062+ not do this.3063+3064+ This example should show the difference between '=' and '|=':3065+3066+ Provide input '{"a": {"b": 10}, "b": 20}' to the programs:3067+3068+ .a = .b3069+3070+ .a |= .b3071+3072+ The former will set the "a" field of the input to the "b"3073+ field of the input, and produce the output {"a": 20, "b": 20}.3074+ The latter will set the "a" field of the input to the "a"3075+ field's "b" field, producing {"a": 10, "b": 20}.3076+3077+ Another example of the difference between '=' and '|=':3078+3079+ null|(.a,.b)=range(3)3080+3081+ outputs '{"a":0,"b":0}', '{"a":1,"b":1}', and '{"a":2,"b":2}',3082+ while3083+3084+ null|(.a,.b)|=range(3)3085+3086+ outputs just '{"a":0,"b":0}'.3087+3088+ - title: Complex assignments3089+ body: |3090+ Lots more things are allowed on the left-hand side of a jq assignment3091+ than in most languages. We've already seen simple field accesses on3092+ the left hand side, and it's no surprise that array accesses work just3093+ as well:3094+3095+ .posts[0].title = "JQ Manual"3096+3097+ What may come as a surprise is that the expression on the left may3098+ produce multiple results, referring to different points in the input3099+ document:3100+3101+ .posts[].comments |= . + ["this is great"]3102+3103+ That example appends the string "this is great" to the "comments"3104+ array of each post in the input (where the input is an object with a3105+ field "posts" which is an array of posts).3106+3107+ When jq encounters an assignment like 'a = b', it records the "path"3108+ taken to select a part of the input document while executing a. This3109+ path is then used to find which part of the input to change while3110+ executing the assignment. Any filter may be used on the3111+ left-hand side of an equals - whichever paths it selects from the3112+ input will be where the assignment is performed.3113+3114+ This is a very powerful operation. Suppose we wanted to add a comment3115+ to blog posts, using the same "blog" input above. This time, we only3116+ want to comment on the posts written by "stedolan". We can find those3117+ posts using the "select" function described earlier:3118+3119+ .posts[] | select(.author == "stedolan")3120+3121+ The paths provided by this operation point to each of the posts that3122+ "stedolan" wrote, and we can comment on each of them in the same way3123+ that we did before:3124+3125+ (.posts[] | select(.author == "stedolan") | .comments) |=3126+ . + ["terrible."]3127+3128+ - title: Modules3129+ body: |3130+3131+ jq has a library/module system. Modules are files whose names end3132+ in `.jq`.3133+3134+ Modules imported by a program are searched for in a default search3135+ path (see below). The `import` and `include` directives allow the3136+ importer to alter this path.3137+3138+ Paths in the a search path are subject to various substitutions.3139+3140+ For paths starting with "~/", the user's home directory is3141+ substituted for "~".3142+3143+ For paths starting with "$ORIGIN/", the path of the jq executable3144+ is substituted for "$ORIGIN".3145+3146+ For paths starting with "./" or paths that are ".", the path of3147+ the including file is substituted for ".". For top-level programs3148+ given on the command-line, the current directory is used.3149+3150+ Import directives can optionally specify a search path to which3151+ the default is appended.3152+3153+ The default search path is the search path given to the `-L`3154+ command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",3155+ "$ORIGIN/../lib"]`.3156+3157+ Null and empty string path elements terminate search path3158+ processing.3159+3160+ A dependency with relative path "foo/bar" would be searched for in3161+ "foo/bar.jq" and "foo/bar/bar.jq" in the given search path. This3162+ is intended to allow modules to be placed in a directory along3163+ with, for example, version control files, README files, and so on,3164+ but also to allow for single-file modules.3165+3166+ Consecutive components with the same name are not allowed to avoid3167+ ambiguities (e.g., "foo/foo").3168+3169+ For example, with `-L$HOME/.jq` a module `foo` can be found in3170+ `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.3171+3172+ If "$HOME/.jq" is a file, it is sourced into the main program.3173+3174+ entries:3175+ - title: "`import RelativePathString as NAME [<metadata>];`"3176+ body: |3177+3178+ Imports a module found at the given path relative to a3179+ directory in a search path. A ".jq" suffix will be added to3180+ the relative path string. The module's symbols are prefixed3181+ with "NAME::".3182+3183+ The optional metadata must be a constant jq expression. It3184+ should be an object with keys like "homepage" and so on. At3185+ this time jq only uses the "search" key/value of the metadata.3186+ The metadata is also made available to users via the3187+ `modulemeta` builtin.3188+3189+ The "search" key in the metadata, if present, should have a3190+ string or array value (array of strings); this is the search3191+ path to be prefixed to the top-level search path.3192+3193+ - title: "`include RelativePathString [<metadata>];`"3194+ body: |3195+3196+ Imports a module found at the given path relative to a3197+ directory in a search path as if it were included in place. A3198+ ".jq" suffix will be added to the relative path string. The3199+ module's symbols are imported into the caller's namespace as3200+ if the module's content had been included directly.3201+3202+ The optional metadata must be a constant jq expression. It3203+ should be an object with keys like "homepage" and so on. At3204+ this time jq only uses the "search" key/value of the metadata.3205+ The metadata is also made available to users via the3206+ `modulemeta` builtin.3207+3208+ - title: "`import RelativePathString as $NAME [<metadata>];`"3209+ body: |3210+3211+ Imports a JSON file found at the given path relative to a3212+ directory in a search path. A ".json" suffix will be added to3213+ the relative path string. The file's data will be available3214+ as `$NAME::NAME`.3215+3216+ The optional metadata must be a constant jq expression. It3217+ should be an object with keys like "homepage" and so on. At3218+ this time jq only uses the "search" key/value of the metadata.3219+ The metadata is also made available to users via the3220+ `modulemeta` builtin.3221+3222+ The "search" key in the metadata, if present, should have a3223+ string or array value (array of strings); this is the search3224+ path to be prefixed to the top-level search path.3225+3226+ - title: "`module <metadata>;`"3227+ body: |3228+3229+ This directive is entirely optional. It's not required for3230+ proper operation. It serves only the purpose of providing3231+ metadata that can be read with the `modulemeta` builtin.3232+3233+ The metadata must be a constant jq expression. It should be3234+ an object with keys like "homepage". At this time jq doesn't3235+ use this metadata, but it is made available to users via the3236+ `modulemeta` builtin.3237+3238+ - title: "`modulemeta`"3239+ body: |3240+3241+ Takes a module name as input and outputs the module's metadata3242+ as an object, with the module's imports (including metadata)3243+ as an array value for the "deps" key.3244+3245+ Programs can use this to query a module's metadata, which they3246+ could then use to, for example, search for, download, and3247+ install missing dependencies.3248+3249+ - title: Colors3250+ body: |3251+3252+ To configure alternative colors just set the `JQ_COLORS`3253+ environment variable to colon-delimited list of partial terminal3254+ escape sequences like `"1;31"`, in this order:3255+3256+ - color for `null`3257+ - color for `false`3258+ - color for `true`3259+ - color for numbers3260+ - color for strings3261+ - color for arrays3262+ - color for objects3263+3264+ The default color scheme is the same as setting3265+ `"JQ_COLORS=1;30:0;39:0;39:0;39:0;32:1;39:1;39"`.3266+3267+ This is not a manual for VT100/ANSI escapes. However, each of3268+ these color specifications should consist of two numbers separated3269+ by a semi-colon, where the first number is one of these:3270+3271+ - 1 (bright)3272+ - 2 (dim)3273+ - 4 (underscore)3274+ - 5 (blink)3275+ - 7 (reverse)3276+ - 8 (hidden)3277+3278+ and the second is one of these:3279+3280+ - 30 (black)3281+ - 31 (red)3282+ - 32 (green)3283+ - 33 (yellow)3284+ - 34 (blue)3285+ - 35 (magenta)3286+ - 36 (cyan)3287+ - 37 (white)added:docs/content/manual/manual.yml+3304 added
1+---2+headline: jq Manual (development version)3+4+history: |5+6+ *For released versions, see [jq 1.6](/jq/manual/v1.6),7+ [jq 1.5](/jq/manual/v1.5), [jq 1.4](/jq/manual/v1.4)8+ or [jq 1.3](/jq/manual/v1.3).*9+10+body: |11+12+ A jq program is a "filter": it takes an input, and produces an13+ output. There are a lot of builtin filters for extracting a14+ particular field of an object, or converting a number to a string,15+ or various other standard tasks.16+17+ Filters can be combined in various ways - you can pipe the output of18+ one filter into another filter, or collect the output of a filter19+ into an array.20+21+ Some filters produce multiple results, for instance there's one that22+ produces all the elements of its input array. Piping that filter23+ into a second runs the second filter for each element of the24+ array. Generally, things that would be done with loops and iteration25+ in other languages are just done by gluing filters together in jq.26+27+ It's important to remember that every filter has an input and an28+ output. Even literals like "hello" or 42 are filters - they take an29+ input but always produce the same literal as output. Operations that30+ combine two filters, like addition, generally feed the same input to31+ both and combine the results. So, you can implement an averaging32+ filter as `add / length` - feeding the input array both to the `add`33+ filter and the `length` filter and then performing the division.34+35+ But that's getting ahead of ourselves. :) Let's start with something36+ simpler:37+38+manpage_intro: |39+ jq(1) -- Command-line JSON processor40+ ====================================41+42+ ## SYNOPSIS43+44+ `jq` [<options>...] <filter> [<files>...]45+46+ `jq` can transform JSON in various ways, by selecting, iterating,47+ reducing and otherwise mangling JSON documents. For instance,48+ running the command `jq 'map(.price) | add'` will take an array of49+ JSON objects as input and return the sum of their "price" fields.50+51+ `jq` can accept text input as well, but by default, `jq` reads a52+ stream of JSON entities (including numbers and other literals) from53+ `stdin`. Whitespace is only needed to separate entities such as 154+ and 2, and true and false. One or more <files> may be specified, in55+ which case `jq` will read input from those instead.56+57+ The <options> are described in the [INVOKING JQ] section; they58+ mostly concern input and output formatting. The <filter> is written59+ in the jq language and specifies how to transform the input60+ file or document.61+62+ ## FILTERS63+64+manpage_epilogue: |65+ ## BUGS66+67+ Presumably. Report them or discuss them at:68+69+ https://github.com/stedolan/jq/issues70+71+ ## AUTHOR72+73+ Stephen Dolan `<mu@netsoc.tcd.ie>`74+75+sections:76+ - title: Invoking jq77+ body: |78+79+ jq filters run on a stream of JSON data. The input to jq is80+ parsed as a sequence of whitespace-separated JSON values which81+ are passed through the provided filter one at a time. The82+ output(s) of the filter are written to standard out, again as a83+ sequence of whitespace-separated JSON data.84+85+ Note: it is important to mind the shell's quoting rules. As a86+ general rule it's best to always quote (with single-quote87+ characters) the jq program, as too many characters with special88+ meaning to jq are also shell meta-characters. For example, `jq89+ "foo"` will fail on most Unix shells because that will be the same90+ as `jq foo`, which will generally fail because `foo is not91+ defined`. When using the Windows command shell (cmd.exe) it's92+ best to use double quotes around your jq program when given on the93+ command-line (instead of the `-f program-file` option), but then94+ double-quotes in the jq program need backslash escaping.95+96+ You can affect how jq reads and writes its input and output97+ using some command-line options:98+99+ * `--version`:100+101+ Output the jq version and exit with zero.102+103+ * `--seq`:104+105+ Use the `application/json-seq` MIME type scheme for separating106+ JSON texts in jq's input and output. This means that an ASCII107+ RS (record separator) character is printed before each value on108+ output and an ASCII LF (line feed) is printed after every109+ output. Input JSON texts that fail to parse are ignored (but110+ warned about), discarding all subsequent input until the next111+ RS. This mode also parses the output of jq without the `--seq`112+ option.113+114+ * `--stream`:115+116+ Parse the input in streaming fashion, outputing arrays of path117+ and leaf values (scalars and empty arrays or empty objects).118+ For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]`119+ becomes `[[0],[]]`, `[[1],"a"]`, and `[[1,0],"b"]`.120+121+ This is useful for processing very large inputs. Use this in122+ conjunction with filtering and the `reduce` and `foreach` syntax123+ to reduce large inputs incrementally.124+125+ * `--slurp`/`-s`:126+127+ Instead of running the filter for each JSON object in the128+ input, read the entire input stream into a large array and run129+ the filter just once.130+131+ * `--raw-input`/`-R`:132+133+ Don't parse the input as JSON. Instead, each line of text is134+ passed to the filter as a string. If combined with `--slurp`,135+ then the entire input is passed to the filter as a single long136+ string.137+138+ * `--null-input`/`-n`:139+140+ Don't read any input at all! Instead, the filter is run once141+ using `null` as the input. This is useful when using jq as a142+ simple calculator or to construct JSON data from scratch.143+144+ * `--compact-output` / `-c`:145+146+ By default, jq pretty-prints JSON output. Using this option147+ will result in more compact output by instead putting each148+ JSON object on a single line.149+150+ * `--tab`:151+152+ Use a tab for each indentation level instead of two spaces.153+154+ * `--indent n`:155+156+ Use the given number of spaces (no more than 8) for indentation.157+158+ * `--color-output` / `-C` and `--monochrome-output` / `-M`:159+160+ By default, jq outputs colored JSON if writing to a161+ terminal. You can force it to produce color even if writing to162+ a pipe or a file using `-C`, and disable color with `-M`.163+164+ Colors can be configured with the `JQ_COLORS` environment165+ variable (see below).166+167+ * `--ascii-output` / `-a`:168+169+ jq usually outputs non-ASCII Unicode codepoints as UTF-8, even170+ if the input specified them as escape sequences (like171+ "\u03bc"). Using this option, you can force jq to produce pure172+ ASCII output with every non-ASCII character replaced with the173+ equivalent escape sequence.174+175+ * `--unbuffered`176+177+ Flush the output after each JSON object is printed (useful if178+ you're piping a slow data source into jq and piping jq's179+ output elsewhere).180+181+ * `--sort-keys` / `-S`:182+183+ Output the fields of each object with the keys in sorted order.184+185+ * `--raw-output` / `-r`:186+187+ With this option, if the filter's result is a string then it188+ will be written directly to standard output rather than being189+ formatted as a JSON string with quotes. This can be useful for190+ making jq filters talk to non-JSON-based systems.191+192+ * `--join-output` / `-j`:193+194+ Like `-r` but jq won't print a newline after each output.195+196+ * `-f filename` / `--from-file filename`:197+198+ Read filter from the file rather than from a command line, like199+ awk's -f option. You can also use '#' to make comments.200+201+ * `-Ldirectory` / `-L directory`:202+203+ Prepend `directory` to the search list for modules. If this204+ option is used then no builtin search list is used. See the205+ section on modules below.206+207+ * `-e` / `--exit-status`:208+209+ Sets the exit status of jq to 0 if the last output values was210+ neither `false` nor `null`, 1 if the last output value was211+ either `false` or `null`, or 4 if no valid result was ever212+ produced. Normally jq exits with 2 if there was any usage213+ problem or system error, 3 if there was a jq program compile214+ error, or 0 if the jq program ran.215+216+ Another way to set the exit status is with the `halt_error`217+ builtin function.218+219+ * `--arg name value`:220+221+ This option passes a value to the jq program as a predefined222+ variable. If you run jq with `--arg foo bar`, then `$foo` is223+ available in the program and has the value `"bar"`. Note that224+ `value` will be treated as a string, so `--arg foo 123` will225+ bind `$foo` to `"123"`.226+227+ Named arguments are also available to the jq program as228+ `$ARGS.named`.229+230+ * `--argjson name JSON-text`:231+232+ This option passes a JSON-encoded value to the jq program as a233+ predefined variable. If you run jq with `--argjson foo 123`, then234+ `$foo` is available in the program and has the value `123`.235+236+ * `--slurpfile variable-name filename`:237+238+ This option reads all the JSON texts in the named file and binds239+ an array of the parsed JSON values to the given global variable.240+ If you run jq with `--slurpfile foo bar`, then `$foo` is available241+ in the program and has an array whose elements correspond to the242+ texts in the file named `bar`.243+244+ * `--rawfile variable-name filename`:245+246+ This option reads in the named file and binds its contents to the given247+ global variable. If you run jq with `--rawfile foo bar`, then `$foo` is248+ available in the program and has a string whose contents are to the texs249+ in the file named `bar`.250+251+ * `--argfile variable-name filename`:252+253+ Do not use. Use `--slurpfile` instead.254+255+ (This option is like `--slurpfile`, but when the file has just256+ one text, then that is used, else an array of texts is used as257+ in `--slurpfile`.)258+259+ * `--args`:260+261+ Remaining arguments are positional string arguments. These are262+ available to the jq program as `$ARGS.positional[]`.263+264+ * `--jsonargs`:265+266+ Remaining arguments are positional JSON text arguments. These267+ are available to the jq program as `$ARGS.positional[]`.268+269+ * `--run-tests [filename]`:270+271+ Runs the tests in the given file or standard input. This must272+ be the last option given and does not honor all preceding273+ options. The input consists of comment lines, empty lines, and274+ program lines followed by one input line, as many lines of275+ output as are expected (one per output), and a terminating empty276+ line. Compilation failure tests start with a line containing277+ only "%%FAIL", then a line containing the program to compile,278+ then a line containing an error message to compare to the279+ actual.280+281+ Be warned that this option can change backwards-incompatibly.282+283+ - title: Basic filters284+ entries:285+ - title: "Identity: `.`"286+ body: |287+288+ The absolute simplest filter is `.` . This is a filter that289+ takes its input and produces it unchanged as output. That is,290+ this is the identity operator.291+292+ Since jq by default pretty-prints all output, this trivial293+ program can be a useful way of formatting JSON output from,294+ say, `curl`.295+296+ examples:297+ - program: '.'298+ input: '"Hello, world!"'299+ output: ['"Hello, world!"']300+301+ - title: "Object Identifier-Index: `.foo`, `.foo.bar`"302+ body: |303+304+ The simplest *useful* filter is `.foo`. When given a305+ JSON object (aka dictionary or hash) as input, it produces306+ the value at the key "foo", or null if there's none present.307+308+ A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.309+310+ This syntax only works for simple, identifier-like keys, that311+ is, keys that are all made of alphanumeric characters and312+ underscore, and which do not start with a digit.313+314+ If the key contains special characters, you need to surround315+ it with double quotes like this: `."foo$"`, or else `.["foo$"]`.316+317+ For example `.["foo::bar"]` and `.["foo.bar"]` work while318+ `.foo::bar` does not, and `.foo.bar` means `.["foo"].["bar"]`.319+320+ examples:321+ - program: '.foo'322+ input: '{"foo": 42, "bar": "less interesting data"}'323+ output: [42]324+ - program: '.foo'325+ input: '{"notfoo": true, "alsonotfoo": false}'326+ output: ['null']327+ - program: '.["foo"]'328+ input: '{"foo": 42}'329+ output: [42]330+331+ - title: "Optional Object Identifier-Index: `.foo?`"332+ body: |333+334+ Just like `.foo`, but does not output even an error when `.`335+ is not an array or an object.336+337+ examples:338+ - program: '.foo?'339+ input: '{"foo": 42, "bar": "less interesting data"}'340+ output: [42]341+ - program: '.foo?'342+ input: '{"notfoo": true, "alsonotfoo": false}'343+ output: ['null']344+ - program: '.["foo"]?'345+ input: '{"foo": 42}'346+ output: [42]347+ - program: '[.foo?]'348+ input: '[1,2]'349+ output: ['[]']350+351+ - title: "Generic Object Index: `.[<string>]`"352+ body: |353+354+ You can also look up fields of an object using syntax like355+ `.["foo"]` (.foo above is a shorthand version of this, but356+ only for identifier-like strings).357+358+ - title: "Array Index: `.[2]`"359+ body: |360+361+ When the index value is an integer, `.[<value>]` can index362+ arrays. Arrays are zero-based, so `.[2]` returns the third363+ element.364+365+ Negative indices are allowed, with -1 referring to the last366+ element, -2 referring to the next to last element, and so on.367+368+ examples:369+ - program: '.[0]'370+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'371+ output: ['{"name":"JSON", "good":true}']372+373+ - program: '.[2]'374+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'375+ output: ['null']376+377+ - program: '.[-2]'378+ input: '[1,2,3]'379+ output: ['2']380+381+ - title: "Array/String Slice: `.[10:15]`"382+ body: |383+384+ The `.[10:15]` syntax can be used to return a subarray of an385+ array or substring of a string. The array returned by386+ `.[10:15]` will be of length 5, containing the elements from387+ index 10 (inclusive) to index 15 (exclusive). Either index may388+ be negative (in which case it counts backwards from the end of389+ the array), or omitted (in which case it refers to the start390+ or end of the array).391+392+ examples:393+ - program: '.[2:4]'394+ input: '["a","b","c","d","e"]'395+ output: ['["c", "d"]']396+397+ - program: '.[2:4]'398+ input: '"abcdefghi"'399+ output: ['"cd"']400+401+ - program: '.[:3]'402+ input: '["a","b","c","d","e"]'403+ output: ['["a", "b", "c"]']404+405+ - program: '.[-2:]'406+ input: '["a","b","c","d","e"]'407+ output: ['["d", "e"]']408+409+ - title: "Array/Object Value Iterator: `.[]`"410+ body: |411+412+ If you use the `.[index]` syntax, but omit the index413+ entirely, it will return *all* of the elements of an414+ array. Running `.[]` with the input `[1,2,3]` will produce the415+ numbers as three separate results, rather than as a single416+ array.417+418+ You can also use this on an object, and it will return all419+ the values of the object.420+421+ examples:422+ - program: '.[]'423+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'424+ output:425+ - '{"name":"JSON", "good":true}'426+ - '{"name":"XML", "good":false}'427+428+ - program: '.[]'429+ input: '[]'430+ output: []431+432+ - program: '.[]'433+ input: '{"a": 1, "b": 1}'434+ output: ['1', '1']435+436+ - title: "`.[]?`"437+ body: |438+439+ Like `.[]`, but no errors will be output if . is not an array440+ or object.441+442+ - title: "Comma: `,`"443+ body: |444+445+ If two filters are separated by a comma, then the446+ same input will be fed into both and the two filters' output447+ value streams will be concatenated in order: first, all of the448+ outputs produced by the left expression, and then all of the449+ outputs produced by the right. For instance, filter `.foo,450+ .bar`, produces both the "foo" fields and "bar" fields as451+ separate outputs.452+453+ examples:454+ - program: '.foo, .bar'455+ input: '{"foo": 42, "bar": "something else", "baz": true}'456+ output: ['42', '"something else"']457+458+ - program: ".user, .projects[]"459+ input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'460+ output: ['"stedolan"', '"jq"', '"wikiflow"']461+462+ - program: '.[4,2]'463+ input: '["a","b","c","d","e"]'464+ output: ['"e"', '"c"']465+466+ - title: "Pipe: `|`"467+ body: |468+469+ The | operator combines two filters by feeding the output(s) of470+ the one on the left into the input of the one on the right. It's471+ pretty much the same as the Unix shell's pipe, if you're used to472+ that.473+474+ If the one on the left produces multiple results, the one on475+ the right will be run for each of those results. So, the476+ expression `.[] | .foo` retrieves the "foo" field of each477+ element of the input array.478+479+ Note that `.a.b.c` is the same as `.a | .b | .c`.480+481+ Note too that `.` is the input value at the particular stage482+ in a "pipeline", specifically: where the `.` expression appears.483+ Thus `.a | . | .b` is the same as `.a.b`, as the `.` in the484+ middle refers to whatever value `.a` produced.485+486+ examples:487+ - program: '.[] | .name'488+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'489+ output: ['"JSON"', '"XML"']490+491+ - title: "Parenthesis"492+ body: |493+494+ Parenthesis work as a grouping operator just as in any typical495+ programming language.496+497+ examples:498+ - program: '(. + 2) * 5'499+ input: '1'500+ output: [15]501+502+ - title: Types and Values503+ body: |504+505+ jq supports the same set of datatypes as JSON - numbers,506+ strings, booleans, arrays, objects (which in JSON-speak are507+ hashes with only string keys), and "null".508+509+ Booleans, null, strings and numbers are written the same way as510+ in javascript. Just like everything else in jq, these simple511+ values take an input and produce an output - `42` is a valid jq512+ expression that takes an input, ignores it, and returns 42513+ instead.514+515+ entries:516+ - title: "Array construction: `[]`"517+ body: |518+519+ As in JSON, `[]` is used to construct arrays, as in520+ `[1,2,3]`. The elements of the arrays can be any jq521+ expression, including a pipeline. All of the results produced522+ by all of the expressions are collected into one big array.523+ You can use it to construct an array out of a known quantity524+ of values (as in `[.foo, .bar, .baz]`) or to "collect" all the525+ results of a filter into an array (as in `[.items[].name]`)526+527+ Once you understand the "," operator, you can look at jq's array528+ syntax in a different light: the expression `[1,2,3]` is not using a529+ built-in syntax for comma-separated arrays, but is instead applying530+ the `[]` operator (collect results) to the expression 1,2,3 (which531+ produces three different results).532+533+ If you have a filter `X` that produces four results,534+ then the expression `[X]` will produce a single result, an535+ array of four elements.536+537+ examples:538+ - program: "[.user, .projects[]]"539+ input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'540+ output: ['["stedolan", "jq", "wikiflow"]']541+ - program: "[ .[] | . * 2]"542+ input: '[1, 2, 3]'543+ output: ['[2, 4, 6]']544+545+ - title: "Object Construction: `{}`"546+ body: |547+548+ Like JSON, `{}` is for constructing objects (aka549+ dictionaries or hashes), as in: `{"a": 42, "b": 17}`.550+551+ If the keys are "identifier-like", then the quotes can be left552+ off, as in `{a:42, b:17}`. Variable references as key553+ expressions use the value of the variable as the key. Key554+ expressions other than constant literals, identifiers, or555+ variable references, need to be parenthesized, e.g.,556+ `{("a"+"b"):59}`.557+558+ The value can be any expression (although you may need to wrap559+ it in parentheses if, for example, it contains colons), which560+ gets applied to the {} expression's input (remember, all561+ filters have an input and an output).562+563+ {foo: .bar}564+565+ will produce the JSON object `{"foo": 42}` if given the JSON566+ object `{"bar":42, "baz":43}` as its input. You can use this567+ to select particular fields of an object: if the input is an568+ object with "user", "title", "id", and "content" fields and569+ you just want "user" and "title", you can write570+571+ {user: .user, title: .title}572+573+ Because that is so common, there's a shortcut syntax for it:574+ `{user, title}`.575+576+ If one of the expressions produces multiple results,577+ multiple dictionaries will be produced. If the input's578+579+ {"user":"stedolan","titles":["JQ Primer", "More JQ"]}580+581+ then the expression582+583+ {user, title: .titles[]}584+585+ will produce two outputs:586+587+ {"user":"stedolan", "title": "JQ Primer"}588+ {"user":"stedolan", "title": "More JQ"}589+590+ Putting parentheses around the key means it will be evaluated as an591+ expression. With the same input as above,592+593+ {(.user): .titles}594+595+ produces596+597+ {"stedolan": ["JQ Primer", "More JQ"]}598+599+ Variable references as keys use the value of the variable as600+ the key. Without a value then the variable's name becomes the601+ key and its value becomes the value,602+603+ "f o o" as $foo | "b a r" as $bar | {$foo, $bar:$foo}604+605+ produces606+607+ {"f o o":"f o o","b a r":"f o o"}608+609+ examples:610+ - program: '{user, title: .titles[]}'611+ input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'612+ output:613+ - '{"user":"stedolan", "title": "JQ Primer"}'614+ - '{"user":"stedolan", "title": "More JQ"}'615+ - program: '{(.user): .titles}'616+ input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'617+ output: ['{"stedolan": ["JQ Primer", "More JQ"]}']618+619+ - title: "Recursive Descent: `..`"620+ body: |621+622+ Recursively descends `.`, producing every value. This is the623+ same as the zero-argument `recurse` builtin (see below). This624+ is intended to resemble the XPath `//` operator. Note that625+ `..a` does not work; use `..|.a` instead. In the example626+ below we use `..|.a?` to find all the values of object keys627+ "a" in any object found "below" `.`.628+629+ This is particularly useful in conjunction with `path(EXP)`630+ (also see below) and the `?` operator.631+632+ examples:633+ - program: '..|.a?'634+ input: '[[{"a":1}]]'635+ output: ['1']636+637+ - title: Builtin operators and functions638+ body: |639+640+ Some jq operator (for instance, `+`) do different things641+ depending on the type of their arguments (arrays, numbers,642+ etc.). However, jq never does implicit type conversions. If you643+ try to add a string to an object you'll get an error message and644+ no result.645+646+ entries:647+ - title: "Addition: `+`"648+ body: |649+650+ The operator `+` takes two filters, applies them both651+ to the same input, and adds the results together. What652+ "adding" means depends on the types involved:653+654+ - **Numbers** are added by normal arithmetic.655+656+ - **Arrays** are added by being concatenated into a larger array.657+658+ - **Strings** are added by being joined into a larger string.659+660+ - **Objects** are added by merging, that is, inserting all661+ the key-value pairs from both objects into a single662+ combined object. If both objects contain a value for the663+ same key, the object on the right of the `+` wins. (For664+ recursive merge use the `*` operator.)665+666+ `null` can be added to any value, and returns the other667+ value unchanged.668+669+ examples:670+ - program: '.a + 1'671+ input: '{"a": 7}'672+ output: ['8']673+ - program: '.a + .b'674+ input: '{"a": [1,2], "b": [3,4]}'675+ output: ['[1,2,3,4]']676+ - program: '.a + null'677+ input: '{"a": 1}'678+ output: ['1']679+ - program: '.a + 1'680+ input: '{}'681+ output: ['1']682+ - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'683+ input: 'null'684+ output: ['{"a": 42, "b": 2, "c": 3}']685+686+ - title: "Subtraction: `-`"687+ body: |688+689+ As well as normal arithmetic subtraction on numbers, the `-`690+ operator can be used on arrays to remove all occurrences of691+ the second array's elements from the first array.692+693+ examples:694+ - program: '4 - .a'695+ input: '{"a":3}'696+ output: ['1']697+ - program: . - ["xml", "yaml"]698+ input: '["xml", "yaml", "json"]'699+ output: ['["json"]']700+701+ - title: "Multiplication, division, modulo: `*`, `/`, and `%`"702+ body: |703+704+ These infix operators behave as expected when given two numbers.705+ Division by zero raises an error. `x % y` computes x modulo y.706+707+ Multiplying a string by a number produces the concatenation of708+ that string that many times. `"x" * 0` produces **null**.709+710+ Dividing a string by another splits the first using the second711+ as separators.712+713+ Multiplying two objects will merge them recursively: this works714+ like addition but if both objects contain a value for the715+ same key, and the values are objects, the two are merged with716+ the same strategy.717+718+ examples:719+ - program: '10 / . * 3'720+ input: 5721+ output: [6]722+ - program: '. / ", "'723+ input: '"a, b,c,d, e"'724+ output: ['["a","b,c,d","e"]']725+ - program: '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'726+ input: 'null'727+ output: ['{"k": {"a": 0, "b": 2, "c": 3}}']728+ - program: '.[] | (1 / .)?'729+ input: '[1,0,-1]'730+ output: ['1', '-1']731+732+733+ - title: "`length`"734+ body: |735+736+ The builtin function `length` gets the length of various737+ different types of value:738+739+ - The length of a **string** is the number of Unicode740+ codepoints it contains (which will be the same as its741+ JSON-encoded length in bytes if it's pure ASCII).742+743+ - The length of an **array** is the number of elements.744+745+ - The length of an **object** is the number of key-value pairs.746+747+ - The length of **null** is zero.748+749+ examples:750+ - program: '.[] | length'751+ input: '[[1,2], "string", {"a":2}, null]'752+ output: [2, 6, 1, 0]753+754+755+ - title: "`utf8bytelength`"756+ body: |757+758+ The builtin function `utf8bytelength` outputs the number of759+ bytes used to encode a string in UTF-8.760+761+ examples:762+ - program: 'utf8bytelength'763+ input: '"\u03bc"'764+ output: [2]765+766+ - title: "`keys`, `keys_unsorted`"767+ body: |768+769+ The builtin function `keys`, when given an object, returns770+ its keys in an array.771+772+ The keys are sorted "alphabetically", by unicode codepoint773+ order. This is not an order that makes particular sense in774+ any particular language, but you can count on it being the775+ same for any two objects with the same set of keys,776+ regardless of locale settings.777+778+ When `keys` is given an array, it returns the valid indices779+ for that array: the integers from 0 to length-1.780+781+ The `keys_unsorted` function is just like `keys`, but if782+ the input is an object then the keys will not be sorted,783+ instead the keys will roughly be in insertion order.784+785+ examples:786+ - program: 'keys'787+ input: '{"abc": 1, "abcd": 2, "Foo": 3}'788+ output: ['["Foo", "abc", "abcd"]']789+ - program: 'keys'790+ input: '[42,3,35]'791+ output: ['[0,1,2]']792+793+ - title: "`has(key)`"794+ body: |795+796+ The builtin function `has` returns whether the input object797+ has the given key, or the input array has an element at the798+ given index.799+800+ `has($key)` has the same effect as checking whether `$key`801+ is a member of the array returned by `keys`, although `has`802+ will be faster.803+804+ examples:805+ - program: 'map(has("foo"))'806+ input: '[{"foo": 42}, {}]'807+ output: ['[true, false]']808+ - program: 'map(has(2))'809+ input: '[[0,1], ["a","b","c"]]'810+ output: ['[false, true]']811+812+ - title: "`in`"813+ body: |814+815+ The builtin function `in` returns whether or not the input key is in the816+ given object, or the input index corresponds to an element817+ in the given array. It is, essentially, an inversed version818+ of `has`.819+820+ examples:821+ - program: '.[] | in({"foo": 42})'822+ input: '["foo", "bar"]'823+ output: ['true', 'false']824+ - program: 'map(in([0,1]))'825+ input: '[2, 0]'826+ output: ['[false, true]']827+828+ - title: "`map(x)`, `map_values(x)`"829+ body: |830+831+ For any filter `x`, `map(x)` will run that filter for each832+ element of the input array, and return the outputs in a new833+ array. `map(.+1)` will increment each element of an array of numbers.834+835+ Similarly, `map_values(x)` will run that filter for each element,836+ but it will return an object when an object is passed.837+838+ `map(x)` is equivalent to `[.[] | x]`. In fact, this is how839+ it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`.840+841+ examples:842+ - program: 'map(.+1)'843+ input: '[1,2,3]'844+ output: ['[2,3,4]']845+846+ - program: 'map_values(.+1)'847+ input: '{"a": 1, "b": 2, "c": 3}'848+ output: ['{"a": 2, "b": 3, "c": 4}']849+850+ - title: "`path(path_expression)`"851+ body: |852+853+ Outputs array representations of the given path expression854+ in `.`. The outputs are arrays of strings (object keys)855+ and/or numbers (array indices).856+857+ Path expressions are jq expressions like `.a`, but also `.[]`.858+ There are two types of path expressions: ones that can match859+ exactly, and ones that cannot. For example, `.a.b.c` is an860+ exact match path expression, while `.a[].b` is not.861+862+ `path(exact_path_expression)` will produce the array863+ representation of the path expression even if it does not864+ exist in `.`, if `.` is `null` or an array or an object.865+866+ `path(pattern)` will produce array representations of the867+ paths matching `pattern` if the paths exist in `.`.868+869+ Note that the path expressions are not different from normal870+ expressions. The expression871+ `path(..|select(type=="boolean"))` outputs all the paths to872+ boolean values in `.`, and only those paths.873+874+ examples:875+ - program: 'path(.a[0].b)'876+ input: 'null'877+ output: ['["a",0,"b"]']878+ - program: '[path(..)]'879+ input: '{"a":[{"b":1}]}'880+ output: ['[[],["a"],["a",0],["a",0,"b"]]']881+882+ - title: "`del(path_expression)`"883+ body: |884+885+ The builtin function `del` removes a key and its corresponding886+ value from an object.887+888+ examples:889+ - program: 'del(.foo)'890+ input: '{"foo": 42, "bar": 9001, "baz": 42}'891+ output: ['{"bar": 9001, "baz": 42}']892+ - program: 'del(.[1, 2])'893+ input: '["foo", "bar", "baz"]'894+ output: ['["foo"]']895+896+ - title: "`getpath(PATHS)`"897+ body: |898+899+ The builtin function `getpath` outputs the values in `.` found900+ at each path in `PATHS`.901+902+ examples:903+ - program: 'getpath(["a","b"])'904+ input: 'null'905+ output: ['null']906+ - program: '[getpath(["a","b"], ["a","c"])]'907+ input: '{"a":{"b":0, "c":1}}'908+ output: ['[0, 1]']909+910+ - title: "`setpath(PATHS; VALUE)`"911+ body: |912+913+ The builtin function `setpath` sets the `PATHS` in `.` to `VALUE`.914+915+ examples:916+ - program: 'setpath(["a","b"]; 1)'917+ input: 'null'918+ output: ['{"a": {"b": 1}}']919+ - program: 'setpath(["a","b"]; 1)'920+ input: '{"a":{"b":0}}'921+ output: ['{"a": {"b": 1}}']922+ - program: 'setpath([0,"a"]; 1)'923+ input: 'null'924+ output: ['[{"a":1}]']925+926+ - title: "`delpaths(PATHS)`"927+ body: |928+929+ The builtin function `delpaths` sets the `PATHS` in `.`.930+ `PATHS` must be an array of paths, where each path is an array931+ of strings and numbers.932+933+ examples:934+ - program: 'delpaths([["a","b"]])'935+ input: '{"a":{"b":1},"x":{"y":2}}'936+ output: ['{"a":{},"x":{"y":2}}']937+938+ - title: "`to_entries`, `from_entries`, `with_entries`"939+ body: |940+941+ These functions convert between an object and an array of942+ key-value pairs. If `to_entries` is passed an object, then943+ for each `k: v` entry in the input, the output array944+ includes `{"key": k, "value": v}`.945+946+ `from_entries` does the opposite conversion, and947+ `with_entries(foo)` is a shorthand for `to_entries |948+ map(foo) | from_entries`, useful for doing some operation to949+ all keys and values of an object. `from_entries` accepts key, Key,950+ name, Name, value and Value as keys.951+952+ examples:953+ - program: 'to_entries'954+ input: '{"a": 1, "b": 2}'955+ output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']956+ - program: 'from_entries'957+ input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'958+ output: ['{"a": 1, "b": 2}']959+ - program: 'with_entries(.key |= "KEY_" + .)'960+ input: '{"a": 1, "b": 2}'961+ output: ['{"KEY_a": 1, "KEY_b": 2}']962+963+964+ - title: "`select(boolean_expression)`"965+ body: |966+967+ The function `select(foo)` produces its input unchanged if968+ `foo` returns true for that input, and produces no output969+ otherwise.970+971+ It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`972+ will give you `[2,3]`.973+974+ examples:975+ - program: 'map(select(. >= 2))'976+ input: '[1,5,3,0,7]'977+ output: ['[5,3,7]']978+ - program: '.[] | select(.id == "second")'979+ input: '[{"id": "first", "val": 1}, {"id": "second", "val": 2}]'980+ output: ['{"id": "second", "val": 2}']981+982+983+ - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"984+ body: |985+986+ These built-ins select only inputs that are arrays, objects,987+ iterables (arrays or objects), booleans, numbers, normal988+ numbers, finite numbers, strings, null, non-null values, and989+ non-iterables, respectively.990+991+ examples:992+ - program: '.[]|numbers'993+ input: '[[],{},1,"foo",null,true,false]'994+ output: ['1']995+996+ - title: "`empty`"997+ body: |998+999+ `empty` returns no results. None at all. Not even `null`.1000+1001+ It's useful on occasion. You'll know if you need it :)1002+1003+ examples:1004+ - program: '1, empty, 2'1005+ input: 'null'1006+ output: [1, 2]1007+ - program: '[1,2,empty,3]'1008+ input: 'null'1009+ output: ['[1,2,3]']1010+1011+ - title: "`error(message)`"1012+ body: |1013+1014+ Produces an error, just like `.a` applied to values other than1015+ null and objects would, but with the given message as the1016+ error's value. Errors can be caught with try/catch; see below.1017+1018+ - title: "`halt`"1019+ body: |1020+1021+ Stops the jq program with no further outputs. jq will exit1022+ with exit status `0`.1023+1024+ - title: "`halt_error`, `halt_error(exit_code)`"1025+ body: |1026+1027+ Stops the jq program with no further outputs. The input will1028+ be printed on `stderr` as raw output (i.e., strings will not1029+ have double quotes) with no decoration, not even a newline.1030+1031+ The given `exit_code` (defaulting to `5`) will be jq's exit1032+ status.1033+1034+ For example, `"Error: somthing went wrong\n"|halt_error(1)`.1035+1036+ - title: "`$__loc__`"1037+ body: |1038+1039+ Produces an object with a "file" key and a "line" key, with1040+ the filename and line number where `$__loc__` occurs, as1041+ values.1042+1043+ examples:1044+ - program: 'try error("\($__loc__)") catch .'1045+ input: 'null'1046+ output: ['"{\"file\":\"<top-level>\",\"line\":1}"']1047+1048+ - title: "`paths`, `paths(node_filter)`, `leaf_paths`"1049+ body: |1050+1051+ `paths` outputs the paths to all the elements in its input1052+ (except it does not output the empty list, representing .1053+ itself).1054+1055+ `paths(f)` outputs the paths to any values for which `f` is true.1056+ That is, `paths(numbers)` outputs the paths to all numeric1057+ values.1058+1059+ `leaf_paths` is an alias of `paths(scalars)`; `leaf_paths` is1060+ *deprecated* and will be removed in the next major release.1061+1062+ examples:1063+ - program: '[paths]'1064+ input: '[1,[[],{"a":2}]]'1065+ output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']1066+ - program: '[paths(scalars)]'1067+ input: '[1,[[],{"a":2}]]'1068+ output: ['[[0],[1,1,"a"]]']1069+1070+ - title: "`add`"1071+ body: |1072+1073+ The filter `add` takes as input an array, and produces as1074+ output the elements of the array added together. This might1075+ mean summed, concatenated or merged depending on the types1076+ of the elements of the input array - the rules are the same1077+ as those for the `+` operator (described above).1078+1079+ If the input is an empty array, `add` returns `null`.1080+1081+ examples:1082+ - program: add1083+ input: '["a","b","c"]'1084+ output: ['"abc"']1085+ - program: add1086+ input: '[1, 2, 3]'1087+ output: [6]1088+ - program: add1089+ input: '[]'1090+ output: ["null"]1091+1092+ - title: "`any`, `any(condition)`, `any(generator; condition)`"1093+ body: |1094+1095+ The filter `any` takes as input an array of boolean values,1096+ and produces `true` as output if any of the elements of1097+ the array are `true`.1098+1099+ If the input is an empty array, `any` returns `false`.1100+1101+ The `any(condition)` form applies the given condition to the1102+ elements of the input array.1103+1104+ The `any(generator; condition)` form applies the given1105+ condition to all the outputs of the given generator.1106+1107+ examples:1108+ - program: any1109+ input: '[true, false]'1110+ output: ["true"]1111+ - program: any1112+ input: '[false, false]'1113+ output: ["false"]1114+ - program: any1115+ input: '[]'1116+ output: ["false"]1117+1118+ - title: "`all`, `all(condition)`, `all(generator; condition)`"1119+ body: |1120+1121+ The filter `all` takes as input an array of boolean values,1122+ and produces `true` as output if all of the elements of1123+ the array are `true`.1124+1125+ The `all(condition)` form applies the given condition to the1126+ elements of the input array.1127+1128+ The `all(generator; condition)` form applies the given1129+ condition to all the outputs of the given generator.1130+1131+ If the input is an empty array, `all` returns `true`.1132+1133+ examples:1134+ - program: all1135+ input: '[true, false]'1136+ output: ["false"]1137+ - program: all1138+ input: '[true, true]'1139+ output: ["true"]1140+ - program: all1141+ input: '[]'1142+ output: ["true"]1143+1144+ - title: "`flatten`, `flatten(depth)`"1145+ body: |1146+1147+ The filter `flatten` takes as input an array of nested arrays,1148+ and produces a flat array in which all arrays inside the original1149+ array have been recursively replaced by their values. You can pass1150+ an argument to it to specify how many levels of nesting to flatten.1151+1152+ `flatten(2)` is like `flatten`, but going only up to two1153+ levels deep.1154+1155+ examples:1156+ - program: flatten1157+ input: '[1, [2], [[3]]]'1158+ output: ["[1, 2, 3]"]1159+ - program: flatten(1)1160+ input: '[1, [2], [[3]]]'1161+ output: ["[1, 2, [3]]"]1162+ - program: flatten1163+ input: '[[]]'1164+ output: ["[]"]1165+ - program: flatten1166+ input: '[{"foo": "bar"}, [{"foo": "baz"}]]'1167+ output: ['[{"foo": "bar"}, {"foo": "baz"}]']1168+1169+ - title: "`range(upto)`, `range(from;upto)` `range(from;upto;by)`"1170+ body: |1171+1172+ The `range` function produces a range of numbers. `range(4;10)`1173+ produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers1174+ are produced as separate outputs. Use `[range(4;10)]` to get a range as1175+ an array.1176+1177+ The one argument form generates numbers from 0 to the given1178+ number, with an increment of 1.1179+1180+ The two argument form generates numbers from `from` to `upto`1181+ with an increment of 1.1182+1183+ The three argument form generates numbers `from` to `upto`1184+ with an increment of `by`.1185+1186+ examples:1187+ - program: 'range(2;4)'1188+ input: 'null'1189+ output: ['2', '3']1190+ - program: '[range(2;4)]'1191+ input: 'null'1192+ output: ['[2,3]']1193+ - program: '[range(4)]'1194+ input: 'null'1195+ output: ['[0,1,2,3]']1196+ - program: '[range(0;10;3)]'1197+ input: 'null'1198+ output: ['[0,3,6,9]']1199+ - program: '[range(0;10;-1)]'1200+ input: 'null'1201+ output: ['[]']1202+ - program: '[range(0;-5;-1)]'1203+ input: 'null'1204+ output: ['[0,-1,-2,-3,-4]']1205+1206+ - title: "`floor`"1207+ body: |1208+1209+ The `floor` function returns the floor of its numeric input.1210+1211+ examples:1212+ - program: 'floor'1213+ input: '3.14159'1214+ output: ['3']1215+1216+ - title: "`sqrt`"1217+ body: |1218+1219+ The `sqrt` function returns the square root of its numeric input.1220+1221+ examples:1222+ - program: 'sqrt'1223+ input: '9'1224+ output: ['3']1225+1226+ - title: "`tonumber`"1227+ body: |1228+1229+ The `tonumber` function parses its input as a number. It1230+ will convert correctly-formatted strings to their numeric1231+ equivalent, leave numbers alone, and give an error on all other input.1232+1233+ examples:1234+ - program: '.[] | tonumber'1235+ input: '[1, "1"]'1236+ output: [1, 1]1237+1238+ - title: "`tostring`"1239+ body: |1240+1241+ The `tostring` function prints its input as a1242+ string. Strings are left unchanged, and all other values are1243+ JSON-encoded.1244+1245+ examples:1246+ - program: '.[] | tostring'1247+ input: '[1, "1", [1]]'1248+ output: ['"1"', '"1"', '"[1]"']1249+1250+ - title: "`type`"1251+ body: |1252+1253+ The `type` function returns the type of its argument as a1254+ string, which is one of null, boolean, number, string, array1255+ or object.1256+1257+ examples:1258+ - program: 'map(type)'1259+ input: '[0, false, [], {}, null, "hello"]'1260+ output: ['["number", "boolean", "array", "object", "null", "string"]']1261+1262+ - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1263+ body: |1264+1265+ Some arithmetic operations can yield infinities and "not a1266+ number" (NaN) values. The `isinfinite` builtin returns `true`1267+ if its input is infinite. The `isnan` builtin returns `true`1268+ if its input is a NaN. The `infinite` builtin returns a1269+ positive infinite value. The `nan` builtin returns a NaN.1270+ The `isnormal` builtin returns true if its input is a normal1271+ number.1272+1273+ Note that division by zero raises an error.1274+1275+ Currently most arithmetic operations operating on infinities,1276+ NaNs, and sub-normals do not raise errors.1277+1278+ examples:1279+ - program: '.[] | (infinite * .) < 0'1280+ input: '[-1, 1]'1281+ output: ['true', 'false']1282+ - program: 'infinite, nan | type'1283+ input: 'null'1284+ output: ['"number"', '"number"']1285+1286+ - title: "`sort, sort_by(path_expression)`"1287+ body: |1288+1289+ The `sort` functions sorts its input, which must be an1290+ array. Values are sorted in the following order:1291+1292+ * `null`1293+ * `false`1294+ * `true`1295+ * numbers1296+ * strings, in alphabetical order (by unicode codepoint value)1297+ * arrays, in lexical order1298+ * objects1299+1300+ The ordering for objects is a little complex: first they're1301+ compared by comparing their sets of keys (as arrays in1302+ sorted order), and if their keys are equal then the values1303+ are compared key by key.1304+1305+ `sort` may be used to sort by a particular field of an1306+ object, or by applying any jq filter.1307+1308+ `sort_by(foo)` compares two elements by comparing the result of1309+ `foo` on each element.1310+1311+ examples:1312+ - program: 'sort'1313+ input: '[8,3,null,6]'1314+ output: ['[null,3,6,8]']1315+ - program: 'sort_by(.foo)'1316+ input: '[{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}]'1317+ output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']1318+1319+ - title: "`group_by(path_expression)`"1320+ body: |1321+1322+ `group_by(.foo)` takes as input an array, groups the1323+ elements having the same `.foo` field into separate arrays,1324+ and produces all of these arrays as elements of a larger1325+ array, sorted by the value of the `.foo` field.1326+1327+ Any jq expression, not just a field access, may be used in1328+ place of `.foo`. The sorting order is the same as described1329+ in the `sort` function above.1330+1331+ examples:1332+ - program: 'group_by(.foo)'1333+ input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'1334+ output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']1335+1336+ - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1337+ body: |1338+1339+ Find the minimum or maximum element of the input array.1340+1341+ The `min_by(path_exp)` and `max_by(path_exp)` functions allow1342+ you to specify a particular field or property to examine, e.g.1343+ `min_by(.foo)` finds the object with the smallest `foo` field.1344+1345+ examples:1346+ - program: 'min'1347+ input: '[5,4,2,7]'1348+ output: ['2']1349+ - program: 'max_by(.foo)'1350+ input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'1351+ output: ['{"foo":2, "bar":3}']1352+1353+ - title: "`unique`, `unique_by(path_exp)`"1354+ body: |1355+1356+ The `unique` function takes as input an array and produces1357+ an array of the same elements, in sorted order, with1358+ duplicates removed.1359+1360+ The `unique_by(path_exp)` function will keep only one element1361+ for each value obtained by applying the argument. Think of it1362+ as making an array by taking one element out of every group1363+ produced by `group`.1364+1365+ examples:1366+ - program: 'unique'1367+ input: '[1,2,5,3,5,3,1,3]'1368+ output: ['[1,2,3,5]']1369+ - program: 'unique_by(.foo)'1370+ input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'1371+ output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']1372+ - program: 'unique_by(length)'1373+ input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'1374+ output: ['["bacon", "chunky", "asparagus"]']1375+1376+ - title: "`reverse`"1377+ body: |1378+1379+ This function reverses an array.1380+1381+ examples:1382+ - program: 'reverse'1383+ input: '[1,2,3,4]'1384+ output: ['[4,3,2,1]']1385+1386+ - title: "`contains(element)`"1387+ body: |1388+1389+ The filter `contains(b)` will produce true if b is1390+ completely contained within the input. A string B is1391+ contained in a string A if B is a substring of A. An array B1392+ is contained in an array A if all elements in B are1393+ contained in any element in A. An object B is contained in1394+ object A if all of the values in B are contained in the1395+ value in A with the same key. All other types are assumed to1396+ be contained in each other if they are equal.1397+1398+ examples:1399+ - program: 'contains("bar")'1400+ input: '"foobar"'1401+ output: ['true']1402+ - program: 'contains(["baz", "bar"])'1403+ input: '["foobar", "foobaz", "blarp"]'1404+ output: ['true']1405+ - program: 'contains(["bazzzzz", "bar"])'1406+ input: '["foobar", "foobaz", "blarp"]'1407+ output: ['false']1408+ - program: 'contains({foo: 12, bar: [{barp: 12}]})'1409+ input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1410+ output: ['true']1411+ - program: 'contains({foo: 12, bar: [{barp: 15}]})'1412+ input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1413+ output: ['false']1414+1415+ - title: "`indices(s)`"1416+ body: |1417+1418+ Outputs an array containing the indices in `.` where `s`1419+ occurs. The input may be an array, in which case if `s` is an1420+ array then the indices output will be those where all elements1421+ in `.` match those of `s`.1422+1423+ examples:1424+ - program: 'indices(", ")'1425+ input: '"a,b, cd, efg, hijk"'1426+ output: ['[3,7,12]']1427+ - program: 'indices(1)'1428+ input: '[0,1,2,1,3,1,4]'1429+ output: ['[1,3,5]']1430+ - program: 'indices([1,2])'1431+ input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1432+ output: ['[1,8]']1433+1434+ - title: "`index(s)`, `rindex(s)`"1435+ body: |1436+1437+ Outputs the index of the first (`index`) or last (`rindex`)1438+ occurrence of `s` in the input.1439+1440+ examples:1441+ - program: 'index(", ")'1442+ input: '"a,b, cd, efg, hijk"'1443+ output: ['3']1444+ - program: 'rindex(", ")'1445+ input: '"a,b, cd, efg, hijk"'1446+ output: ['12']1447+1448+ - title: "`inside`"1449+ body: |1450+1451+ The filter `inside(b)` will produce true if the input is1452+ completely contained within b. It is, essentially, an1453+ inversed version of `contains`.1454+1455+ examples:1456+ - program: 'inside("foobar")'1457+ input: '"bar"'1458+ output: ['true']1459+ - program: 'inside(["foobar", "foobaz", "blarp"])'1460+ input: '["baz", "bar"]'1461+ output: ['true']1462+ - program: 'inside(["foobar", "foobaz", "blarp"])'1463+ input: '["bazzzzz", "bar"]'1464+ output: ['false']1465+ - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1466+ input: '{"foo": 12, "bar": [{"barp": 12}]}'1467+ output: ['true']1468+ - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1469+ input: '{"foo": 12, "bar": [{"barp": 15}]}'1470+ output: ['false']1471+1472+ - title: "`startswith(str)`"1473+ body: |1474+1475+ Outputs `true` if . starts with the given string argument.1476+1477+ examples:1478+ - program: '[.[]|startswith("foo")]'1479+ input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1480+ output: ['[false, true, false, true, false]']1481+1482+ - title: "`endswith(str)`"1483+ body: |1484+1485+ Outputs `true` if . ends with the given string argument.1486+1487+ examples:1488+ - program: '[.[]|endswith("foo")]'1489+ input: '["foobar", "barfoo"]'1490+ output: ['[false, true]']1491+1492+ - title: "`combinations`, `combinations(n)`"1493+ body: |1494+1495+ Outputs all combinations of the elements of the arrays in the1496+ input array. If given an argument `n`, it outputs all combinations1497+ of `n` repetitions of the input array.1498+1499+ examples:1500+ - program: 'combinations'1501+ input: '[[1,2], [3, 4]]'1502+ output: ['[1, 3]', '[1, 4]', '[2, 3]', '[2, 4]']1503+ - program: 'combinations(2)'1504+ input: '[0, 1]'1505+ output: ['[0, 0]', '[0, 1]', '[1, 0]', '[1, 1]']1506+1507+ - title: "`ltrimstr(str)`"1508+ body: |1509+1510+ Outputs its input with the given prefix string removed, if it1511+ starts with it.1512+1513+ examples:1514+ - program: '[.[]|ltrimstr("foo")]'1515+ input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1516+ output: ['["fo","","barfoo","bar","afoo"]']1517+1518+ - title: "`rtrimstr(str)`"1519+ body: |1520+1521+ Outputs its input with the given suffix string removed, if it1522+ ends with it.1523+1524+ examples:1525+ - program: '[.[]|rtrimstr("foo")]'1526+ input: '["fo", "foo", "barfoo", "foobar", "foob"]'1527+ output: ['["fo","","bar","foobar","foob"]']1528+1529+ - title: "`explode`"1530+ body: |1531+1532+ Converts an input string into an array of the string's1533+ codepoint numbers.1534+1535+ examples:1536+ - program: 'explode'1537+ input: '"foobar"'1538+ output: ['[102,111,111,98,97,114]']1539+1540+ - title: "`implode`"1541+ body: |1542+1543+ The inverse of explode.1544+1545+ examples:1546+ - program: 'implode'1547+ input: '[65, 66, 67]'1548+ output: ['"ABC"']1549+1550+ - title: "`split(str)`"1551+ body: |1552+1553+ Splits an input string on the separator argument.1554+1555+ examples:1556+ - program: 'split(", ")'1557+ input: '"a, b,c,d, e, "'1558+ output: ['["a","b,c,d","e",""]']1559+1560+ - title: "`join(str)`"1561+ body: |1562+1563+ Joins the array of elements given as input, using the1564+ argument as separator. It is the inverse of `split`: that is,1565+ running `split("foo") | join("foo")` over any input string1566+ returns said input string.1567+1568+ Numbers and booleans in the input are converted to strings.1569+ Null values are treated as empty strings. Arrays and objects1570+ in the input are not supported.1571+1572+ examples:1573+ - program: 'join(", ")'1574+ input: '["a","b,c,d","e"]'1575+ output: ['"a, b,c,d, e"']1576+ - program: 'join(" ")'1577+ input: '["a",1,2.3,true,null,false]'1578+ output: ['"a 1 2.3 true false"']1579+1580+ - title: "`ascii_downcase`, `ascii_upcase`"1581+ body: |1582+1583+ Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1584+ converted to the specified case.1585+1586+ example:1587+ - program: 'ascii_upcase'1588+ input: '"useful but not for é"'1589+ output: '"USEFUL BUT NOT FOR é"'1590+1591+ - title: "`while(cond; update)`"1592+ body: |1593+1594+ The `while(cond; update)` function allows you to repeatedly1595+ apply an update to `.` until `cond` is false.1596+1597+ Note that `while(cond; update)` is internally defined as a1598+ recursive jq function. Recursive calls within `while` will1599+ not consume additional memory if `update` produces at most one1600+ output for each input. See advanced topics below.1601+1602+ examples:1603+ - program: '[while(.<100; .*2)]'1604+ input: '1'1605+ output: ['[1,2,4,8,16,32,64]']1606+1607+ - title: "`until(cond; next)`"1608+ body: |1609+1610+ The `until(cond; next)` function allows you to repeatedly1611+ apply the expression `next`, initially to `.` then to its own1612+ output, until `cond` is true. For example, this can be used1613+ to implement a factorial function (see below).1614+1615+ Note that `until(cond; next)` is internally defined as a1616+ recursive jq function. Recursive calls within `until()` will1617+ not consume additional memory if `next` produces at most one1618+ output for each input. See advanced topics below.1619+1620+ examples:1621+ - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1622+ input: '4'1623+ output: ['24']1624+1625+1626+ - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`, `recurse_down`"1627+ body: |1628+1629+ The `recurse(f)` function allows you to search through a1630+ recursive structure, and extract interesting data from all1631+ levels. Suppose your input represents a filesystem:1632+1633+ {"name": "/", "children": [1634+ {"name": "/bin", "children": [1635+ {"name": "/bin/ls", "children": []},1636+ {"name": "/bin/sh", "children": []}]},1637+ {"name": "/home", "children": [1638+ {"name": "/home/stephen", "children": [1639+ {"name": "/home/stephen/jq", "children": []}]}]}]}1640+1641+ Now suppose you want to extract all of the filenames1642+ present. You need to retrieve `.name`, `.children[].name`,1643+ `.children[].children[].name`, and so on. You can do this1644+ with:1645+1646+ recurse(.children[]) | .name1647+1648+ When called without an argument, `recurse` is equivalent to1649+ `recurse(.[]?)`.1650+1651+ `recurse(f)` is identical to `recurse(f; . != null)` and can be1652+ used without concerns about recursion depth.1653+1654+ `recurse(f; condition)` is a generator which begins by1655+ emitting . and then emits in turn .|f, .|f|f, .|f|f|f, ... so long1656+ as the computed value satisfies the condition. For example,1657+ to generate all the integers, at least in principle, one1658+ could write `recurse(.+1; true)`.1659+1660+ For legacy reasons, `recurse_down` exists as an alias to1661+ calling `recurse` without arguments. This alias is considered1662+ *deprecated* and will be removed in the next major release.1663+1664+ The recursive calls in `recurse` will not consume additional1665+ memory whenever `f` produces at most a single output for each1666+ input.1667+1668+ examples:1669+ - program: 'recurse(.foo[])'1670+ input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'1671+ output:1672+ - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'1673+ - '{"foo":[]}'1674+ - '{"foo":[{"foo":[]}]}'1675+ - '{"foo":[]}'1676+1677+ - program: 'recurse'1678+ input: '{"a":0,"b":[1]}'1679+ output:1680+ - '{"a":0,"b":[1]}'1681+ - '0'1682+ - '[1]'1683+ - '1'1684+1685+ - program: 'recurse(. * .; . < 20)'1686+ input: 21687+ output:1688+ - 21689+ - 41690+ - 161691+1692+ - title: "`walk(f)`"1693+ body: |1694+1695+ The `walk(f)` function applies f recursively to every1696+ component of the input entity. When an array is1697+ encountered, f is first applied to its elements and then to1698+ the array itself; when an object is encountered, f is first1699+ applied to all the values and then to the object. In1700+ practice, f will usually test the type of its input, as1701+ illustrated in the following examples. The first example1702+ highlights the usefulness of processing the elements of an1703+ array of arrays before processing the array itself. The second1704+ example shows how all the keys of all the objects within the1705+ input can be considered for alteration.1706+1707+ examples:1708+ - program: 'walk(if type == "array" then sort else . end)'1709+ input: '[[4, 1, 7], [8, 5, 2], [3, 6, 9]]'1710+ output:1711+ - '[[1,4,7],[2,5,8],[3,6,9]]'1712+1713+ - program: 'walk( if type == "object" then with_entries( .key |= sub( "^_+"; "") ) else . end )'1714+ input: '[ { "_a": { "__b": 2 } } ]'1715+ output:1716+ - '[{"a":{"b":2}}]'1717+1718+ - title: "`$ENV`, `env`"1719+ body: |1720+1721+ `$ENV` is an object representing the environment variables as1722+ set when the jq program started.1723+1724+ `env` outputs an object representing jq's current environment.1725+1726+ At the moment there is no builtin for setting environment1727+ variables.1728+1729+ examples:1730+ - program: '$ENV.PAGER'1731+ input: 'null'1732+ output: ['"less"']1733+1734+ - program: 'env.PAGER'1735+ input: 'null'1736+ output: ['"less"']1737+1738+ - title: "`transpose`"1739+ body: |1740+1741+ Transpose a possibly jagged matrix (an array of arrays).1742+ Rows are padded with nulls so the result is always rectangular.1743+1744+ examples:1745+ - program: 'transpose'1746+ input: '[[1], [2,3]]'1747+ output: ['[[1,2],[null,3]]']1748+1749+ - title: "`bsearch(x)`"1750+ body: |1751+1752+ bsearch(x) conducts a binary search for x in the input1753+ array. If the input is sorted and contains x, then1754+ bsearch(x) will return its index in the array; otherwise, if1755+ the array is sorted, it will return (-1 - ix) where ix is an1756+ insertion point such that the array would still be sorted1757+ after the insertion of x at ix. If the array is not sorted,1758+ bsearch(x) will return an integer that is probably of no1759+ interest.1760+1761+ examples:1762+ - program: 'bsearch(0)'1763+ input: '[0,1]'1764+ output: ['0']1765+ - program: 'bsearch(0)'1766+ input: '[1,2,3]'1767+ output: ['-1']1768+ - program: 'bsearch(4) as $ix | if $ix < 0 then .[-(1+$ix)] = 4 else . end'1769+ input: '[1,2,3]'1770+ output: ['[1,2,3,4]']1771+1772+ - title: "String interpolation - `\\(foo)`"1773+ body: |1774+1775+ Inside a string, you can put an expression inside parens1776+ after a backslash. Whatever the expression returns will be1777+ interpolated into the string.1778+1779+ examples:1780+ - program: '"The input was \(.), which is one less than \(.+1)"'1781+ input: '42'1782+ output: ['"The input was 42, which is one less than 43"']1783+1784+ - title: "Convert to/from JSON"1785+ body: |1786+1787+ The `tojson` and `fromjson` builtins dump values as JSON texts1788+ or parse JSON texts into values, respectively. The tojson1789+ builtin differs from tostring in that tostring returns strings1790+ unmodified, while tojson encodes strings as JSON strings.1791+1792+ examples:1793+ - program: '[.[]|tostring]'1794+ input: '[1, "foo", ["foo"]]'1795+ output: ['["1","foo","[\"foo\"]"]']1796+ - program: '[.[]|tojson]'1797+ input: '[1, "foo", ["foo"]]'1798+ output: ['["1","\"foo\"","[\"foo\"]"]']1799+ - program: '[.[]|tojson|fromjson]'1800+ input: '[1, "foo", ["foo"]]'1801+ output: ['[1,"foo",["foo"]]']1802+1803+ - title: "Format strings and escaping"1804+ body: |1805+1806+ The `@foo` syntax is used to format and escape strings,1807+ which is useful for building URLs, documents in a language1808+ like HTML or XML, and so forth. `@foo` can be used as a1809+ filter on its own, the possible escapings are:1810+1811+ * `@text`:1812+1813+ Calls `tostring`, see that function for details.1814+1815+ * `@json`:1816+1817+ Serializes the input as JSON.1818+1819+ * `@html`:1820+1821+ Applies HTML/XML escaping, by mapping the characters1822+ `<>&'"` to their entity equivalents `<`, `>`,1823+ `&`, `'`, `"`.1824+1825+ * `@uri`:1826+1827+ Applies percent-encoding, by mapping all reserved URI1828+ characters to a `%XX` sequence.1829+1830+ * `@csv`:1831+1832+ The input must be an array, and it is rendered as CSV1833+ with double quotes for strings, and quotes escaped by1834+ repetition.1835+1836+ * `@tsv`:1837+1838+ The input must be an array, and it is rendered as TSV1839+ (tab-separated values). Each input array will be printed as1840+ a single line. Fields are separated by a single1841+ tab (ascii `0x09`). Input characters line-feed (ascii `0x0a`),1842+ carriage-return (ascii `0x0d`), tab (ascii `0x09`) and1843+ backslash (ascii `0x5c`) will be output as escape sequences1844+ `\n`, `\r`, `\t`, `\\` respectively.1845+1846+ * `@sh`:1847+1848+ The input is escaped suitable for use in a command-line1849+ for a POSIX shell. If the input is an array, the output1850+ will be a series of space-separated strings.1851+1852+ * `@base64`:1853+1854+ The input is converted to base64 as specified by RFC 4648.1855+1856+ * `@base64d`:1857+1858+ The inverse of `@base64`, input is decoded as specified by RFC 4648.1859+ Note\: If the decoded string is not UTF-8, the results are undefined.1860+1861+ This syntax can be combined with string interpolation in a1862+ useful way. You can follow a `@foo` token with a string1863+ literal. The contents of the string literal will *not* be1864+ escaped. However, all interpolations made inside that string1865+ literal will be escaped. For instance,1866+1867+ @uri "https://www.google.com/search?q=\(.search)"1868+1869+ will produce the following output for the input1870+ `{"search":"what is jq?"}`:1871+1872+ "https://www.google.com/search?q=what%20is%20jq%3F"1873+1874+ Note that the slashes, question mark, etc. in the URL are1875+ not escaped, as they were part of the string literal.1876+1877+ examples:1878+ - program: '@html'1879+ input: '"This works if x < y"'1880+ output: ['"This works if x < y"']1881+1882+# - program: '@html "<span>Anonymous said: \(.)</span>"'1883+# input: '"<script>alert(\"lol hax\");</script>"'1884+# output: ["<span>Anonymous said: <script>alert("lol hax");</script></span>"]1885+1886+ - program: '@sh "echo \(.)"'1887+ input: "\"O'Hara's Ale\""1888+ output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]1889+1890+ - program: '@base64'1891+ input: '"This is a message"'1892+ output: ['"VGhpcyBpcyBhIG1lc3NhZ2U="']1893+1894+ - program: '@base64d'1895+ input: '"VGhpcyBpcyBhIG1lc3NhZ2U="'1896+ output: ['"This is a message"']1897+1898+ - title: "Dates"1899+ body: |1900+1901+ jq provides some basic date handling functionality, with some1902+ high-level and low-level builtins. In all cases these1903+ builtins deal exclusively with time in UTC.1904+1905+ The `fromdateiso8601` builtin parses datetimes in the ISO 86011906+ format to a number of seconds since the Unix epoch1907+ (1970-01-01T00:00:00Z). The `todateiso8601` builtin does the1908+ inverse.1909+1910+ The `fromdate` builtin parses datetime strings. Currently1911+ `fromdate` only supports ISO 8601 datetime strings, but in the1912+ future it will attempt to parse datetime strings in more1913+ formats.1914+1915+ The `todate` builtin is an alias for `todateiso8601`.1916+1917+ The `now` builtin outputs the current time, in seconds since1918+ the Unix epoch.1919+1920+ Low-level jq interfaces to the C-library time functions are1921+ also provided: `strptime`, `strftime`, `strflocaltime`,1922+ `mktime`, `gmtime`, and `localtime`. Refer to your host1923+ operating system's documentation for the format strings used1924+ by `strptime` and `strftime`. Note: these are not necessarily1925+ stable interfaces in jq, particularly as to their localization1926+ functionality.1927+1928+ The `gmtime` builtin consumes a number of seconds since the1929+ Unix epoch and outputs a "broken down time" representation of1930+ Greenwhich Meridian time as an array of numbers representing1931+ (in this order): the year, the month (zero-based), the day of1932+ the month (one-based), the hour of the day, the minute of the1933+ hour, the second of the minute, the day of the week, and the1934+ day of the year -- all one-based unless otherwise stated. The1935+ day of the week number may be wrong on some systems for dates1936+ before March 1st 1900, or after December 31 2099.1937+1938+ The `localtime` builtin works like the `gmtime` builtin, but1939+ using the local timezone setting.1940+1941+ The `mktime` builtin consumes "broken down time"1942+ representations of time output by `gmtime` and `strptime`.1943+1944+ The `strptime(fmt)` builtin parses input strings matching the1945+ `fmt` argument. The output is in the "broken down time"1946+ representation consumed by `gmtime` and output by `mktime`.1947+1948+ The `strftime(fmt)` builtin formats a time (GMT) with the1949+ given format. The `strflocaltime` does the same, but using1950+ the local timezone setting.1951+1952+ The format strings for `strptime` and `strftime` are described1953+ in typical C library documentation. The format string for ISO1954+ 8601 datetime is `"%Y-%m-%dT%H:%M:%SZ"`.1955+1956+ jq may not support some or all of this date functionality on1957+ some systems. In particular, the `%u` and `%j` specifiers for1958+ `strptime(fmt)` are not supported on macOS.1959+1960+ examples:1961+ - program: 'fromdate'1962+ input: '"2015-03-05T23:51:47Z"'1963+ output: ['1425599507']1964+1965+ - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")'1966+ input: '"2015-03-05T23:51:47Z"'1967+ output: ['[2015,2,5,23,51,47,4,63]']1968+1969+ - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'1970+ input: '"2015-03-05T23:51:47Z"'1971+ output: ['1425599507']1972+1973+ - title: "SQL-Style Operators"1974+ body: |1975+1976+ jq provides a few SQL-style operators.1977+1978+ * INDEX(stream; index_expression):1979+1980+ This builtin produces an object whose keys are computed by1981+ the given index expression applied to each value from the1982+ given stream.1983+1984+ * JOIN($idx; stream; idx_expr; join_expr):1985+1986+ This builtin joins the values from the given stream to the1987+ given index. The index's keys are computed by applying the1988+ given index expression to each value from the given stream.1989+ An array of the value in the stream and the corresponding1990+ value from the index is fed to the given join expression to1991+ produce each result.1992+1993+ * JOIN($idx; stream; idx_expr):1994+1995+ Same as `JOIN($idx; stream; idx_expr; .)`.1996+1997+ * JOIN($idx; idx_expr):1998+1999+ This builtin joins the input `.` to the given index, applying2000+ the given index expression to `.` to compute the index key.2001+ The join operation is as described above.2002+2003+ * IN(s):2004+2005+ This builtin outputs `true` if `.` appears in the given2006+ stream, otherwise it outputs `false`.2007+2008+ * IN(source; s):2009+2010+ This builtin outputs `true` if any value in the source stream2011+ appears in the second stream, otherwise it outputs `false`.2012+2013+ - title: "`builtins`"2014+ body: |2015+2016+ Returns a list of all builtin functions in the format `name/arity`.2017+ Since functions with the same name but different arities are considered2018+ separate functions, `all/0`, `all/1`, and `all/2` would all be present2019+ in the list.2020+2021+ - title: Conditionals and Comparisons2022+ entries:2023+ - title: "`==`, `!=`"2024+ body: |2025+2026+ The expression 'a == b' will produce 'true' if the result of a and b2027+ are equal (that is, if they represent equivalent JSON documents) and2028+ 'false' otherwise. In particular, strings are never considered equal2029+ to numbers. If you're coming from Javascript, jq's == is like2030+ Javascript's === - considering values equal only when they have the2031+ same type as well as the same value.2032+2033+ != is "not equal", and 'a != b' returns the opposite value of 'a == b'2034+2035+ examples:2036+ - program: '.[] == 1'2037+ input: '[1, 1.0, "1", "banana"]'2038+ output: ['true', 'true', 'false', 'false']2039+2040+ - title: if-then-else2041+ body: |2042+2043+ `if A then B else C end` will act the same as `B` if `A`2044+ produces a value other than false or null, but act the same2045+ as `C` otherwise.2046+2047+ `if A then B end` is the same as `if A then B else . end`.2048+ That is, the `else` branch is optional, and if absent is the2049+ same as `.`.2050+2051+ Checking for false or null is a simpler notion of2052+ "truthiness" than is found in Javascript or Python, but it2053+ means that you'll sometimes have to be more explicit about2054+ the condition you want. You can't test whether, e.g. a2055+ string is empty using `if .name then A else B end`, you'll2056+ need something more like `if .name then A else B end` instead.2057+2058+ If the condition `A` produces multiple results, then `B` is evaluated2059+ once for each result that is not false or null, and `C` is evaluated2060+ once for each false or null.2061+2062+ More cases can be added to an if using `elif A then B` syntax.2063+2064+ examples:2065+ - program: 'if . == 0 then2066+ "zero"2067+ elif . == 1 then2068+ "one"2069+ else2070+ "many"2071+ end'2072+ input: 22073+ output: ['"many"']2074+2075+ - title: "`>, >=, <=, <`"2076+ body: |2077+2078+ The comparison operators `>`, `>=`, `<=`, `<` return whether2079+ their left argument is greater than, greater than or equal2080+ to, less than or equal to or less than their right argument2081+ (respectively).2082+2083+ The ordering is the same as that described for `sort`, above.2084+2085+ examples:2086+ - program: '. < 5'2087+ input: 22088+ output: ['true']2089+2090+ - title: and/or/not2091+ body: |2092+2093+ jq supports the normal Boolean operators and/or/not. They have the2094+ same standard of truth as if expressions - false and null are2095+ considered "false values", and anything else is a "true value".2096+2097+ If an operand of one of these operators produces multiple2098+ results, the operator itself will produce a result for each input.2099+2100+ `not` is in fact a builtin function rather than an operator,2101+ so it is called as a filter to which things can be piped2102+ rather than with special syntax, as in `.foo and .bar |2103+ not`.2104+2105+ These three only produce the values "true" and "false", and2106+ so are only useful for genuine Boolean operations, rather2107+ than the common Perl/Python/Ruby idiom of2108+ "value_that_may_be_null or default". If you want to use this2109+ form of "or", picking between two values rather than2110+ evaluating a condition, see the "//" operator below.2111+2112+ examples:2113+ - program: '42 and "a string"'2114+ input: 'null'2115+ output: ['true']2116+ - program: '(true, false) or false'2117+ input: 'null'2118+ output: ['true', 'false']2119+# - program: '(true, false) and (true, false)'2120+# input: 'null'2121+# output: ['true', 'false', 'false', 'false']2122+ - program: '(true, true) and (true, false)'2123+ input: 'null'2124+ output: ['true', 'false', 'true', 'false']2125+ - program: '[true, false | not]'2126+ input: 'null'2127+ output: ['[false, true]']2128+2129+ - title: "Alternative operator: `//`"2130+ body: |2131+2132+ A filter of the form `a // b` produces the same2133+ results as `a`, if `a` produces results other than `false`2134+ and `null`. Otherwise, `a // b` produces the same results as `b`.2135+2136+ This is useful for providing defaults: `.foo // 1` will2137+ evaluate to `1` if there's no `.foo` element in the2138+ input. It's similar to how `or` is sometimes used in Python2139+ (jq's `or` operator is reserved for strictly Boolean2140+ operations).2141+2142+ examples:2143+ - program: '.foo // 42'2144+ input: '{"foo": 19}'2145+ output: [19]2146+ - program: '.foo // 42'2147+ input: '{}'2148+ output: [42]2149+2150+ - title: try-catch2151+ body: |2152+2153+ Errors can be caught by using `try EXP catch EXP`. The first2154+ expression is executed, and if it fails then the second is2155+ executed with the error message. The output of the handler,2156+ if any, is output as if it had been the output of the2157+ expression to try.2158+2159+ The `try EXP` form uses `empty` as the exception handler.2160+2161+ examples:2162+ - program: 'try .a catch ". is not an object"'2163+ input: 'true'2164+ output: ['". is not an object"']2165+ - program: '[.[]|try .a]'2166+ input: '[{}, true, {"a":1}]'2167+ output: ['[null, 1]']2168+ - program: 'try error("some exception") catch .'2169+ input: 'true'2170+ output: ['"some exception"']2171+2172+ - title: Breaking out of control structures2173+ body: |2174+2175+ A convenient use of try/catch is to break out of control2176+ structures like `reduce`, `foreach`, `while`, and so on.2177+2178+ For example:2179+2180+ # Repeat an expression until it raises "break" as an2181+ # error, then stop repeating without re-raising the error.2182+ # But if the error caught is not "break" then re-raise it.2183+ try repeat(exp) catch .=="break" then empty else error;2184+2185+ jq has a syntax for named lexical labels to "break" or "go (back) to":2186+2187+ label $out | ... break $out ...2188+2189+ The `break $label_name` expression will cause the program to2190+ to act as though the nearest (to the left) `label $label_name`2191+ produced `empty`.2192+2193+ The relationship between the `break` and corresponding `label`2194+ is lexical: the label has to be "visible" from the break.2195+2196+ To break out of a `reduce`, for example:2197+2198+ label $out | reduce .[] as $item (null; if .==false then break $out else ... end)2199+2200+ The following jq program produces a syntax error:2201+2202+ break $out2203+2204+ because no label `$out` is visible.2205+2206+ - title: "Error Suppression / Optional Operator: `?`"2207+ body: |2208+2209+ The `?` operator, used as `EXP?`, is shorthand for `try EXP`.2210+2211+ examples:2212+ - program: '[.[]|(.a)?]'2213+ input: '[{}, true, {"a":1}]'2214+ output: ['[null, 1]']2215+2216+2217+ - title: Regular expressions (PCRE)2218+ body: |2219+2220+ jq uses the Oniguruma regular expression library, as do php,2221+ ruby, TextMate, Sublime Text, etc, so the description here2222+ will focus on jq specifics.2223+2224+ The jq regex filters are defined so that they can be used using2225+ one of these patterns:2226+2227+ STRING | FILTER( REGEX )2228+ STRING | FILTER( REGEX; FLAGS )2229+ STRING | FILTER( [REGEX] )2230+ STRING | FILTER( [REGEX, FLAGS] )2231+2232+ where:2233+2234+ * STRING, REGEX and FLAGS are jq strings and subject to jq string interpolation;2235+ * REGEX, after string interpolation, should be a valid PCRE regex;2236+ * FILTER is one of `test`, `match`, or `capture`, as described below.2237+2238+ FLAGS is a string consisting of one of more of the supported flags:2239+2240+ * `g` - Global search (find all matches, not just the first)2241+ * `i` - Case insensitive search2242+ * `m` - Multi line mode ('.' will match newlines)2243+ * `n` - Ignore empty matches2244+ * `p` - Both s and m modes are enabled2245+ * `s` - Single line mode ('^' -> '\A', '$' -> '\Z')2246+ * `l` - Find longest possible matches2247+ * `x` - Extended regex format (ignore whitespace and comments)2248+2249+ To match whitespace in an x pattern use an escape such as \s, e.g.2250+2251+ * test( "a\\sb", "x" ).2252+2253+ Note that certain flags may also be specified within REGEX, e.g.2254+2255+ * jq -n '("test", "TEst", "teST", "TEST") | test( "(?i)te(?-i)st" )'2256+2257+ evaluates to: true, true, false, false.2258+2259+ entries:2260+ - title: "`test(val)`, `test(regex; flags)`"2261+ body: |2262+2263+ Like `match`, but does not return match objects, only `true` or `false`2264+ for whether or not the regex matches the input.2265+2266+ examples:2267+ - program: 'test("foo")'2268+ input: '"foo"'2269+ output: ['true']2270+ - program: '.[] | test("a b c # spaces are ignored"; "ix")'2271+ input: '["xabcd", "ABC"]'2272+ output: ['true', 'true']2273+2274+ - title: "`match(val)`, `match(regex; flags)`"2275+ body: |2276+2277+ **match** outputs an object for each match it finds. Matches have2278+ the following fields:2279+2280+ * `offset` - offset in UTF-8 codepoints from the beginning of the input2281+ * `length` - length in UTF-8 codepoints of the match2282+ * `string` - the string that it matched2283+ * `captures` - an array of objects representing capturing groups.2284+2285+ Capturing group objects have the following fields:2286+2287+ * `offset` - offset in UTF-8 codepoints from the beginning of the input2288+ * `length` - length in UTF-8 codepoints of this capturing group2289+ * `string` - the string that was captured2290+ * `name` - the name of the capturing group (or `null` if it was unnamed)2291+2292+ Capturing groups that did not match anything return an offset of -12293+2294+ examples:2295+ - program: 'match("(abc)+"; "g")'2296+ input: '"abc abc"'2297+ output:2298+ - '{"offset": 0, "length": 3, "string": "abc", "captures": [{"offset": 0, "length": 3, "string": "abc", "name": null}]}'2299+ - '{"offset": 4, "length": 3, "string": "abc", "captures": [{"offset": 4, "length": 3, "string": "abc", "name": null}]}'2300+ - program: 'match("foo")'2301+ input: '"foo bar foo"'2302+ output: ['{"offset": 0, "length": 3, "string": "foo", "captures": []}']2303+ - program: 'match(["foo", "ig"])'2304+ input: '"foo bar FOO"'2305+ output:2306+ - '{"offset": 0, "length": 3, "string": "foo", "captures": []}'2307+ - '{"offset": 8, "length": 3, "string": "FOO", "captures": []}'2308+ - program: 'match("foo (?<bar123>bar)? foo"; "ig")'2309+ input: '"foo bar foo foo foo"'2310+ output:2311+ - '{"offset": 0, "length": 11, "string": "foo bar foo", "captures": [{"offset": 4, "length": 3, "string": "bar", "name": "bar123"}]}'2312+ - '{"offset": 12, "length": 8, "string": "foo foo", "captures": [{"offset": -1, "length": 0, "string": null, "name": "bar123"}]}'2313+2314+ - program: '[ match("."; "g")] | length'2315+ input: '"abc"'2316+ output: [3]2317+2318+2319+ - title: "`capture(val)`, `capture(regex; flags)`"2320+ body: |2321+2322+ Collects the named captures in a JSON object, with the name2323+ of each capture as the key, and the matched string as the2324+ corresponding value.2325+2326+ examples:2327+ - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2328+ input: '"xyzzy-14"'2329+ output: ['{ "a": "xyzzy", "n": "14" }']2330+2331+ - title: "`scan(regex)`, `scan(regex; flags)`"2332+ body: |2333+2334+ Emit a stream of the non-overlapping substrings of the input2335+ that match the regex in accordance with the flags, if any2336+ have been specified. If there is no match, the stream is empty.2337+ To capture all the matches for each input string, use the idiom2338+ `[ expr ]`, e.g. `[ scan(regex) ]`.2339+2340+ example:2341+ - program: 'scan("c")'2342+ input: '"abcdefabc"'2343+ output: ['"c"', '"c"']2344+2345+ - program: 'scan("b")'2346+ input: ("", "")2347+ output: ['[]', '[]']2348+2349+ - title: "`split(regex; flags)`"2350+ body: |2351+2352+ For backwards compatibility, `split` splits on a string, not a regex.2353+2354+ example:2355+ - program: 'split(", *"; null)'2356+ input: '"ab,cd, ef"'2357+ output: ['"ab","cd","ef"']2358+2359+2360+ - title: "`splits(regex)`, `splits(regex; flags)`"2361+ body: |2362+2363+ These provide the same results as their `split` counterparts,2364+ but as a stream instead of an array.2365+2366+ example:2367+ - program: 'splits(", *")'2368+ input: '("ab,cd", "ef, gh")'2369+ output: ['"ab"', '"cd"', '"ef"', '"gh"']2370+2371+ - title: "`sub(regex; tostring)` `sub(regex; string; flags)`"2372+ body: |2373+2374+ Emit the string obtained by replacing the first match of regex in the2375+ input string with `tostring`, after interpolation. `tostring` should2376+ be a jq string, and may contain references to named captures. The2377+ named captures are, in effect, presented as a JSON object (as2378+ constructed by `capture`) to `tostring`, so a reference to a captured2379+ variable named "x" would take the form: "\(.x)".2380+2381+ example:2382+ - program: 'sub("^[^a-z]*(?<x>[a-z]*).*")'2383+ input: '"123abc456"'2384+ output: '"ZabcZabc"'2385+2386+2387+ - title: "`gsub(regex; string)`, `gsub(regex; string; flags)`"2388+ body: |2389+2390+ `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2391+ replaced by the string, after interpolation.2392+2393+ example:2394+ - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2395+ input: '"Abcabc"'2396+ output: '"+A-+a-"'2397+2398+2399+ - title: Advanced features2400+ body: |2401+ Variables are an absolute necessity in most programming languages, but2402+ they're relegated to an "advanced feature" in jq.2403+2404+ In most languages, variables are the only means of passing around2405+ data. If you calculate a value, and you want to use it more than once,2406+ you'll need to store it in a variable. To pass a value to another part2407+ of the program, you'll need that part of the program to define a2408+ variable (as a function parameter, object member, or whatever) in2409+ which to place the data.2410+2411+ It is also possible to define functions in jq, although this is2412+ is a feature whose biggest use is defining jq's standard library2413+ (many jq functions such as `map` and `find` are in fact written2414+ in jq).2415+2416+ jq has reduction operators, which are very powerful but a bit2417+ tricky. Again, these are mostly used internally, to define some2418+ useful bits of jq's standard library.2419+2420+ It may not be obvious at first, but jq is all about generators2421+ (yes, as often found in other languages). Some utilities are2422+ provided to help deal with generators.2423+2424+ Some minimal I/O support (besides reading JSON from standard2425+ input, and writing JSON to standard output) is available.2426+2427+ Finally, there is a module/library system.2428+2429+ entries:2430+ - title: "Variable / Symbolic Binding Operator: `... as $identifier | ...`"2431+ body: |2432+2433+ In jq, all filters have an input and an output, so manual2434+ plumbing is not necessary to pass a value from one part of a program2435+ to the next. Many expressions, for instance `a + b`, pass their input2436+ to two distinct subexpressions (here `a` and `b` are both passed the2437+ same input), so variables aren't usually necessary in order to use a2438+ value twice.2439+2440+ For instance, calculating the average value of an array of numbers2441+ requires a few variables in most languages - at least one to hold the2442+ array, perhaps one for each element or for a loop counter. In jq, it's2443+ simply `add / length` - the `add` expression is given the array and2444+ produces its sum, and the `length` expression is given the array and2445+ produces its length.2446+2447+ So, there's generally a cleaner way to solve most problems in jq than2448+ defining variables. Still, sometimes they do make things easier, so jq2449+ lets you define variables using `expression as $variable`. All2450+ variable names start with `$`. Here's a slightly uglier version of the2451+ array-averaging example:2452+2453+ length as $array_length | add / $array_length2454+2455+ We'll need a more complicated problem to find a situation where using2456+ variables actually makes our lives easier.2457+2458+2459+ Suppose we have an array of blog posts, with "author" and "title"2460+ fields, and another object which is used to map author usernames to2461+ real names. Our input looks like:2462+2463+ {"posts": [{"title": "Frist psot", "author": "anon"},2464+ {"title": "A well-written article", "author": "person1"}],2465+ "realnames": {"anon": "Anonymous Coward",2466+ "person1": "Person McPherson"}}2467+2468+ We want to produce the posts with the author field containing a real2469+ name, as in:2470+2471+ {"title": "Frist psot", "author": "Anonymous Coward"}2472+ {"title": "A well-written article", "author": "Person McPherson"}2473+2474+ We use a variable, $names, to store the realnames object, so that we2475+ can refer to it later when looking up author usernames:2476+2477+ .realnames as $names | .posts[] | {title, author: $names[.author]}2478+2479+ The expression `exp as $x | ...` means: for each value of expression2480+ `exp`, run the rest of the pipeline with the entire original input, and2481+ with `$x` set to that value. Thus `as` functions as something of a2482+ foreach loop.2483+2484+ Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2485+ `{$foo}` is a handy way of writing `{foo:$foo}`.2486+2487+ Multiple variables may be declared using a single `as` expression by2488+ providing a pattern that matches the structure of the input2489+ (this is known as "destructuring"):2490+2491+ . as {realnames: $names, posts: [$first, $second]} | ...2492+2493+ The variable declarations in array patterns (e.g., `. as2494+ [$first, $second]`) bind to the elements of the array in from2495+ the element at index zero on up, in order. When there is no2496+ value at the index for an array pattern element, `null` is2497+ bound to that variable.2498+2499+ Variables are scoped over the rest of the expression that defines2500+ them, so2501+2502+ .realnames as $names | (.posts[] | {title, author: $names[.author]})2503+2504+ will work, but2505+2506+ (.realnames as $names | .posts[]) | {title, author: $names[.author]}2507+2508+ won't.2509+2510+ For programming language theorists, it's more accurate to2511+ say that jq variables are lexically-scoped bindings. In2512+ particular there's no way to change the value of a binding;2513+ one can only setup a new binding with the same name, but which2514+ will not be visible where the old one was.2515+2516+ examples:2517+ - program: '.bar as $x | .foo | . + $x'2518+ input: '{"foo":10, "bar":200}'2519+ output: ['210']2520+ - program: '. as $i|[(.*2|. as $i| $i), $i]'2521+ input: '5'2522+ output: ['[10,5]']2523+ - program: '. as [$a, $b, {c: $c}] | $a + $b + $c'2524+ input: '[2, 3, {"c": 4, "d": 5}]'2525+ output: ['9']2526+ - program: '.[] as [$a, $b] | {a: $a, b: $b}'2527+ input: '[[0], [0, 1], [2, 1, 0]]'2528+ output: ['{"a":0,"b":null}', '{"a":0,"b":1}', '{"a":2,"b":1}']2529+2530+ - title: 'Destructuring Alternative Operator: `?//`'2531+ body: |2532+ 2533+ The destructuring alternative operator provides a concise mechanism2534+ for destructuring an input that can take one of several forms.2535+2536+ Suppose we have an API that returns a list of resources and events2537+ associated with them, and we want to get the user_id and timestamp of2538+ the first event for each resource. The API (having been clumsily2539+ converted from XML) will only wrap the events in an array if the resource2540+ has multiple events:2541+ 2542+ {"resources": [{"id": 1, "kind": "widget", "events": {"action": "create", "user_id": 1, "ts": 13}},2543+ {"id": 2, "kind": "widget", "events": [{"action": "create", "user_id": 1, "ts": 14}, {"action": "destroy", "user_id": 1, "ts": 15}]}]}2544+ 2545+ We can use the destructuring alternative operator to handle this structural change simply:2546+2547+ .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$user_id, $ts}]} | {$user_id, $kind, $id, $ts}2548+2549+ Or, if we aren't sure if the input is an array of values or an object:2550+2551+ .[] as [$id, $kind, $user_id, $ts] ?// {$id, $kind, $user_id, $ts} | ...2552+2553+ Each alternative need not define all of the same variables, but all named2554+ variables will be available to the subsequent expression. Variables not2555+ matched in the alternative that succeeded will be `null`:2556+2557+ .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$first_user_id, $first_ts}]} | {$user_id, $first_user_id, $kind, $id, $ts, $first_ts}2558+2559+ Additionally, if the subsequent expression returns an error, the2560+ alternative operator will attempt to try the next binding. Errors2561+ that occur during the final alternative are passed through.2562+2563+ [[3]] | .[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end2564+2565+ examples:2566+ - program: '.[] as {$a, $b, c: {$d, $e}} ?// {$a, $b, c: [{$d, $e}]} | {$a, $b, $d, $e}'2567+ input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2568+ output: ['{"a":1,"b":2,"d":3,"e":4}', '{"a":1,"b":2,"d":3,"e":4}']2569+ - program: '.[] as {$a, $b, c: {$d}} ?// {$a, $b, c: [{$e}]} | {$a, $b, $d, $e}'2570+ input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2571+ output: ['{"a":1,"b":2,"d":3,"e":null}', '{"a":1,"b":2,"d":null,"e":4}']2572+ - program: '.[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end'2573+ input: '[[3]]'2574+ output: ['{"a":null,"b":3}']2575+2576+ - title: 'Defining Functions'2577+ body: |2578+2579+ You can give a filter a name using "def" syntax:2580+2581+ def increment: . + 1;2582+2583+ From then on, `increment` is usable as a filter just like a2584+ builtin function (in fact, this is how many of the builtins2585+ are defined). A function may take arguments:2586+2587+ def map(f): [.[] | f];2588+2589+ Arguments are passed as _filters_ (functions with no2590+ arguments), _not_ as values. The same argument may be2591+ referenced multiple times with different inputs (here `f` is2592+ run for each element of the input array). Arguments to a2593+ function work more like callbacks than like value arguments.2594+ This is important to understand. Consider:2595+2596+ def foo(f): f|f;2597+ 5|foo(.*2)2598+2599+ The result will be 20 because `f` is `.*2`, and during the2600+ first invocation of `f` `.` will be 5, and the second time it2601+ will be 10 (5 * 2), so the result will be 20. Function2602+ arguments are filters, and filters expect an input when2603+ invoked.2604+2605+ If you want the value-argument behaviour for defining simple2606+ functions, you can just use a variable:2607+2608+ def addvalue(f): f as $f | map(. + $f);2609+2610+ Or use the short-hand:2611+2612+ def addvalue($f): ...;2613+2614+ With either definition, `addvalue(.foo)` will add the current2615+ input's `.foo` field to each element of the array. Do note2616+ that calling `addvalue(.[])` will cause the `map(. + $f)` part2617+ to be evaluated once per value in the value of `.` at the call2618+ site.2619+2620+ Multiple definitions using the same function name are allowed.2621+ Each re-definition replaces the previous one for the same2622+ number of function arguments, but only for references from2623+ functions (or main program) subsequent to the re-definition.2624+ See also the section below on scoping.2625+2626+ examples:2627+ - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'2628+ input: '[[1,2],[10,20]]'2629+ output: ['[[1,2,1], [10,20,10]]']2630+ - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'2631+ input: '[[1,2],[10,20]]'2632+ output: ['[[1,2,1,2], [10,20,1,2]]']2633+2634+ - title: 'Scoping'2635+ body: |2636+2637+ There are two types of symbols in jq: value bindings (a.k.a.,2638+ "variables"), and functions. Both are scoped lexically,2639+ with expressions being able to refer only to symbols that2640+ have been defined "to the left" of them. The only exception2641+ to this rule is that functions can refer to themselves so as2642+ to be able to create recursive functions.2643+2644+ For example, in the following expression there is a binding2645+ which is visible "to the right" of it, `... | .*3 as2646+ $times_three | [. + $times_three] | ...`, but not "to the2647+ left". Consider this expression now, `... | (.*3 as2648+ $times_three | [.+ $times_three]) | ...`: here the binding2649+ `$times_three` is _not_ visible past the closing parenthesis.2650+2651+ - title: Reduce2652+ body: |2653+2654+ The `reduce` syntax in jq allows you to combine all of the2655+ results of an expression by accumulating them into a single2656+ answer. As an example, we'll pass `[3,2,1]` to this expression:2657+2658+ reduce .[] as $item (0; . + $item)2659+2660+ For each result that `.[]` produces, `. + $item` is run to2661+ accumulate a running total, starting from 0. In this2662+ example, `.[]` produces the results 3, 2, and 1, so the2663+ effect is similar to running something like this:2664+2665+ 0 | (3 as $item | . + $item) |2666+ (2 as $item | . + $item) |2667+ (1 as $item | . + $item)2668+2669+ examples:2670+ - program: 'reduce .[] as $item (0; . + $item)'2671+ input: '[10,2,5,3]'2672+ output: ['20']2673+2674+ - title: "`isempty(exp)`"2675+ body: |2676+2677+ Returns true if `exp` produces no outputs, false otherwise.2678+2679+ examples:2680+ - program: 'isempty(empty)'2681+ input: 'null'2682+ output: ['true']2683+2684+ - title: "`limit(n; exp)`"2685+ body: |2686+2687+ The `limit` function extracts up to `n` outputs from `exp`.2688+2689+ examples:2690+ - program: '[limit(3;.[])]'2691+ input: '[0,1,2,3,4,5,6,7,8,9]'2692+ output: ['[0,1,2]']2693+2694+ - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"2695+ body: |2696+2697+ The `first(expr)` and `last(expr)` functions extract the first2698+ and last values from `expr`, respectively.2699+2700+ The `nth(n; expr)` function extracts the nth value output by2701+ `expr`. This can be defined as `def nth(n; expr):2702+ last(limit(n + 1; expr));`. Note that `nth(n; expr)` doesn't2703+ support negative values of `n`.2704+2705+ examples:2706+ - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'2707+ input: '10'2708+ output: ['[0,9,5]']2709+2710+ - title: "`first`, `last`, `nth(n)`"2711+ body: |2712+2713+ The `first` and `last` functions extract the first2714+ and last values from any array at `.`.2715+2716+ The `nth(n)` function extracts the nth value of any array at `.`.2717+2718+ examples:2719+ - program: '[range(.)]|[first, last, nth(5)]'2720+ input: '10'2721+ output: ['[0,9,5]']2722+2723+ - title: "`foreach`"2724+ body: |2725+2726+ The `foreach` syntax is similar to `reduce`, but intended to2727+ allow the construction of `limit` and reducers that produce2728+ intermediate results (see example).2729+2730+ The form is `foreach EXP as $var (INIT; UPDATE; EXTRACT)`.2731+ Like `reduce`, `INIT` is evaluated once to produce a state2732+ value, then each output of `EXP` is bound to `$var`, `UPDATE`2733+ is evaluated for each output of `EXP` with the current state2734+ and with `$var` visible. Each value output by `UPDATE`2735+ replaces the previous state. Finally, `EXTRACT` is evaluated2736+ for each new state to extract an output of `foreach`.2737+2738+ This is mostly useful only for constructing `reduce`- and2739+ `limit`-like functions. But it is much more general, as it2740+ allows for partial reductions (see the example below).2741+2742+ examples:2743+ - program: '[foreach .[] as $item2744+ ([[],[]];2745+ if $item == null then [[],.[0]] else [(.[0] + [$item]),[]] end;2746+ if $item == null then .[1] else empty end)]'2747+ input: '[1,2,3,4,null,"a","b",null]'2748+ output: ['[[1,2,3,4],["a","b"]]']2749+2750+ - title: Recursion2751+ body: |2752+2753+ As described above, `recurse` uses recursion, and any jq2754+ function can be recursive. The `while` builtin is also2755+ implemented in terms of recursion.2756+2757+ Tail calls are optimized whenever the expression to the left of2758+ the recursive call outputs its last value. In practice this2759+ means that the expression to the left of the recursive call2760+ should not produce more than one output for each input.2761+2762+ For example:2763+2764+ def recurse(f): def r: ., (f | select(. != null) | r); r;2765+2766+ def while(cond; update):2767+ def _while:2768+ if cond then ., (update | _while) else empty end;2769+ _while;2770+2771+ def repeat(exp):2772+ def _repeat:2773+ exp, _repeat;2774+ _repeat;2775+2776+ - title: Generators and iterators2777+ body: |2778+2779+ Some jq operators and functions are actually generators in2780+ that they can produce zero, one, or more values for each2781+ input, just as one might expect in other programming2782+ languages that have generators. For example, `.[]`2783+ generates all the values in its input (which must be an2784+ array or an object), `range(0; 10)` generates the integers2785+ between 0 and 10, and so on.2786+2787+ Even the comma operator is a generator, generating first the2788+ values generated by the expression to the left of the comma,2789+ then for each of those, the values generate by the2790+ expression on the right of the comma.2791+2792+ The `empty` builtin is the generator that produces zero2793+ outputs. The `empty` builtin backtracks to the preceding2794+ generator expression.2795+2796+ All jq functions can be generators just by using builtin2797+ generators. It is also possible to define new generators2798+ using only recursion and the comma operator. If the2799+ recursive call(s) is(are) "in tail position" then the2800+ generator will be efficient. In the example below the2801+ recursive call by `_range` to itself is in tail position.2802+ The example shows off three advanced topics: tail recursion,2803+ generator construction, and sub-functions.2804+2805+ examples:2806+ - program: 'def range(init; upto; by):2807+ def _range:2808+ if (by > 0 and . < upto) or (by < 0 and . > upto)2809+ then ., ((.+by)|_range)2810+ else . end;2811+ if by == 0 then init else init|_range end |2812+ select((by > 0 and . < upto) or (by < 0 and . > upto));2813+ range(0; 10; 3)'2814+ input: 'null'2815+ output: ['0', '3', '6', '9']2816+ - program: 'def while(cond; update):2817+ def _while:2818+ if cond then ., (update | _while) else empty end;2819+ _while;2820+ [while(.<100; .*2)]'2821+ input: '1'2822+ output: ['[1,2,4,8,16,32,64]']2823+2824+ - title: 'Math'2825+ body: |2826+2827+ jq currently only has IEEE754 double-precision (64-bit) floating2828+ point number support.2829+2830+ Besides simple arithmetic operators such as `+`, jq also has most2831+ standard math functions from the C math library. C math functions2832+ that take a single input argument (e.g., `sin()`) are available as2833+ zero-argument jq functions. C math functions that take two input2834+ arguments (e.g., `pow()`) are available as two-argument jq2835+ functions that ignore `.`. C math functions that take three input2836+ arguments are available as three-argument jq functions that ignore2837+ `.`.2838+2839+ Availability of standard math functions depends on the2840+ availability of the corresponding math functions in your operating2841+ system and C math library. Unavailable math functions will be2842+ defined but will raise an error.2843+2844+ One-input C math functions: `acos` `acosh` `asin` `asinh` `atan`2845+ `atanh` `cbrt` `ceil` `cos` `cosh` `erf` `erfc` `exp` `exp10`2846+ `exp2` `expm1` `fabs` `floor` `gamma` `j0` `j1` `lgamma` `log`2847+ `log10` `log1p` `log2` `logb` `nearbyint` `pow10` `rint` `round`2848+ `significand` `sin` `sinh` `sqrt` `tan` `tanh` `tgamma` `trunc`2849+ `y0` `y1`.2850+2851+ Two-input C math functions: `atan2` `copysign` `drem` `fdim`2852+ `fmax` `fmin` `fmod` `frexp` `hypot` `jn` `ldexp` `modf`2853+ `nextafter` `nexttoward` `pow` `remainder` `scalb` `scalbln` `yn`.2854+2855+ Three-input C math functions: `fma`.2856+2857+ See your system's manual for more information on each of these.2858+2859+ - title: 'I/O'2860+ body: |2861+2862+ At this time jq has minimal support for I/O, mostly in the2863+ form of control over when inputs are read. Two builtins functions2864+ are provided for this, `input` and `inputs`, that read from the2865+ same sources (e.g., `stdin`, files named on the command-line) as2866+ jq itself. These two builtins, and jq's own reading actions, can2867+ be interleaved with each other.2868+2869+ Two builtins provide minimal output capabilities, `debug`, and2870+ `stderr`. (Recall that a jq program's output values are always2871+ output as JSON texts on `stdout`.) The `debug` builtin can have2872+ application-specific behavior, such as for executables that use2873+ the libjq C API but aren't the jq executable itself. The `stderr`2874+ builtin outputs its input in raw mode to stder with no additional2875+ decoration, not even a newline.2876+2877+ Most jq builtins are referentially transparent, and yield constant2878+ and repeatable value streams when applied to constant inputs.2879+ This is not true of I/O builtins.2880+2881+ entries:2882+ - title: "`input`"2883+ body: |2884+2885+ Outputs one new input.2886+2887+ - title: "`inputs`"2888+ body: |2889+2890+ Outputs all remaining inputs, one by one.2891+2892+ This is primarily useful for reductions over a program's2893+ inputs.2894+2895+ - title: "`debug`"2896+ body: |2897+2898+ Causes a debug message based on the input value to be2899+ produced. The jq executable wraps the input value with2900+ `["DEBUG:", <input-value>]` and prints that and a newline on2901+ stderr, compactly. This may change in the future.2902+2903+ - title: "`stderr`"2904+ body: |2905+2906+ Prints its input in raw and compact mode to stderr with no2907+ additional decoration, not even a newline.2908+2909+ - title: "`input_filename`"2910+ body: |2911+2912+ Returns the name of the file whose input is currently being2913+ filtered. Note that this will not work well unless jq is2914+ running in a UTF-8 locale.2915+2916+ - title: "`input_line_number`"2917+ body: |2918+2919+ Returns the line number of the input currently being filtered.2920+2921+ - title: 'Streaming'2922+ body: |2923+2924+ With the `--stream` option jq can parse input texts in a streaming2925+ fashion, allowing jq programs to start processing large JSON texts2926+ immediately rather than after the parse completes. If you have a2927+ single JSON text that is 1GB in size, streaming it will allow you2928+ to process it much more quickly.2929+2930+ However, streaming isn't easy to deal with as the jq program will2931+ have `[<path>, <leaf-value>]` (and a few other forms) as inputs.2932+2933+ Several builtins are provided to make handling streams easier.2934+2935+ The examples below use the streamed form of `[0,[1]]`, which is2936+ `[[0],0],[[1,0],1],[[1,0]],[[1]]`.2937+2938+ Streaming forms include `[<path>, <leaf-value>]` (to indicate any2939+ scalar value, empty array, or empty object), and `[<path>]` (to2940+ indicate the end of an array or object). Future versions of jq2941+ run with `--stream` and `-seq` may output additional forms such as2942+ `["error message"]` when an input text fails to parse.2943+2944+ entries:2945+ - title: "`truncate_stream(stream_expression)`"2946+ body: |2947+2948+ Consumes a number as input and truncates the corresponding2949+ number of path elements from the left of the outputs of the2950+ given streaming expression.2951+2952+ examples:2953+ - program: '[1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]'2954+ input: '1'2955+ output: ['[[[0],2],[[0]]]']2956+2957+ - title: "`fromstream(stream_expression)`"2958+ body: |2959+2960+ Outputs values corresponding to the stream expression's2961+ outputs.2962+2963+ examples:2964+ - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'2965+ input: 'null'2966+ output: ['[2]']2967+2968+ - title: "`tostream`"2969+ body: |2970+2971+ The `tostream` builtin outputs the streamed form of its input.2972+2973+ examples:2974+ - program: '. as $dot|fromstream($dot|tostream)|.==$dot'2975+ input: '[0,[1,{"a":1},{"b":2}]]'2976+ output: ['true']2977+2978+ - title: Assignment2979+ body: |2980+ Assignment works a little differently in jq than in most2981+ programming languages. jq doesn't distinguish between references2982+ to and copies of something - two objects or arrays are either2983+ equal or not equal, without any further notion of being "the2984+ same object" or "not the same object".2985+2986+ If an object has two fields which are arrays, `.foo` and `.bar`,2987+ and you append something to `.foo`, then `.bar` will not get2988+ bigger, even if you've previously set `.bar = .foo`. If you're2989+ used to programming in languages like Python, Java, Ruby,2990+ Javascript, etc. then you can think of it as though jq does a full2991+ deep copy of every object before it does the assignment (for2992+ performance it doesn't actually do that, but that's the general2993+ idea).2994+2995+ This means that it's impossible to build circular values in jq2996+ (such as an array whose first element is itself). This is quite2997+ intentional, and ensures that anything a jq program can produce2998+ can be represented in JSON.2999+3000+ All the assignment operators in jq have path expressions on the3001+ left-hand side (LHS). The right-hand side (RHS) provides values3002+ to set to the paths named by the LHS path expressions.3003+3004+ Values in jq are always immutable. Internally, assignment works3005+ by using a reduction to compute new, replacement values for `.` that3006+ have had all the desired assignments applied to `.`, then3007+ outputting the modified value. This might be made clear by this3008+ example: `{a:{b:{c:1}}} | (.a.b|=3), .`. This will output3009+ `{"a":{"b":3}}` and `{"a":{"b":{"c":1}}}` because the last3010+ sub-expression, `.`, sees the original value, not the modified3011+ value.3012+3013+ Most users will want to use modification assignment operators,3014+ such as `|=` or `+=`, rather than `=`.3015+3016+ Note that the LHS of assignment operators refers to a value in3017+ `.`. Thus `$var.foo = 1` won't work as expected (`$var.foo` is3018+ not a valid or useful path expression in `.`); use `$var | .foo =3019+ 1` instead.3020+3021+ Note too that `.a,.b=0` does not set `.a` and `.b`, but3022+ `(.a,.b)=0` sets both.3023+3024+ entries:3025+ - title: "Update-assignment: `|=`"3026+ body: |3027+ This is the "update" operator '|='. It takes a filter on the3028+ right-hand side and works out the new value for the property3029+ of `.` being assigned to by running the old value through this3030+ expression. For instance, (.foo, .bar) |= .+1 will build an3031+ object with the "foo" field set to the input's "foo" plus 1,3032+ and the "bar" field set to the input's "bar" plus 1.3033+3034+ The left-hand side can be any general path expression; see `path()`.3035+3036+ Note that the left-hand side of '|=' refers to a value in `.`.3037+ Thus `$var.foo |= . + 1` won't work as expected (`$var.foo` is3038+ not a valid or useful path expression in `.`); use `$var |3039+ .foo |= . + 1` instead.3040+3041+ If the right-hand side outputs no values (i.e., `empty`), then3042+ the left-hand side path will be deleted, as with `del(path)`.3043+3044+ If the right-hand side outputs multiple values, only the first3045+ one will be used (COMPATIBILITY NOTE: in jq 1.5 and earlier3046+ releases, it used to be that only the last one was used).3047+3048+ examples:3049+ - program: '(..|select(type=="boolean")) |= if . then 1 else 0 end'3050+ input: '[true,false,[5,true,[true,[false]],false]]'3051+ output: ['[1,0,[5,1,[1,[0]],0]]']3052+3053+ - title: "Arithmetic update-assignment: `+=`, `-=`, `*=`, `/=`, `%=`, `//=`"3054+ body: |3055+3056+ jq has a few operators of the form `a op= b`, which are all3057+ equivalent to `a |= . op b`. So, `+= 1` can be used to3058+ increment values, being the same as `|= . + 1`.3059+3060+ examples:3061+ - program: .foo += 13062+ input: '{"foo": 42}'3063+ output: ['{"foo": 43}']3064+3065+ - title: "Plain assignment: `=`"3066+ body: |3067+3068+ This is the plain assignment operator. Unlike the others, the3069+ input to the right-hand-side (RHS) is the same as the input to3070+ the left-hand-side (LHS) rather than the value at the LHS3071+ path, and all values output by the RHS will be used (as shown3072+ below).3073+3074+ If the RHS of '=' produces multiple values, then for each such3075+ value jq will set the paths on the left-hand side to the value3076+ and then it will output the modified `.`. For example,3077+ `(.a,.b)=range(2)` outputs `{"a":0,"b":0}`, then3078+ `{"a":1,"b":1}`. The "update" assignment forms (see above) do3079+ not do this.3080+3081+ This example should show the difference between '=' and '|=':3082+3083+ Provide input '{"a": {"b": 10}, "b": 20}' to the programs:3084+3085+ .a = .b3086+3087+ .a |= .b3088+3089+ The former will set the "a" field of the input to the "b"3090+ field of the input, and produce the output {"a": 20, "b": 20}.3091+ The latter will set the "a" field of the input to the "a"3092+ field's "b" field, producing {"a": 10, "b": 20}.3093+3094+ Another example of the difference between '=' and '|=':3095+3096+ null|(.a,.b)=range(3)3097+3098+ outputs '{"a":0,"b":0}', '{"a":1,"b":1}', and '{"a":2,"b":2}',3099+ while3100+3101+ null|(.a,.b)|=range(3)3102+3103+ outputs just '{"a":0,"b":0}'.3104+3105+ - title: Complex assignments3106+ body: |3107+ Lots more things are allowed on the left-hand side of a jq assignment3108+ than in most languages. We've already seen simple field accesses on3109+ the left hand side, and it's no surprise that array accesses work just3110+ as well:3111+3112+ .posts[0].title = "JQ Manual"3113+3114+ What may come as a surprise is that the expression on the left may3115+ produce multiple results, referring to different points in the input3116+ document:3117+3118+ .posts[].comments |= . + ["this is great"]3119+3120+ That example appends the string "this is great" to the "comments"3121+ array of each post in the input (where the input is an object with a3122+ field "posts" which is an array of posts).3123+3124+ When jq encounters an assignment like 'a = b', it records the "path"3125+ taken to select a part of the input document while executing a. This3126+ path is then used to find which part of the input to change while3127+ executing the assignment. Any filter may be used on the3128+ left-hand side of an equals - whichever paths it selects from the3129+ input will be where the assignment is performed.3130+3131+ This is a very powerful operation. Suppose we wanted to add a comment3132+ to blog posts, using the same "blog" input above. This time, we only3133+ want to comment on the posts written by "stedolan". We can find those3134+ posts using the "select" function described earlier:3135+3136+ .posts[] | select(.author == "stedolan")3137+3138+ The paths provided by this operation point to each of the posts that3139+ "stedolan" wrote, and we can comment on each of them in the same way3140+ that we did before:3141+3142+ (.posts[] | select(.author == "stedolan") | .comments) |=3143+ . + ["terrible."]3144+3145+ - title: Modules3146+ body: |3147+3148+ jq has a library/module system. Modules are files whose names end3149+ in `.jq`.3150+3151+ Modules imported by a program are searched for in a default search3152+ path (see below). The `import` and `include` directives allow the3153+ importer to alter this path.3154+3155+ Paths in the a search path are subject to various substitutions.3156+3157+ For paths starting with "~/", the user's home directory is3158+ substituted for "~".3159+3160+ For paths starting with "$ORIGIN/", the path of the jq executable3161+ is substituted for "$ORIGIN".3162+3163+ For paths starting with "./" or paths that are ".", the path of3164+ the including file is substituted for ".". For top-level programs3165+ given on the command-line, the current directory is used.3166+3167+ Import directives can optionally specify a search path to which3168+ the default is appended.3169+3170+ The default search path is the search path given to the `-L`3171+ command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",3172+ "$ORIGIN/../lib"]`.3173+3174+ Null and empty string path elements terminate search path3175+ processing.3176+3177+ A dependency with relative path "foo/bar" would be searched for in3178+ "foo/bar.jq" and "foo/bar/bar.jq" in the given search path. This3179+ is intended to allow modules to be placed in a directory along3180+ with, for example, version control files, README files, and so on,3181+ but also to allow for single-file modules.3182+3183+ Consecutive components with the same name are not allowed to avoid3184+ ambiguities (e.g., "foo/foo").3185+3186+ For example, with `-L$HOME/.jq` a module `foo` can be found in3187+ `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.3188+3189+ If "$HOME/.jq" is a file, it is sourced into the main program.3190+3191+ entries:3192+ - title: "`import RelativePathString as NAME [<metadata>];`"3193+ body: |3194+3195+ Imports a module found at the given path relative to a3196+ directory in a search path. A ".jq" suffix will be added to3197+ the relative path string. The module's symbols are prefixed3198+ with "NAME::".3199+3200+ The optional metadata must be a constant jq expression. It3201+ should be an object with keys like "homepage" and so on. At3202+ this time jq only uses the "search" key/value of the metadata.3203+ The metadata is also made available to users via the3204+ `modulemeta` builtin.3205+3206+ The "search" key in the metadata, if present, should have a3207+ string or array value (array of strings); this is the search3208+ path to be prefixed to the top-level search path.3209+3210+ - title: "`include RelativePathString [<metadata>];`"3211+ body: |3212+3213+ Imports a module found at the given path relative to a3214+ directory in a search path as if it were included in place. A3215+ ".jq" suffix will be added to the relative path string. The3216+ module's symbols are imported into the caller's namespace as3217+ if the module's content had been included directly.3218+3219+ The optional metadata must be a constant jq expression. It3220+ should be an object with keys like "homepage" and so on. At3221+ this time jq only uses the "search" key/value of the metadata.3222+ The metadata is also made available to users via the3223+ `modulemeta` builtin.3224+3225+ - title: "`import RelativePathString as $NAME [<metadata>];`"3226+ body: |3227+3228+ Imports a JSON file found at the given path relative to a3229+ directory in a search path. A ".json" suffix will be added to3230+ the relative path string. The file's data will be available3231+ as `$NAME::NAME`.3232+3233+ The optional metadata must be a constant jq expression. It3234+ should be an object with keys like "homepage" and so on. At3235+ this time jq only uses the "search" key/value of the metadata.3236+ The metadata is also made available to users via the3237+ `modulemeta` builtin.3238+3239+ The "search" key in the metadata, if present, should have a3240+ string or array value (array of strings); this is the search3241+ path to be prefixed to the top-level search path.3242+3243+ - title: "`module <metadata>;`"3244+ body: |3245+3246+ This directive is entirely optional. It's not required for3247+ proper operation. It serves only the purpose of providing3248+ metadata that can be read with the `modulemeta` builtin.3249+3250+ The metadata must be a constant jq expression. It should be3251+ an object with keys like "homepage". At this time jq doesn't3252+ use this metadata, but it is made available to users via the3253+ `modulemeta` builtin.3254+3255+ - title: "`modulemeta`"3256+ body: |3257+3258+ Takes a module name as input and outputs the module's metadata3259+ as an object, with the module's imports (including metadata)3260+ as an array value for the "deps" key.3261+3262+ Programs can use this to query a module's metadata, which they3263+ could then use to, for example, search for, download, and3264+ install missing dependencies.3265+3266+ - title: Colors3267+ body: |3268+3269+ To configure alternative colors just set the `JQ_COLORS`3270+ environment variable to colon-delimited list of partial terminal3271+ escape sequences like `"1;31"`, in this order:3272+3273+ - color for `null`3274+ - color for `false`3275+ - color for `true`3276+ - color for numbers3277+ - color for strings3278+ - color for arrays3279+ - color for objects3280+3281+ The default color scheme is the same as setting3282+ `"JQ_COLORS=1;30:0;39:0;39:0;39:0;32:1;39:1;39"`.3283+3284+ This is not a manual for VT100/ANSI escapes. However, each of3285+ these color specifications should consist of two numbers separated3286+ by a semi-colon, where the first number is one of these:3287+3288+ - 1 (bright)3289+ - 2 (dim)3290+ - 4 (underscore)3291+ - 5 (blink)3292+ - 7 (reverse)3293+ - 8 (hidden)3294+3295+ and the second is one of these:3296+3297+ - 30 (black)3298+ - 31 (red)3299+ - 32 (green)3300+ - 33 (yellow)3301+ - 34 (blue)3302+ - 35 (magenta)3303+ - 36 (cyan)3304+ - 37 (white)added:docs/content/tutorial/default.yml+327 added
1+headline: Tutorial2+body:3+ - text: |4+5+ GitHub has a JSON API, so let's play with that. This URL gets us the last6+ 5 commits from the jq repo.7+8+ - command: "curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5'"9+ result: |10+ [11+ {12+ "sha": "d25341478381063d1c76e81b3a52e0592a7c997f",13+ "commit": {14+ "author": {15+ "name": "Stephen Dolan",16+ "email": "mu@netsoc.tcd.ie",17+ "date": "2013-06-22T16:30:59Z"18+ },19+ "committer": {20+ "name": "Stephen Dolan",21+ "email": "mu@netsoc.tcd.ie",22+ "date": "2013-06-22T16:30:59Z"23+ },24+ "message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",25+ "tree": {26+ "sha": "6ab697a8dfb5a96e124666bf6d6213822599fb40",27+ "url": "https://api.github.com/repos/stedolan/jq/git/trees/6ab697a8dfb5a96e124666bf6d6213822599fb40"28+ },29+ "url": "https://api.github.com/repos/stedolan/jq/git/commits/d25341478381063d1c76e81b3a52e0592a7c997f",30+ "comment_count": 031+ },32+ "url": "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f",33+ "html_url": "https://github.com/stedolan/jq/commit/d25341478381063d1c76e81b3a52e0592a7c997f",34+ "comments_url": "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f/comments",35+ "author": {36+ "login": "stedolan",37+ ...38+39+ - text: |40+41+ GitHub returns nicely formatted JSON. For servers that don't, it can be42+ helpful to pipe the response through jq to pretty-print it. The simplest43+ jq program is the expression `.`, which takes the input and produces it44+ unchanged as output.45+46+ - command: "curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jq '.'"47+ result: |48+ [49+ {50+ "sha": "d25341478381063d1c76e81b3a52e0592a7c997f",51+ "commit": {52+ "author": {53+ "name": "Stephen Dolan",54+ "email": "mu@netsoc.tcd.ie",55+ "date": "2013-06-22T16:30:59Z"56+ },57+ "committer": {58+ "name": "Stephen Dolan",59+ "email": "mu@netsoc.tcd.ie",60+ "date": "2013-06-22T16:30:59Z"61+ },62+ "message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",63+ "tree": {64+ "sha": "6ab697a8dfb5a96e124666bf6d6213822599fb40",65+ "url": "https://api.github.com/repos/stedolan/jq/git/trees/6ab697a8dfb5a96e124666bf6d6213822599fb40"66+ },67+ "url": "https://api.github.com/repos/stedolan/jq/git/commits/d25341478381063d1c76e81b3a52e0592a7c997f",68+ "comment_count": 069+ },70+ "url": "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f",71+ "html_url": "https://github.com/stedolan/jq/commit/d25341478381063d1c76e81b3a52e0592a7c997f",72+ "comments_url": "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f/comments",73+ "author": {74+ "login": "stedolan",75+ ...76+77+ - text: |78+79+ We can use jq to extract just the first commit.80+81+ - command: "curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jq '.[0]'"82+ result: |83+ {84+ "sha": "d25341478381063d1c76e81b3a52e0592a7c997f",85+ "commit": {86+ "author": {87+ "name": "Stephen Dolan",88+ "email": "mu@netsoc.tcd.ie",89+ "date": "2013-06-22T16:30:59Z"90+ },91+ "committer": {92+ "name": "Stephen Dolan",93+ "email": "mu@netsoc.tcd.ie",94+ "date": "2013-06-22T16:30:59Z"95+ },96+ "message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",97+ "tree": {98+ "sha": "6ab697a8dfb5a96e124666bf6d6213822599fb40",99+ "url": "https://api.github.com/repos/stedolan/jq/git/trees/6ab697a8dfb5a96e124666bf6d6213822599fb40"100+ },101+ "url": "https://api.github.com/repos/stedolan/jq/git/commits/d25341478381063d1c76e81b3a52e0592a7c997f",102+ "comment_count": 0103+ },104+ "url": "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f",105+ "html_url": "https://github.com/stedolan/jq/commit/d25341478381063d1c76e81b3a52e0592a7c997f",106+ "comments_url": "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f/comments",107+ "author": {108+ "login": "stedolan",109+ "id": 79765,110+ "avatar_url": "https://avatars.githubusercontent.com/u/79765?v=3",111+ "gravatar_id": "",112+ "url": "https://api.github.com/users/stedolan",113+ "html_url": "https://github.com/stedolan",114+ "followers_url": "https://api.github.com/users/stedolan/followers",115+ "following_url": "https://api.github.com/users/stedolan/following{/other_user}",116+ "gists_url": "https://api.github.com/users/stedolan/gists{/gist_id}",117+ "starred_url": "https://api.github.com/users/stedolan/starred{/owner}{/repo}",118+ "subscriptions_url": "https://api.github.com/users/stedolan/subscriptions",119+ "organizations_url": "https://api.github.com/users/stedolan/orgs",120+ "repos_url": "https://api.github.com/users/stedolan/repos",121+ "events_url": "https://api.github.com/users/stedolan/events{/privacy}",122+ "received_events_url": "https://api.github.com/users/stedolan/received_events",123+ "type": "User",124+ "site_admin": false125+ },126+ "committer": {127+ "login": "stedolan",128+ "id": 79765,129+ "avatar_url": "https://avatars.githubusercontent.com/u/79765?v=3",130+ "gravatar_id": "",131+ "url": "https://api.github.com/users/stedolan",132+ "html_url": "https://github.com/stedolan",133+ "followers_url": "https://api.github.com/users/stedolan/followers",134+ "following_url": "https://api.github.com/users/stedolan/following{/other_user}",135+ "gists_url": "https://api.github.com/users/stedolan/gists{/gist_id}",136+ "starred_url": "https://api.github.com/users/stedolan/starred{/owner}{/repo}",137+ "subscriptions_url": "https://api.github.com/users/stedolan/subscriptions",138+ "organizations_url": "https://api.github.com/users/stedolan/orgs",139+ "repos_url": "https://api.github.com/users/stedolan/repos",140+ "events_url": "https://api.github.com/users/stedolan/events{/privacy}",141+ "received_events_url": "https://api.github.com/users/stedolan/received_events",142+ "type": "User",143+ "site_admin": false144+ },145+ "parents": [146+ {147+ "sha": "54b9c9bdb225af5d886466d72f47eafc51acb4f7",148+ "url": "https://api.github.com/repos/stedolan/jq/commits/54b9c9bdb225af5d886466d72f47eafc51acb4f7",149+ "html_url": "https://github.com/stedolan/jq/commit/54b9c9bdb225af5d886466d72f47eafc51acb4f7"150+ },151+ {152+ "sha": "8b1b503609c161fea4b003a7179b3fbb2dd4345a",153+ "url": "https://api.github.com/repos/stedolan/jq/commits/8b1b503609c161fea4b003a7179b3fbb2dd4345a",154+ "html_url": "https://github.com/stedolan/jq/commit/8b1b503609c161fea4b003a7179b3fbb2dd4345a"155+ }156+ ]157+ }158+159+ - text: |160+161+ For the rest of the examples, I'll leave out the `curl` command - it's not162+ going to change.163+164+ There's a lot of info we don't care about there, so we'll restrict it down165+ to the most interesting fields.166+167+ - command: "jq '.[0] | {message: .commit.message, name: .commit.committer.name}'"168+ result: |169+ {170+ "message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",171+ "name": "Stephen Dolan"172+ }173+174+ - text: |175+176+ The `|` operator in jq feeds the output of one filter (`.[0]` which gets177+ the first element of the array in the response) into the input of another178+ (`{...}` which builds an object out of those fields). You can access179+ nested attributes, such as `.commit.message`.180+181+ Now let's get the rest of the commits.182+183+ - command: "jq '.[] | {message: .commit.message, name: .commit.committer.name}'"184+ result: |185+ {186+ "message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",187+ "name": "Stephen Dolan"188+ }189+ {190+ "message": "Reject all overlong UTF8 sequences.",191+ "name": "Stephen Dolan"192+ }193+ {194+ "message": "Fix various UTF8 parsing bugs.\n\nIn particular, parse bad UTF8 by replacing the broken bits with U+FFFD\nand resychronise correctly after broken sequences.",195+ "name": "Stephen Dolan"196+ }197+ {198+ "message": "Fix example in manual for `floor`. See #155.",199+ "name": "Stephen Dolan"200+ }201+ {202+ "message": "Document floor",203+ "name": "Nicolas Williams"204+ }205+206+ - text: |207+208+ `.[]` returns each element of the array returned in the response, one at a209+ time, which are all fed into210+ `{message: .commit.message, name: .commit.committer.name}`.211+212+ Data in jq is represented as streams of JSON values - every jq213+ expression runs for each value in its input stream, and can214+ produce any number of values to its output stream.215+216+ Streams are serialised by just separating JSON values with217+ whitespace. This is a `cat`-friendly format - you can just join218+ two JSON streams together and get a valid JSON stream.219+220+ If you want to get the output as a single array, you can tell jq to221+ "collect" all of the answers by wrapping the filter in square222+ brackets:223+224+ - command: "jq '[.[] | {message: .commit.message, name: .commit.committer.name}]'"225+ result: |226+ [227+ {228+ "message": "Merge pull request #163 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",229+ "name": "Stephen Dolan"230+ },231+ {232+ "message": "Reject all overlong UTF8 sequences.",233+ "name": "Stephen Dolan"234+ },235+ {236+ "message": "Fix various UTF8 parsing bugs.\n\nIn particular, parse bad UTF8 by replacing the broken bits with U+FFFD\nand resychronise correctly after broken sequences.",237+ "name": "Stephen Dolan"238+ },239+ {240+ "message": "Fix example in manual for `floor`. See #155.",241+ "name": "Stephen Dolan"242+ },243+ {244+ "message": "Document floor",245+ "name": "Nicolas Williams"246+ }247+ ]248+249+ - text: |250+251+ - - -252+253+ Next, let's try getting the URLs of the parent commits out of the254+ API results as well. In each commit, the GitHub API includes information255+ about "parent" commits. There can be one or many.256+257+ "parents": [258+ {259+ "sha": "54b9c9bdb225af5d886466d72f47eafc51acb4f7",260+ "url": "https://api.github.com/repos/stedolan/jq/commits/54b9c9bdb225af5d886466d72f47eafc51acb4f7",261+ "html_url": "https://github.com/stedolan/jq/commit/54b9c9bdb225af5d886466d72f47eafc51acb4f7"262+ },263+ {264+ "sha": "8b1b503609c161fea4b003a7179b3fbb2dd4345a",265+ "url": "https://api.github.com/repos/stedolan/jq/commits/8b1b503609c161fea4b003a7179b3fbb2dd4345a",266+ "html_url": "https://github.com/stedolan/jq/commit/8b1b503609c161fea4b003a7179b3fbb2dd4345a"267+ }268+ ]269+270+ We want to pull out all of the "html_url" fields inside that array of parent271+ commits and make a simple list of strings to go along with the272+ "message" and "author" fields we already have.273+274+ - command: "jq '[.[] | {message: .commit.message, name: .commit.committer.name, parents: [.parents[].html_url]}]'"275+ result: |276+ [277+ {278+ "message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",279+ "name": "Stephen Dolan",280+ "parents": [281+ "https://github.com/stedolan/jq/commit/54b9c9bdb225af5d886466d72f47eafc51acb4f7",282+ "https://github.com/stedolan/jq/commit/8b1b503609c161fea4b003a7179b3fbb2dd4345a"283+ ]284+ },285+ {286+ "message": "Reject all overlong UTF8 sequences.",287+ "name": "Stephen Dolan",288+ "parents": [289+ "https://github.com/stedolan/jq/commit/ff48bd6ec538b01d1057be8e93b94eef6914e9ef"290+ ]291+ },292+ {293+ "message": "Fix various UTF8 parsing bugs.\n\nIn particular, parse bad UTF8 by replacing the broken bits with U+FFFD\nand resychronise correctly after broken sequences.",294+ "name": "Stephen Dolan",295+ "parents": [296+ "https://github.com/stedolan/jq/commit/54b9c9bdb225af5d886466d72f47eafc51acb4f7"297+ ]298+ },299+ {300+ "message": "Fix example in manual for `floor`. See #155.",301+ "name": "Stephen Dolan",302+ "parents": [303+ "https://github.com/stedolan/jq/commit/3dcdc582ea993afea3f5503a78a77675967ecdfa"304+ ]305+ },306+ {307+ "message": "Document floor",308+ "name": "Nicolas Williams",309+ "parents": [310+ "https://github.com/stedolan/jq/commit/7c4171d414f647ab08bcd20c76a4d8ed68d9c602"311+ ]312+ }313+ ]314+315+ - text: |316+317+ Here we're making an object as before, but this time the `parents`318+ field is being set to `[.parents[].html_url]`, which collects319+ all of the parent commit URLs defined in the parents object.320+321+ - text: |322+323+ - - -324+325+ Here endeth the tutorial! There's lots more to play with. Go326+ read [the manual](../manual/) if you're interested, and [download327+ jq](../download/) if you haven't already.added:docs/content/index.yml+73 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273headline: jq
blurb: |
jq is a lightweight and flexible command-line JSON processor.
body1: |
jq is like `sed` for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that `sed`, `awk`, `grep` and friends let you play with text.
body2: |
jq is written in portable C, and it has zero runtime dependencies. You can download a single binary, `scp` it to a far away machine of the same type, and expect it to work.
body3: |
jq can mangle the data format that you have into the one that you want with very little effort, and the program to do so is often shorter and simpler than you'd expect.
tail: |
Go read the [tutorial](/jq/tutorial/) for more, or the [manual](/jq/manual/) for *way* more.
Ask questions on [stackoverflow](https://stackoverflow.com/) using the [jq tag](https://stackoverflow.com/questions/tagged/jq), or on the [#jq](http://irc.lc/freenode/%23jq/) channel on [Freenode](https://webchat.freenode.net/).
news: - date: 1 November 2018 body: | jq 1.6 released. See installation options on the [download](/jq/download/) page, and the [release notes](https://github.com/stedolan/jq/releases/tag/jq-1.6) for details.
- date: 15 August 2015 body: |
jq 1.5 released, including new datetime, math, and regexp functions, try/catch syntax, array and object destructuring, a streaming parser, and a module system. See installation options on the [download](/jq/download/) page, and the [release notes](https://github.com/stedolan/jq/releases/tag/jq-1.5) for details.
- date: 26 July 2015 body: |
jq 1.5rc2 is available. Get it on the [releases](https://github.com/stedolan/jq/releases) page.
- date: 01 January 2015 body: |
jq 1.5rc1 is available. Get it on the [releases](https://github.com/stedolan/jq/releases) page.
- date: 09 June 2014 body: |
jq 1.4 (finally) released! Get it on the [download](/jq/download/) page.
- date: 19 May 2013 body: |
jq 1.3 released.
added:docs/public/css/base.css+173 added
1+body {2+ padding-top: 80px;3+}4+5+.container {6+ max-width: 970px;7+}8+9+/* index.liquid *******************************************/10+#blurb {11+ padding-top: 40px;12+}13+#blurb p {14+ font-size: 1.9em;15+}16+#blurb .btn-group {17+ margin: 4px;18+}19+20+#multiblurb {21+ line-height: 1.7;22+ text-align: center;23+ font-size: 12pt;24+}25+#multiblurb code {26+ border: 0;27+ font-size: 12pt;28+}29+30+#news {31+ font-size: 12pt;32+}33+#news .date {34+ font-style: italic;35+}36+37+/* default.liquid *****************************************/38+.tutorial-example {39+ position: relative;40+ margin-bottom: 10px;41+}42+.tutorial-example pre {43+ margin-bottom: 0px;44+}45+.tutorial-example a {46+ position: absolute;47+ top: 0px;48+ right: 0px;49+ padding: 15px 8px;50+ color: #777777;51+ font-weight: bold;52+ line-height: 10px;53+ font-size: 12px;54+ border-left: 1px solid #DDDDDD;55+ display: block;56+}57+.tutorial-example .accordion-body pre {58+ margin: 0 4px;59+ border-top: 0;60+ border-top-left-radius: 0;61+ border-top-right-radius: 0;62+}63+64+@media print {65+ .tutorial-example a {66+ display: none;67+ }68+}69+/* manual.liquid ******************************************/70+section {71+ padding-top: 24px;72+}73+74+h3 code {75+ border: 0;76+ font-size: 20px;77+}78+79+@media (max-width: 991px) {80+ #navcolumn {81+ /* Put nav column above manual content */82+ position: relative !important;83+ margin-bottom: 60px;84+ }85+}86+@media (min-width: 992px) {87+ #manualcontent {88+ /* Put nav column left of manual content */89+ padding-left: 280px;90+ }91+}92+.nav-pills {93+ margin-bottom: 20px;94+}95+ .nav-pills li a {96+ padding: 8px 12px;97+}98+99+.manual-example table {100+ border-top: 1px solid #E5E5E5;101+}102+.manual-example table td {103+ white-space: pre-wrap;104+ font-family: Monaco, Menlo, Consolas, "Courier New", monospace;105+}106+.manual-example table td.jqprogram {107+ font-weight: bold;108+}109+.manual-example table th {110+ text-align: right;111+ padding-right: 10px;112+}113+114+@media print {115+ #navcolumn {116+ display: none !important;117+ }118+119+ .manual-example {120+ display: block !important;121+ height: auto !important;122+ }123+124+ .jqplay-btn {125+ display: none !important;126+ }127+}128+/* shared/_footer.liquid **********************************/129+footer {130+ background-color: #F5F5F5;131+ padding: 20px 0;132+ margin-top: 40px;133+ color: #999999;134+ text-align: center;135+}136+footer p {137+ margin: 8px 0;138+}139+140+/* typeahead **********************************************/141+.twitter-typeahead {142+ width: 100%;143+}144+145+.tt-menu {146+ width: 100%;147+ background-color: #fff;148+ padding: 8px 0;149+ border: 1px solid #ccc;150+ border: 1px solid rgba(0, 0, 0, 0.2);151+ -webkit-border-radius: 8px;152+ -moz-border-radius: 8px;153+ border-radius: 8px;154+ -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);155+ -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);156+ box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);157+}158+159+.tt-suggestion {160+ padding: 3px 20px;161+}162+.tt-suggestion:hover {163+ cursor: pointer;164+ color: #fff;165+ background-color: #446e9b;166+}167+.tt-suggestion.tt-cursor {168+ color: #fff;169+ background-color: #446e9b;170+}171+.tt-suggestion p {172+ margin: 0;173+}added:docs/templates/shared/_footer.html.j2+10 added
1+ <footer>2+ <div class="container">3+ <p>This website is made with <a href="http://getbootstrap.com">Bootstrap</a>, themed with <a href="https://bootswatch.com">Bootswatch</a>.</p>4+ <p>jq is licensed under the MIT license (code) and the <a href="https://creativecommons.org/licenses/by/3.0/">CC-BY-3.0</a> license (docs).</p>5+ </div>6+ </footer>7+8+ <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>9+ <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" integrity="sha256-Sk3nkD6mLTMOF0EOpNtsIry+s1CsaqQC1rVLTAy+0yc= sha512-K1qjQ+NcF2TYO/eI3M6v8EiNYZfA95pQumfvcVrTHtwQVDG+aHRqLi/ETn2uB+1JqwYqVG3LIvdm9lj6imS/pQ==" crossorigin="anonymous"></script>10+ <script src="https://twitter.github.io/typeahead.js/releases/0.11.1/typeahead.bundle.js"></script>deleted:docs/templates/shared/_footer.liquid-10 removed
1- <footer>2- <div class="container">3- <p>This website is made with <a href="http://www.tinytree.info">Bonsai</a> and <a href="http://getbootstrap.com">Bootstrap</a>, themed with <a href="https://bootswatch.com">Bootswatch</a>.</p>4- <p>jq is licensed under the MIT license (code) and the <a href="https://creativecommons.org/licenses/by/3.0/">CC-BY-3.0</a> license (docs).</p>5- </div>6- </footer>7-8- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>9- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" integrity="sha256-Sk3nkD6mLTMOF0EOpNtsIry+s1CsaqQC1rVLTAy+0yc= sha512-K1qjQ+NcF2TYO/eI3M6v8EiNYZfA95pQumfvcVrTHtwQVDG+aHRqLi/ETn2uB+1JqwYqVG3LIvdm9lj6imS/pQ==" crossorigin="anonymous"></script>10- <script src="https://twitter.github.io/typeahead.js/releases/0.11.1/typeahead.bundle.js"></script>added:docs/templates/shared/_head.html.j2+17 added
1+ <head>2+ <script>3+ if ((window.location.host == "stedolan.github.io") && (window.location.protocol != "https:"))4+ window.location.protocol = "https";5+ </script>6+ <meta charset="utf-8">7+ <title>{{headline}}</title>8+ <meta name="viewport" content="width=device-width, initial-scale=1">9+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />10+ <link rel="canonical" href="{{ url }}{{ permalink | replace('/index','') }}" />11+ <link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/spacelab/bootstrap.min.css" rel="stylesheet" integrity="sha256-j7Dtnd7ZjexEiPNbscbopFn9+Cs0b3TLipKsWAPHZIM= sha512-RFhfi6P8zWMAJrEGU+CPjuxPh3r/UUBGqQ+/o6WKPIVZmQqeOipGotH2ihRULuQ8wsMBoK15TSZqc/7VYWyuIw==" crossorigin="anonymous">12+ <link rel="stylesheet" href="{{ root }}/css/base.css" type="text/css">13+ <!--[if lt IE 9]>14+ <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>15+ <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>16+ <![endif]-->17+ </head>deleted:docs/templates/shared/_head.liquid-17 removed
1- <head>2- <script>3- if ((window.location.host == "stedolan.github.io") && (window.location.protocol != "https:"))4- window.location.protocol = "https";5- </script>6- <meta charset="utf-8">7- <title>{{headline}}</title>8- <meta name="viewport" content="width=device-width, initial-scale=1">9- <meta http-equiv="X-UA-Compatible" content="IE=edge" />10- <link rel="canonical" href="{{url}}{{permalink | remove:'/index'}}" />11- <link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/spacelab/bootstrap.min.css" rel="stylesheet" integrity="sha256-j7Dtnd7ZjexEiPNbscbopFn9+Cs0b3TLipKsWAPHZIM= sha512-RFhfi6P8zWMAJrEGU+CPjuxPh3r/UUBGqQ+/o6WKPIVZmQqeOipGotH2ihRULuQ8wsMBoK15TSZqc/7VYWyuIw==" crossorigin="anonymous">12- <link rel="stylesheet" href="{{root}}/css/base.css" type="text/css">13- <!--[if lt IE 9]>14- <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>15- <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>16- <![endif]-->17- </head>added:docs/templates/shared/_navbar.html.j2+27 added
1+ <div class="navbar navbar-default navbar-fixed-top" role="navigation">2+ <div class="container">3+ <div class="navbar-header">4+ <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#nav-collapse">5+ <span class="sr-only">Toggle navigation</span>6+ <span class="icon-bar"></span>7+ <span class="icon-bar"></span>8+ <span class="icon-bar"></span>9+ </button>10+ <a class="navbar-brand" href="{{root}}/">jq</a>11+ </div>12+13+ <div class="navbar-collapse collapse" id="nav-collapse">14+ <ul class="nav navbar-nav">15+ {% for item in navigation %}16+ <li {% if item == permalink %} class="active" {% endif %}>17+ <a href="{{root}}/{{item}}">{{item | capitalize}}</a>18+ </li>19+ {% endfor %}20+ <li><a href="https://github.com/stedolan/jq/issues">Issues</a></li>21+ <li><a href="https://github.com/stedolan/jq">Source</a></li>22+ <li><a href="https://jqplay.org">Try online!</a></li>23+ <li><a href="https://raw.githubusercontent.com/stedolan/jq/master/NEWS">News</a></li>24+ </ul>25+ </div>26+ </div>27+ </div>deleted:docs/templates/shared/_navbar.liquid-27 removed
1- <div class="navbar navbar-default navbar-fixed-top" role="navigation">2- <div class="container">3- <div class="navbar-header">4- <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#nav-collapse">5- <span class="sr-only">Toggle navigation</span>6- <span class="icon-bar"></span>7- <span class="icon-bar"></span>8- <span class="icon-bar"></span>9- </button>10- <a class="navbar-brand" href="{{root}}/">jq</a>11- </div>12-13- <div class="navbar-collapse collapse" id="nav-collapse">14- <ul class="nav navbar-nav">15- {% for item in navigation %}16- <li {% if item.permalink == permalink %} class="active" {% endif %}>17- <a href="{{root}}{{item.permalink}}">{{item.name}}</a>18- </li>19- {% endfor %}20- <li><a href="https://github.com/stedolan/jq/issues">Issues</a></li>21- <li><a href="https://github.com/stedolan/jq">Source</a></li>22- <li><a href="https://jqplay.org">Try online!</a></li>23- <li><a href="https://raw.githubusercontent.com/stedolan/jq/master/NEWS">News</a></li>24- </ul>25- </div>26- </div>27- </div>added:docs/templates/default.html.j2+34 added
1+<!DOCTYPE html>2+<html lang="en">3+{% include "shared/_head.html.j2" %}4+5+ <body id="{{slug}}">6+{% include "shared/_navbar.html.j2" %}7+8+ <div class="container">9+ <div class="row">10+ <h1>{{headline}}</h1>11+ {% for item in body %}12+ {% if item.text %}13+ {{ item.text | replace('$JQ_VERSION', jq_version) | markdownify }}14+ {% endif %}15+16+ {% if item.command %}17+ {% set resultID = unique_id() %}18+ <div class="tutorial-example">19+ <div class="accordion-heading">20+ <pre>{{item.command}}</pre>21+ <a data-toggle="collapse" href="#result{{resultID}}">Show result</a>22+ </div>23+ <div id="result{{resultID}}" class="accordion-body collapse">24+ <pre>{{item.result}}</pre>25+ </div>26+ </div>27+ {% endif %}28+ {% endfor %}29+ </div>30+ </div>31+32+{% include "shared/_footer.html.j2" %}33+ </body>34+</html>deleted:docs/templates/default.liquid-34 removed
1-<!DOCTYPE html>2-<html lang="en">3-{% include "shared/head" %}4-5- <body id="{{slug}}">6-{% include "shared/navbar" %}7-8- <div class="container">9- <div class="row">10- <h1>{{headline}}</h1>11- {% for item in body %}12- {% if item.text %}13- {{ item.text | replace: '$JQ_VERSION', jq_version | markdownify }}14- {% endif %}15-16- {% if item.command %}17- {% capture resultID %}{{ "result" | unique}}{% endcapture %}18- <div class="tutorial-example">19- <div class="accordion-heading">20- <pre>{{item.command}}</pre>21- <a data-toggle="collapse" href="#{{resultID}}">Show result</a>22- </div>23- <div id="{{resultID}}" class="accordion-body collapse">24- <pre>{{item.result}}</pre>25- </div>26- </div>27- {% endif %}28- {% endfor %}29- </div>30- </div>31-32-{% include "shared/footer" %}33- </body>34-</html>added:docs/templates/index.html.j2+73 added
1+<!DOCTYPE html>2+<html lang="en">3+{% include "shared/_head.html.j2" %}4+5+ <body id="{{ slug }}">6+{% include "shared/_navbar.html.j2" %}7+8+ <div class="container">9+ <div class="row">10+ <div class="jumbotron">11+ <div class="row">12+ <div class="col-sm-6">13+ <img src="{{root}}/jq.png" class="img-responsive" alt="jq logo"14+ width="400" height="220">15+ </div>16+ <div class="col-sm-6">17+ <div id="blurb">18+ {{blurb | markdownify}}19+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.624+ <span class="caret"></span>25+ </a>26+ <ul class="dropdown-menu">27+ <li><a href="https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64">Linux (64-bit)</a></li>28+ <li><a href="https://github.com/stedolan/jq/releases/download/jq-1.6/jq-osx-amd64">OS X (64-bit)</a></li>29+ <li><a href="https://github.com/stedolan/jq/releases/download/jq-1.6/jq-win64.exe">Windows (64-bit)</a></li>30+ <li><a href="{{root}}/download/">Other platforms, older versions, and source</a></li>31+ </ul>32+ </div>33+34+ <div class="btn-group">35+ <a class="btn btn-primary" href="https://jqplay.org">36+ Try online at jqplay.org!37+ </a>38+ </div>39+ </div>40+ </div>41+ </div>42+ </div>43+ </div>44+ </div>45+46+ <div class="row" id="multiblurb">47+ <div class="col-sm-4">{{body1 | markdownify}}</div>48+ <div class="col-sm-4">{{body2 | markdownify}}</div>49+ <div class="col-sm-4">{{body3 | markdownify}}</div>50+ </div>51+52+ <div class="row" style="text-align:center; margin-top: 30px">53+ {{tail | markdownify}}54+ </div>55+56+ <div class="row">57+ <h2>News</h2>58+ <div id="news">59+ <ul>60+ {% for item in news %}61+ <li>62+ <span class="date">{{item.date}}</span>63+ {{item.body | markdownify}}64+ </li>65+ {% endfor %}66+ </ul>67+ </div>68+ </div>69+ </div>70+71+{% include "shared/_footer.html.j2" %}72+ </body>73+</html>deleted:docs/templates/index.liquid-73 removed
1-<!DOCTYPE html>2-<html lang="en">3-{% include "shared/head" %}4-5- <body id="{{slug}}">6-{% include "shared/navbar" %}7-8- <div class="container">9- <div class="row">10- <div class="jumbotron">11- <div class="row">12- <div class="col-sm-6">13- <img src="{{root}}/jq.png" class="img-responsive" alt="jq logo"14- width="400" height="220">15- </div>16- <div class="col-sm-6">17- <div id="blurb">18- {{blurb | markdownify}}19-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.624- <span class="caret"></span>25- </a>26- <ul class="dropdown-menu">27- <li><a href="https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64">Linux (64-bit)</a></li>28- <li><a href="https://github.com/stedolan/jq/releases/download/jq-1.6/jq-osx-amd64">OS X (64-bit)</a></li>29- <li><a href="https://github.com/stedolan/jq/releases/download/jq-1.6/jq-win64.exe">Windows (64-bit)</a></li>30- <li><a href="/jq/download/">Other platforms, older versions, and source</a></li>31- </ul>32- </div>33-34- <div class="btn-group">35- <a class="btn btn-primary" href="https://jqplay.org">36- Try online at jqplay.org!37- </a>38- </div>39- </div>40- </div>41- </div>42- </div>43- </div>44- </div>45-46- <div class="row" id="multiblurb">47- <div class="col-sm-4">{{body1 | markdownify}}</div>48- <div class="col-sm-4">{{body2 | markdownify}}</div>49- <div class="col-sm-4">{{body3 | markdownify}}</div>50- </div>51-52- <div class="row" style="text-align:center; margin-top: 30px">53- {{tail | markdownify}}54- </div>55-56- <div class="row">57- <h2>News</h2>58- <div id="news">59- <ul>60- {% for item in news %}61- <li>62- <span class="date">{{item.date}}</span>63- {{item.body | markdownify}}64- </li>65- {% endfor %}66- </ul>67- </div>68- </div>69- </div>70-71-{% include "shared/footer" %}72- </body>73-</html>added:docs/templates/manual.html.j2+99 added
1+<!DOCTYPE html>2+<html lang="en">3+{% include "shared/_head.html.j2" %}4+5+ <body id="{{slug}}" data-spy="scroll" data-target="#navcolumn" data-offset="100">6+{% include "shared/_navbar.html.j2" %}7+8+ <div class="container">9+ <div class="row">10+ <div class="affix" id="navcolumn">11+ <h4>Contents</h4>12+ <ul class="nav nav-pills nav-stacked">13+ {% for section in sections %}14+ <li>15+ <a href="#{{section.title | section_id}}">{{section.title}}</a>16+ </li>17+ {% endfor %}18+ </ul>19+ <form class="form-group" onsubmit="go_to_section(); return false;">20+ <input type="text"21+ class="form-control"22+ placeholder="Search"23+ autocomplete="off"24+ id="searchbox">25+ </form>26+ </div>27+28+ <div id="manualcontent">29+ <h1>{{headline}}</h1>30+ {{ history | markdownify }}31+ {{ body | markdownify }}32+ {% for section in sections %}33+ <section id="{{section.title | section_id}}">34+ <h2>{{section.title}}</h2>35+ {{ (section.body | markdownify) if section.body }}36+ {% for entry in section.entries %}37+ <section id="{{entry.title | entry_id}}">38+ <h3>39+ {{entry.title | markdownify | no_paragraph }}40+ {% if entry.subtitle %}<small>{{entry.subtitle}}</small>{% endif %}41+ </h3>42+ {{entry.body | markdownify}}43+44+ {% if entry.examples %}45+ <div>46+ {% set exampleID = unique_id() %}47+ <a data-toggle="collapse" href="#example{{exampleID}}">48+ <i class="glyphicon glyphicon-chevron-right"></i>49+ {% if entry.examples | length > 1 %}Examples{%else%}Example{%endif%}50+ </a>51+ <div id="example{{exampleID}}" class="manual-example collapse">52+ {% for example in entry.examples %}53+ <table>54+ <tr><th></th><td class="jqprogram">jq '{{ example.program }}'</td></tr>55+ <tr><th>Input</th><td>{{ example.input }}</td></tr>56+ {% if not example.output[0] %}57+ <tr>58+ <th>Output</th>59+ <td><i>none</i></td>60+ </tr>61+ {% endif %}62+ {% for output in example.output %}63+ <tr>64+ {% if loop.first %}65+ <th>Output</th>66+ {% else %}67+ <th></th>68+ {% endif %}69+ <td>{{ output }}</td>70+ </tr>71+ {% endfor %}72+ </table>73+ {% endfor %}74+ </div>75+ </div>76+ {% endif %}77+ </section>78+ {% endfor %}79+ </section>80+ {% endfor %}81+ </div>82+ </div>83+ </div>84+85+{% include "shared/_footer.html.j2" %}86+ <script>87+ var section_map = {88+ {% for section in sections %}89+ {% for entry in section.entries %}90+ {{entry.title | search_id | tojson }} : {{entry.title | entry_id | tojson }},91+ {% endfor %}92+ {{section.title | search_id | tojson }} : {{section.title | section_id | tojson }}93+ {% if not loop.last %},{% endif %}94+ {% endfor %}95+ };96+ </script>97+ <script src="{{root}}/js/manual-search.js"></script>98+ </body>99+</html>deleted:docs/templates/manual.liquid-99 removed
1-<!DOCTYPE html>2-<html lang="en">3-{% include "shared/head" %}4-5- <body id="{{slug}}" data-spy="scroll" data-target="#navcolumn" data-offset="100">6-{% include "shared/navbar" %}7-8- <div class="container">9- <div class="row">10- <div class="affix" id="navcolumn">11- <h4>Contents</h4>12- <ul class="nav nav-pills nav-stacked">13- {% for section in sections %}14- <li>15- <a href="#{{section.title | section_id}}">{{section.title}}</a>16- </li>17- {% endfor %}18- </ul>19- <form class="form-group" onsubmit="go_to_section(); return false;">20- <input type="text"21- class="form-control"22- placeholder="Search"23- autocomplete="off"24- id="searchbox">25- </form>26- </div>27-28- <div id="manualcontent">29- <h1>{{headline}}</h1>30- {{ history | markdownify }}31- {{ body | markdownify }}32- {% for section in sections %}33- <section id="{{section.title | section_id}}">34- <h2>{{section.title}}</h2>35- {{section.body | markdownify}}36- {% for entry in section.entries %}37- <section id="{{entry.title | entry_id}}">38- <h3>39- {{entry.title | markdownify | no_paragraph}}40- {% if entry.subtitle %}<small>{{entry.subtitle}}</small>{% endif %}41- </h3>42- {{entry.body | markdownify}}43-44- {% if entry.examples %}45- <div>46- {% capture exampleID %}{{ "" | unique }}{% endcapture %}47- <a data-toggle="collapse" href="#example{{exampleID}}">48- <i class="glyphicon glyphicon-chevron-right"></i>49- {% if entry.examples[1] %}Examples{%else%}Example{%endif%}50- </a>51- <div id="example{{exampleID}}" class="manual-example collapse">52- {% for example in entry.examples %}53- <table>54- <tr><th></th><td class="jqprogram">jq '{{example.program | escape}}'</td></tr>55- <tr><th>Input</th><td>{{example.input | escape}}</td></tr>56- {% unless example.output[0] %}57- <tr>58- <th>Output</th>59- <td><i>none</i></td>60- </tr>61- {% endunless %}62- {% for output in example.output %}63- <tr>64- {% if forloop.index == 1 %}65- <th>Output</th>66- {% else %}67- <th></th>68- {% endif %}69- <td>{{output | escape}}</td>70- </tr>71- {% endfor %}72- </table>73- {% endfor %}74- </div>75- </div>76- {% endif %}77- </section>78- {% endfor %}79- </section>80- {% endfor %}81- </div>82- </div>83- </div>84-85-{% include "shared/footer" %}86- <script>87- var section_map = {88- {% for section in sections %}89- {% for entry in section.entries %}90- {{entry.title | search_id | json}} : {{entry.title | entry_id | json}},91- {% endfor %}92- {{section.title | search_id | json}} : {{section.title | section_id | json}}93- {% unless forloop.last %},{% endunless %}94- {% endfor %}95- };96- </script>97- <script src="{{root}}/js/manual-search.js"></script>98- </body>99-</html>modified:docs/.gitignore-3 removed
1 .DS_Store2 .sass-cache3 output/*4-5-# Autogenerated from public/css/base.scss6-public/css/base.cssadded:docs/build_manpage.py+2 added
1+#!/usr/bin/env python32+print("Manpage build not yet supported")added:docs/build_website.py+62 added
1+#!/usr/bin/env python32+import glob3+import itertools4+from jinja2 import Environment, FileSystemLoader, Markup, select_autoescape, contextfunction5+from markdown import markdown6+import os7+import os.path8+import re9+import shutil10+import yaml11+12+env = Environment(13+ loader=FileSystemLoader('templates'),14+ autoescape=select_autoescape(['html.j2']),15+)16+17+def load_yml_file(fn):18+ with open(fn) as f:19+ return yaml.load(f)20+21+env.filters['search_id'] = lambda input: input.replace(r'`', '')22+env.filters['section_id'] = lambda input: re.sub(r"[^a-zA-Z0-9_]", '', input)23+env.filters['entry_id'] = lambda input: re.sub(r"[ `]", '', input)24+env.filters['markdownify'] = lambda input: Markup(markdown(input))25+env.filters['no_paragraph'] = lambda input: Markup(re.sub(r"</?p>", '', input))26+27+env.globals['unique_id'] = contextfunction(lambda ctx: str(next(ctx['unique_ctr'])))28+29+30+env.globals.update(load_yml_file('site.yml'))31+32+33+env.globals['navigation'] = ['tutorial', 'download', 'manual']34+35+def generate_file(env, fname='content/1.tutorial/default.yml'):36+ path, base = os.path.split(fname)37+ path = os.path.relpath(path, 'content')38+ output_dir = os.path.join('output', path)39+ output_path = os.path.join(output_dir, 'index.html')40+41+ template_name = re.sub(r".yml$", '.html.j2', base)42+43+ ctx = load_yml_file(fname)44+ ctx.update(unique_ctr=itertools.count(1), permalink=path)45+ os.makedirs(output_dir, exist_ok=True)46+ env.get_template(template_name).stream(ctx).dump(output_path, encoding='utf-8')47+48+49+def copy_public_files(root=''):50+ for f in os.scandir(os.path.join('public', root)):51+ src = os.path.join(root, f.name)52+ dst = os.path.join('output', src)53+ if f.is_dir():54+ os.makedirs(dst, exist_ok=True)55+ copy_public_files(src)56+ else:57+ shutil.copyfile(f.path, dst)58+59+copy_public_files()60+61+for fn in glob.glob('content/**/*.yml', recursive=True):62+ generate_file(env, fn)added:docs/Pipfile+11 added
1+[[source]]2+name = "pypi"3+url = "https://pypi.org/simple"4+verify_ssl = true5+6+[dev-packages]7+8+[packages]9+jinja2 = "*"10+pyyaml = "*"11+markdown = "*"added:docs/Pipfile.lock+85 added
1+{2+ "_meta": {3+ "hash": {4+ "sha256": "6cffc39e0d43a6d7c78f39636c7ed1b047f7b819b158213a96d7cbfefd6524d7"5+ },6+ "pipfile-spec": 6,7+ "requires": {},8+ "sources": [9+ {10+ "name": "pypi",11+ "url": "https://pypi.org/simple",12+ "verify_ssl": true13+ }14+ ]15+ },16+ "default": {17+ "jinja2": {18+ "hashes": [19+ "sha256:74c935a1b8bb9a3947c50a54766a969d4846290e1e788ea44c1392163723c3bd",20+ "sha256:f84be1bb0040caca4cea721fcbbbbd61f9be9464ca236387158b0feea01914a4"21+ ],22+ "index": "pypi",23+ "version": "==2.10"24+ },25+ "markdown": {26+ "hashes": [27+ "sha256:c00429bd503a47ec88d5e30a751e147dcb4c6889663cd3e2ba0afe858e009baa",28+ "sha256:d02e0f9b04c500cde6637c11ad7c72671f359b87b9fe924b2383649d8841db7c"29+ ],30+ "index": "pypi",31+ "version": "==3.0.1"32+ },33+ "markupsafe": {34+ "hashes": [35+ "sha256:048ef924c1623740e70204aa7143ec592504045ae4429b59c30054cb31e3c432",36+ "sha256:130f844e7f5bdd8e9f3f42e7102ef1d49b2e6fdf0d7526df3f87281a532d8c8b",37+ "sha256:19f637c2ac5ae9da8bfd98cef74d64b7e1bb8a63038a3505cd182c3fac5eb4d9",38+ "sha256:1b8a7a87ad1b92bd887568ce54b23565f3fd7018c4180136e1cf412b405a47af",39+ "sha256:1c25694ca680b6919de53a4bb3bdd0602beafc63ff001fea2f2fc16ec3a11834",40+ "sha256:1f19ef5d3908110e1e891deefb5586aae1b49a7440db952454b4e281b41620cd",41+ "sha256:1fa6058938190ebe8290e5cae6c351e14e7bb44505c4a7624555ce57fbbeba0d",42+ "sha256:31cbb1359e8c25f9f48e156e59e2eaad51cd5242c05ed18a8de6dbe85184e4b7",43+ "sha256:3e835d8841ae7863f64e40e19477f7eb398674da6a47f09871673742531e6f4b",44+ "sha256:4e97332c9ce444b0c2c38dd22ddc61c743eb208d916e4265a2a3b575bdccb1d3",45+ "sha256:525396ee324ee2da82919f2ee9c9e73b012f23e7640131dd1b53a90206a0f09c",46+ "sha256:52b07fbc32032c21ad4ab060fec137b76eb804c4b9a1c7c7dc562549306afad2",47+ "sha256:52ccb45e77a1085ec5461cde794e1aa037df79f473cbc69b974e73940655c8d7",48+ "sha256:5c3fbebd7de20ce93103cb3183b47671f2885307df4a17a0ad56a1dd51273d36",49+ "sha256:5e5851969aea17660e55f6a3be00037a25b96a9b44d2083651812c99d53b14d1",50+ "sha256:5edfa27b2d3eefa2210fb2f5d539fbed81722b49f083b2c6566455eb7422fd7e",51+ "sha256:7d263e5770efddf465a9e31b78362d84d015cc894ca2c131901a4445eaa61ee1",52+ "sha256:83381342bfc22b3c8c06f2dd93a505413888694302de25add756254beee8449c",53+ "sha256:857eebb2c1dc60e4219ec8e98dfa19553dae33608237e107db9c6078b1167856",54+ "sha256:98e439297f78fca3a6169fd330fbe88d78b3bb72f967ad9961bcac0d7fdd1550",55+ "sha256:bf54103892a83c64db58125b3f2a43df6d2cb2d28889f14c78519394feb41492",56+ "sha256:d9ac82be533394d341b41d78aca7ed0e0f4ba5a2231602e2f05aa87f25c51672",57+ "sha256:e982fe07ede9fada6ff6705af70514a52beb1b2c3d25d4e873e82114cf3c5401",58+ "sha256:edce2ea7f3dfc981c4ddc97add8a61381d9642dc3273737e756517cc03e84dd6",59+ "sha256:efdc45ef1afc238db84cb4963aa689c0408912a0239b0721cb172b4016eb31d6",60+ "sha256:f137c02498f8b935892d5c0172560d7ab54bc45039de8805075e19079c639a9c",61+ "sha256:f82e347a72f955b7017a39708a3667f106e6ad4d10b25f237396a7115d8ed5fd",62+ "sha256:fb7c206e01ad85ce57feeaaa0bf784b97fa3cad0d4a5737bc5295785f5c613a1"63+ ],64+ "version": "==1.1.0"65+ },66+ "pyyaml": {67+ "hashes": [68+ "sha256:3d7da3009c0f3e783b2c873687652d83b1bbfd5c88e9813fb7e5b03c0dd3108b",69+ "sha256:3ef3092145e9b70e3ddd2c7ad59bdd0252a94dfe3949721633e41344de00a6bf",70+ "sha256:40c71b8e076d0550b2e6380bada1f1cd1017b882f7e16f09a65be98e017f211a",71+ "sha256:558dd60b890ba8fd982e05941927a3911dc409a63dcb8b634feaa0cda69330d3",72+ "sha256:a7c28b45d9f99102fa092bb213aa12e0aaf9a6a1f5e395d36166639c1f96c3a1",73+ "sha256:aa7dd4a6a427aed7df6fb7f08a580d68d9b118d90310374716ae90b710280af1",74+ "sha256:bc558586e6045763782014934bfaf39d48b8ae85a2713117d16c39864085c613",75+ "sha256:d46d7982b62e0729ad0175a9bc7e10a566fc07b224d2c79fafb5e032727eaa04",76+ "sha256:d5eef459e30b09f5a098b9cea68bebfeb268697f78d647bd255a085371ac7f3f",77+ "sha256:e01d3203230e1786cd91ccfdc8f8454c8069c91bee3962ad93b87a4b2860f537",78+ "sha256:e170a9e6fcfd19021dd29845af83bb79236068bf5fd4df3327c1be18182b2531"79+ ],80+ "index": "pypi",81+ "version": "==3.13"82+ }83+ },84+ "develop": {}85+}modified:docs/README.md+10 added-15 removed
1 Documentation2 =============3 4 The jq website, manpages and some of the tests are generated from this5-directory. The directory holds a [Bonsai](http://tinytree.info)6-website, and the manual is a YAML file in `content/3.manual`.5+directory. The manual is a YAML file in `content/manual`.6 7 To build the documentation (including building the jq manpage), you'll9-need a working Ruby setup. The easiest way to get one is to install10-RVM and Ruby 1.9.3 like so:8+need python3 and pipenv. You can install pipenv like so:9 12- \curl -L https://get.rvm.io | bash -s stable --ruby=1.9.310+ pip install pipenv11 14-After that finishes installing, you'll need to make sure RVM is on15-your path by doing `source $HOME/.rvm/scripts/rvm`, or just opening a16-new shell. See <https://rvm.io> for more info on RVM.12+Though, you may need to say pip3 instead, depending on your system. Once13+you have pipenv installed, you can install the dependencies by running14+`pipenv install` from the `docs` directory.15 18-Once RVM is installed, you can install all the dependencies for jq's19-documentation build by running this from the `docs` directory:16+Once this is done, rerun `./configure` in the jq root directory and then17+the Makefile will be able to generate the jq manpage.18 21- bundle install22-23-When bundle manages to install the dependencies, rerun `./configure`24-in the jq root directory and then the Makefile will be able to25-generate the jq manpage.19+To build the website, run `pipenv run ./build_website.py` from inside20+the `docs` directory.modified:scripts/update-website+1 added-1 removed
9 unmodified lines10 # build website11 scriptdir=`dirname "$0"`12 cd "$scriptdir"/../docs13 rm -rf output14-rake build14+pipenv run python3 build_website.py15 cd ..16 17 # copy to /tmp18 tmpdir=$(mktemp -d -t jq.website.XXXXXXXXXX)11 unmodified linesmodified:configure.ac+10 added-10 removed
72 unmodified lines73 dnl Code coverage74 AC_ARG_ENABLE([gcov],75 AC_HELP_STRING([--enable-gcov], [enable gcov code coverage tool]))76 77-dnl Don't attempt to build docs if there's no Ruby lying around77+dnl Don't attempt to build docs if python deps aren't installed78 AC_ARG_ENABLE([docs],79 AC_HELP_STRING([--disable-docs], [don't build docs]))80 81 dnl Don't attempt to build the error injection object (if there is no LD_PRELOAD support)4 unmodified lines86 AC_ARG_ENABLE([all-static],87 AC_HELP_STRING([--enable-all-static], [link jq with static libraries only]))88 89 AS_IF([test "x$enable_docs" != "xno"],[90- AC_CHECK_PROGS(bundle_cmd, bundle)90+ AC_CHECK_PROGS(pipenv_cmd, pipenv)91 92- AC_CACHE_CHECK([for Ruby dependencies], [jq_cv_ruby_deps],93- [jq_cv_ruby_deps=yes;94- AS_IF([test "x$bundle_cmd" = "x" || \95- ! bmsg="`cd ${srcdir}/docs; "$bundle_cmd" check 2>/dev/null`"],[96- AC_MSG_WARN([$bmsg])92+ AC_CACHE_CHECK([for Python dependencies], [jq_cv_python_deps],93+ [jq_cv_python_deps=yes;94+ AS_IF([test "x$pipenv_cmd" = "x" || \95+ ! bmsg="`cd ${srcdir}/docs; LC_ALL=$LANG "$pipenv_cmd" check`"],[96+ AC_MSG_ERROR([$bmsg])97 cat <<EOF98 *****************************************************************99-* Ruby dependencies for building jq documentation not found. *99+* Python dependencies for building jq documentation not found. *100 * You can still build, install and hack on jq, but the manpage *101 * will not be rebuilt and some of the tests will not run. *102 * See docs/README.md for how to install the docs dependencies. *103 *****************************************************************104 EOF105- jq_cv_ruby_deps=no105+ jq_cv_python_deps=no106 ])])107 108- if test "x$jq_cv_ruby_deps" != "xyes"; then108+ if test "x$jq_cv_python_deps" != "xyes"; then109 enable_docs=no110 fi111 ])112 172 unmodified linesmodified:Makefile.am+9 added-9 removed
134 unmodified lines135 ### Building the manpage136 137 man_MANS = jq.1138 if ENABLE_DOCS139-jq.1: $(srcdir)/docs/content/3.manual/manual.yml140- $(AM_V_GEN) ( cd ${abs_srcdir}/docs; '$(BUNDLER)' exec rake manpage ) > $@ || { rm -f $@; false; }139+jq.1: $(srcdir)/docs/content/manual/manual.yml140+ $(AM_V_GEN) ( cd ${abs_srcdir}/docs; pipenv run python build_manpage.py ) > $@ || { rm -f $@; false; }141 jq.1.prebuilt: jq.1142 $(AM_V_GEN) cp jq.1 $@ || { rm -f $@; false; }143 else144 jq.1: $(srcdir)/jq.1.prebuilt19 unmodified lines164 install-binaries: $(BUILT_SOURCES)165 $(MAKE) $(AM_MAKEFLAGS) install-exec166 167 DOC_FILES = docs/content docs/public docs/templates docs/site.yml \168- docs/Gemfile docs/Gemfile.lock docs/Rakefile docs/README.md \169- jq.1.prebuilt168+ docs/Pipfile docs/Pipfile.lock docs/build_website.py \169+ docs/README.md jq.1.prebuilt170 171 EXTRA_DIST = $(DOC_FILES) $(man_MANS) $(TESTS) $(TEST_LOG_COMPILER) \172 jq.1.prebuilt jq.spec src/lexer.c src/lexer.h src/parser.c \173 src/parser.h src/version.h src/builtin.jq \5 unmodified lines179 tests/modules/test_bind_order.jq \180 tests/modules/test_bind_order0.jq \181 tests/modules/test_bind_order1.jq \182 tests/modules/test_bind_order2.jq tests/onig.supp \183- tests/onig.test tests/setup tests/torture/input0.json \184- tests/optional.test tests/optionaltest \185- tests/utf8-truncate.jq tests/utf8test \186- tests/base64.test tests/base64test \187- tests/jq-f-test.sh tests/shtest183+ tests/onig.test tests/setup tests/torture/input0.json \184+ tests/optional.test tests/optionaltest \185+ tests/utf8-truncate.jq tests/utf8test \186+ tests/base64.test tests/base64test \187+ tests/jq-f-test.sh tests/shtest188 189 190 191 # README.md is expected in Github projects, good stuff in it, so we'll31 unmodified lines