Skip to content
Myr

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

38 files+13626 added−13301 removed

deleted:docs/content/1.tutorial/default.yml-327 removed
1headline: Tutorial2body:3 - text: |45 GitHub has a JSON API, so let's play with that. This URL gets us the last6 5 commits from the jq repo.78 - 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 ...3839 - text: |4041 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.4546 - 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 ...7677 - text: |7879 We can use jq to extract just the first commit.8081 - 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 }158159 - text: |160161 For the rest of the examples, I'll leave out the `curl` command - it's not162 going to change.163164 There's a lot of info we don't care about there, so we'll restrict it down165 to the most interesting fields.166167 - 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 }173174 - text: |175176 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`.180181 Now let's get the rest of the commits.182183 - 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 }205206 - text: |207208 `.[]` 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}`.211212 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.215216 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.219220 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:223224 - 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 ]248249 - text: |250251 - - -252253 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.256257 "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 ]269270 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.273274 - 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 ]314315 - text: |316317 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.320321 - text: |322323 - - -324325 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
1headline: Download jq2body:34 - text: |56 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.910 The binaries should just run, but on OS X and Linux you may need11 to make them executable first using `chmod +x jq`.1213 jq is licensed under the MIT license. For all of the gory14 details, read the file `COPYING` in the source distribution.151617 ### Linux1819 * 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`.2223 * jq 1.5 is in the official24 [Fedora](http://pkgs.fedoraproject.org/cgit/jq.git/) repository.25 Install using `sudo dnf install jq`.2627 * jq 1.4 is in the official [openSUSE](https://software.opensuse.org/package/jq)28 repository. Install using `sudo zypper install jq`.2930 * 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`.3334 * 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).3839 * 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).4344 * 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).4849 * 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).5354 ### OS X5556 * Use [Homebrew](http://brew.sh/) to install jq 1.5 with57 `brew install jq`.5859 * jq 1.6 binary for60 [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-osx-amd64).6162 * jq 1.5 binary for63 [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-osx-amd64).6465 * 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).6970 * 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).7475 ### FreeBSD7677 * `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).7980 * `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.8485 ### Solaris8687 * `pkgutil -i jq` in [OpenCSW](https://www.opencsw.org/p/jq) for Solaris88 10+, Sparc and x86.8990 * 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).9495 ### Windows9697 * Use [Chocolatey NuGet](https://chocolatey.org/) to install jq 1.5 with98 `chocolatey install jq`.99100 * 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).104105 * 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).109110 * 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).114115 * 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).119120 ### Checksums and signatures121122 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).129130 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`.140141 ### From source on Linux, OS X, Cygwin, and other POSIX-like operating systems142143 * [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)145146 You can build it using the usual `./configure && make && sudo147 make install` rigmarole.148149 If you're interested in using the lastest development version, try:150151 git clone https://github.com/stedolan/jq.git152 cd jq153 autoreconf -i154 ./configure --disable-maintainer-mode155 make156 sudo make install157158 To build it from a git clone, you'll need to install a few159 packages first:160161 * [GCC](https://gcc.gnu.org)162 * [Make](https://www.gnu.org/software/make/)163 * [Autotools](https://www.gnu.org/software/automake/)164165 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.168169 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/).174175 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/).180181 #### Building the documentation182183 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`.189190 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---2headline: jq 1.3 Manual34history: |56 *The manual for the development version of jq can be found7 [here](/jq/manual).*89body: |1011 A jq program is a "filter": it takes an input, and produces an12 output. There are a lot of builtin filters for extracting a13 particular field of an object, or converting a number to a string,14 or various other standard tasks.1516 Filters can be combined in various ways - you can pipe the output of17 one filter into another filter, or collect the output of a filter18 into an array.1920 Some filters produce multiple results, for instance there's one that21 produces all the elements of its input array. Piping that filter22 into a second runs the second filter for each element of the23 array. Generally, things that would be done with loops and iteration24 in other languages are just done by gluing filters together in jq.2526 It's important to remember that every filter has an input and an27 output. Even literals like "hello" or 42 are filters - they take an28 input but always produce the same literal as output. Operations that29 combine two filters, like addition, generally feed the same input to30 both and combine the results. So, you can implement an averaging31 filter as `add / length` - feeding the input array both to the `add`32 filter and the `length` filter and dividing the results.3334 But that's getting ahead of ourselves. :) Let's start with something35 simpler:3637manpage_intro: |38 jq(1) -- Command-line JSON processor39 ====================================4041 ## SYNOPSIS4243 `jq` [<options>...] <filter> [<files>...]4445 `jq` can transform JSON in various ways, by selecting, iterating,46 reducing and otherwise mangling JSON documents. For instance,47 running the command `jq 'map(.price) | add'` will take an array of48 JSON objects as input and return the sum of their "price" fields.4950 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.5354 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.5859 ## FILTERS6061manpage_epilogue: |62 ## BUGS6364 Presumably. Report them or discuss them at:6566 https://github.com/stedolan/jq/issues6768 ## AUTHOR6970 Stephen Dolan `<mu@netsoc.tcd.ie>`7172sections:73 - title: Invoking jq74 body: |7576 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.8182 You can affect how jq reads and writes its input and output83 using some command-line options:8485 * `--slurp`/`-s`:8687 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.9091 * `--raw-input`/`-R`:9293 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.9798 * `--null-input`/`-n`:99100 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.103104 * `--compact-output` / `-c`:105106 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.109110 * `--color-output` / `-C` and `--monochrome-output` / `-M`:111112 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`.115116 * `--ascii-output` / `-a`:117118 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.123124 * `--raw-output` / `-r`:125126 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.130131 * `--arg name value`:132133 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"`.136137 - title: Basic filters138 entries:139 - title: "`.`"140 body: |141142 The absolute simplest (and least interesting) filter143 is `.`. This is a filter that takes its input and144 produces it unchanged as output.145146 Since jq by default pretty-prints all output, this trivial147 program can be a useful way of formatting JSON output from,148 say, `curl`.149150 examples:151 - program: '.'152 input: '"Hello, world!"'153 output: ['"Hello, world!"']154155 - title: "`.foo`"156 body: |157158 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.161162 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']169170 - title: "`.[foo]`, `.[2]`, `.[10:15]`"171 body: |172173 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.178179 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).185186 examples:187 - program: '.[0]'188 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'189 output: ['{"name":"JSON", "good":true}']190191 - program: '.[2]'192 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'193 output: ['null']194195 - program: '.[2:4]'196 input: '["a","b","c","d","e"]'197 output: ['["c", "d"]']198199 - program: '.[:3]'200 input: '["a","b","c","d","e"]'201 output: ['["a", "b", "c"]']202203 - program: '.[-2:]'204 input: '["a","b","c","d","e"]'205 output: ['["d", "e"]']206207 - title: "`.[]`"208 body: |209210 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.215216 You can also use this on an object, and it will return all217 the values of the object.218219 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}'225226 - program: '.[]'227 input: '[]'228 output: []229230 - program: '.[]'231 input: '{"a": 1, "b": 1}'232 output: ['1', '1']233234 - title: "`,`"235 body: |236237 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.243244 examples:245 - program: '.foo, .bar'246 input: '{"foo": 42, "bar": "something else", "baz": true}'247 output: ['42', '"something else"']248249 - program: ".user, .projects[]"250 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'251 output: ['"stedolan"', '"jq"', '"wikiflow"']252253 - program: '.[4,2]'254 input: '["a","b","c","d","e"]'255 output: ['"e"', '"c"']256257 - 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.263264 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.268269 examples:270 - program: '.[] | .name'271 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'272 output: ['"JSON"', '"XML"']273274 - title: Types and Values275 body: |276277 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".280281 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.286287 entries:288 - title: Array construction - `[]`289 body: |290291 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]`)298299 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).304305 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.308309 examples:310 - program: "[.user, .projects[]]"311 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'312 output: ['["stedolan", "jq", "wikiflow"]']313 - title: Objects - `{}`314 body: |315316 Like JSON, `{}` is for constructing objects (aka317 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.318319 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).325326 {foo: .bar}327328 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 write333334 {user: .user, title: .title}335336 Because that's so common, there's a shortcut syntax: `{user, title}`.337338 If one of the expressions produces multiple results,339 multiple dictionaries will be produced. If the input's340341 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}342343 then the expression344345 {user, title: .titles[]}346347 will produce two outputs:348349 {"user":"stedolan", "title": "JQ Primer"}350 {"user":"stedolan", "title": "More JQ"}351352 Putting parentheses around the key means it will be evaluated as an353 expression. With the same input as above,354355 {(.user): .titles}356357 produces358359 {"stedolan": ["JQ Primer", "More JQ"]}360361 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"]}']370371 - title: Builtin operators and functions372 body: |373374 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.379380 entries:381 - title: Addition - `+`382 body: |383384 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:387388 - **Numbers** are added by normal arithmetic.389390 - **Arrays** are added by being concatenated into a larger array.391392 - **Strings** are added by being joined into a larger string.393394 - **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.398399 `null` can be added to any value, and returns the other400 value unchanged.401402 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}']418419 - title: Subtraction - `-`420 body: |421422 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.425426 examples:427 - program: '4 - .a'428 input: '{"a":3}'429 output: ['1']430 - program: . - ["xml", "yaml"]431 input: '["xml", "yaml", "json"]'432 output: ['["json"]']433434 - title: Multiplication, division - `*` and `/`435 body: |436437 These operators only work on numbers, and do the expected.438439 examples:440 - program: '10 / . * 3'441 input: 5442 output: [6]443444 - title: `length`445 body: |446447 The builtin function `length` gets the length of various448 different types of value:449450 - 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).453454 - The length of an **array** is the number of elements.455456 - The length of an **object** is the number of key-value pairs.457458 - The length of **null** is zero.459460 examples:461 - program: '.[] | length'462 input: '[[1,2], "string", {"a":2}, null]'463 output: [2, 6, 1, 0]464465 - title: `keys`466 body: |467468 The builtin function `keys`, when given an object, returns469 its keys in an array.470471 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.476477 When `keys` is given an array, it returns the valid indices478 for that array: the integers from 0 to length-1.479480 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]']487488 - title: `has`489 body: |490491 The builtin function `has` returns whether the input object492 has the given key, or the input array has an element at the493 given index.494495 `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.498499 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]']506507 - title: `to_entries`, `from_entries`, `with_entries`508 body: |509510 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}`.514515 `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.519520 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}']530531532 - title: `select`533 body: |534535 The function `select(foo)` produces its input unchanged if536 `foo` returns true for that input, and produces no output537 otherwise.538539 It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`540 will give you `[3]`.541542 examples:543 - program: 'map(select(. >= 2))'544 input: '[1,5,3,0,7]'545 output: ['[5,3,7]']546547 - title: `empty`548 body: |549550 `empty` returns no results. None at all. Not even `null`.551552 It's useful on occasion. You'll know if you need it :)553554 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]']561562 - title: `map(x)`563 body: |564565 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.568569 `map(x)` is equivalent to `[.[] | x]`. In fact, this is how570 it's defined.571572 examples:573 - program: 'map(.+1)'574 input: '[1,2,3]'575 output: ['[2,3,4]']576577 - title: `add`578 body: |579580 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).585586 If the input is an empty array, `add` returns `null`.587588 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"]598599 - title: `range`600 body: |601602 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.606607 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]']614615 - title: `tonumber`616 body: |617618 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.621622 examples:623 - program: '.[] | tonumber'624 input: '[1, "1"]'625 output: [1, 1]626627 - title: `tostring`628 body: |629630 The `tostring` function prints its input as a631 string. Strings are left unchanged, and all other values are632 JSON-encoded.633634 examples:635 - program: '.[] | tostring'636 input: '[1, "1", [1]]'637 output: ['"1"', '"1"', '"[1]"']638639 - title: `type`640 body: |641642 The `type` function returns the type of its argument as a643 string, which is one of null, boolean, number, string, array644 or object.645646 examples:647 - program: 'map(type)'648 input: '[0, false, [], {}, null, "hello"]'649 output: ['["number", "boolean", "array", "object", "null", "string"]']650651 - title: `sort, sort_by`652 body: |653654 The `sort` functions sorts its input, which must be an655 array. Values are sorted in the following order:656657 * `null`658 * `false`659 * `true`660 * numbers661 * strings, in alphabetical order (by unicode codepoint value)662 * arrays, in lexical order663 * objects664665 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.669670 `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.674675 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}]']682683 - title: `group_by`684 body: |685686 `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.690691 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.694695 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}]]']699700 - title: `min`, `max`, `min_by`, `max_by`701 body: |702703 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.707708 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}']715716 - title: `unique`717 body: |718719 The `unique` function takes as input an array and produces720 an array of the same elements, in sorted order, with721 duplicates removed.722723 examples:724 - program: 'unique'725 input: '[1,2,5,3,5,3,1,3]'726 output: ['[1,2,3,5]']727728 - title: `reverse`729 body: |730731 This function reverses an array.732733 examples:734 - program: 'reverse'735 input: '[1,2,3,4]'736 output: ['[4,3,2,1]']737738 - title: `contains`739 body: |740741 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.749750 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']766767 - title: `recurse`768 body: |769770 The `recurse` function allows you to search through a771 recursive structure, and extract interesting data from all772 levels. Suppose your input represents a filesystem:773774 {"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": []}]}]}]}781782 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:786787 recurse(.children[]) | .name788789 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":[]}'797798799 - title: "String interpolation - `\(foo)`"800 body: |801802 Inside a string, you can put an expression inside parens803 after a backslash. Whatever the expression returns will be804 interpolated into the string.805806 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"']810811 - title: "Format strings and escaping"812 body: |813814 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:818819 * `@text`:820821 Calls `tostring`, see that function for details.822823 * `@json`:824825 Serialises the input as JSON.826827 * `@html`:828829 Applies HTML/XML escaping, by mapping the characters830 `<>&'"` to their entity equivalents `&lt;`, `&gt;`,831 `&amp;`, `&apos;`, `&quot;`.832833 * `@uri`:834835 Applies percent-encoding, by mapping all reserved URI836 characters to a `%xx` sequence.837838 * `@csv`:839840 The input must be an array, and it is rendered as CSV841 with double quotes for strings, and quotes escaped by842 repetition.843844 * `@sh`:845846 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.849850 * `@base64`:851852 The input is converted to base64 as specified by RFC 4648.853854 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,859860 @uri "https://www.google.com/search?q=\(.search)"861862 will produce the following output for the input863 `{"search":"jq!"}`:864865 https://www.google.com/search?q=jq%21866867 Note that the slashes, question mark, etc. in the URL are868 not escaped, as they were part of the string literal.869870 examples:871 - program: '@html'872 input: '"This works if x < y"'873 output: ['"This works if x &lt; y"']874875# - program: '@html "<span>Anonymous said: \(.)</span>"'876# input: '"<script>alert(\"lol hax\");</script>"'877# output: ["<span>Anonymous said: &lt;script&gt;alert(&quot;lol hax&quot;);&lt;/script&gt;</span>"]878879 - program: '@sh "echo \(.)"'880 input: "\"O'Hara's Ale\""881 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]882883 - title: Conditionals and Comparisons884 entries:885 - title: `==`, `!=`886 body: |887888 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.894895 != is "not equal", and 'a != b' returns the opposite value of 'a == b'896897 examples:898 - program: '.[] == 1'899 input: '[1, 1.0, "1", "banana"]'900 output: ['true', 'true', 'false', 'false']901 - title: if-then-else902 body: |903904 `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.907908 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.915916 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.919920 More cases can be added to an if using `elif A then B` syntax.921922 examples:923 - program: |-924 if . == 0 then925 "zero"926 elif . == 1 then927 "one"928 else929 "many"930 end931 input: 2932 output: ['"many"']933934 - title: `>, >=, <=, <`935 body: |936937 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).941942 The ordering is the same as that described for `sort`, above.943944 examples:945 - program: '. < 5'946 input: 2947 output: ['true']948949 - title: and/or/not950 body: |951952 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".955956 If an operand of one of these operators produces multiple957 results, the operator itself will produce a result for each input.958959 `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`.963964 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.970971 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]']987988 - title: Alternative operator - `//`989 body: |990991 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`.994995 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).10001001 examples:1002 - program: '.foo // 42'1003 input: '{"foo": 19}'1004 output: [19]1005 - program: '.foo // 42'1006 input: '{}'1007 output: [42]10081009 - title: Advanced features1010 body: |1011 Variables are an absolute necessity in most programming languages, but1012 they're relegated to an "advanced feature" in jq.10131014 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.10201021 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).10251026 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.10291030 entries:1031 - title: Variables1032 body: |10331034 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.10401041 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.10471048 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:10531054 length as $array_length | add / $array_length10551056 We'll need a more complicated problem to find a situation where using1057 variables actually makes our lives easier.105810591060 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:10631064 {"posts": [{"title": "Frist psot", "author": "anon"},1065 {"title": "A well-written article", "author": "person1"}],1066 "realnames": {"anon": "Anonymous Coward",1067 "person1": "Person McPherson"}}10681069 We want to produce the posts with the author field containing a real1070 name, as in:10711072 {"title": "Frist psot", "author": "Anonymous Coward"}1073 {"title": "A well-written article", "author": "Person McPherson"}10741075 We use a variable, $names, to store the realnames object, so that we1076 can refer to it later when looking up author usernames:10771078 .realnames as $names | .posts[] | {title, author: $names[.author]}10791080 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.10841085 Variables are scoped over the rest of the expression that defines1086 them, so10871088 .realnames as $names | (.posts[] | {title, author: $names[.author]})10891090 will work, but10911092 (.realnames as $names | .posts[]) | {title, author: $names[.author]}10931094 won't.10951096 examples:1097 - program: '.bar as $x | .foo | . + $x'1098 input: '{"foo":10, "bar":200}'1099 output: ['210']11001101 - title: 'Defining Functions'1102 body: |11031104 You can give a filter a name using "def" syntax:11051106 def increment: . + 1;11071108 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:11111112 def map(f): [.[] | f];11131114 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.11191120 If you want the value-argument behaviour for defining simple1121 functions, you can just use a variable:11221123 def addvalue(f): f as $value | map(. + $value);11241125 With that definition, `addvalue(.foo)` will add the current1126 input's `.foo` field to each element of the array.11271128 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]]']11351136 - title: Reduce1137 body: |11381139 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:11421143 reduce .[] as $item (0; . + $item)11441145 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:11491150 0 | (3 as $item | . + $item) |1151 (2 as $item | . + $item) |1152 (1 as $item | . + $item)11531154 examples:1155 - program: 'reduce .[] as $item (0; . + $item)'1156 input: '[10,2,5,3]'1157 output: ['20']115811591160 - title: Assignment1161 body: |11621163 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".11681169 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).11761177 entries:1178 - title: "`=`"1179 body: |11801181 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,11851186 .foo = .bar | .foo.baz = 111871188 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.11961197 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.12011202 - 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.12091210 This example should show the difference between '=' and '|=':12111212 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:12131214 .a = .b1215 .a |= .b12161217 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}.12201221 - title: "`+=`, `-=`, `*=`, `/=`, `//=`"1222 body: |12231224 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.12261227 examples:1228 - program: .foo += 11229 input: '{"foo": 42}'1230 output: ['{"foo": 43}']12311232 - 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:12381239 .posts[0].title = "JQ Manual"12401241 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:12441245 .posts[].comments |= . + ["this is great"]12461247 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).12501251 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.12571258 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:12621263 .posts[] | select(.author == "stedolan")12641265 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:12681269 (.posts[] | select(.author == "stedolan") | .comments) |=1270 . + ["terrible."]
deleted:docs/content/3.manual/v1.4/manual.yml-1672 removed
1---2headline: jq 1.4 Manual34history: |56 *The manual for the development version of jq can be found7 [here](/jq/manual).*89body: |1011 A jq program is a "filter": it takes an input, and produces an12 output. There are a lot of builtin filters for extracting a13 particular field of an object, or converting a number to a string,14 or various other standard tasks.1516 Filters can be combined in various ways - you can pipe the output of17 one filter into another filter, or collect the output of a filter18 into an array.1920 Some filters produce multiple results, for instance there's one that21 produces all the elements of its input array. Piping that filter22 into a second runs the second filter for each element of the23 array. Generally, things that would be done with loops and iteration24 in other languages are just done by gluing filters together in jq.2526 It's important to remember that every filter has an input and an27 output. Even literals like "hello" or 42 are filters - they take an28 input but always produce the same literal as output. Operations that29 combine two filters, like addition, generally feed the same input to30 both and combine the results. So, you can implement an averaging31 filter as `add / length` - feeding the input array both to the `add`32 filter and the `length` filter and dividing the results.3334 But that's getting ahead of ourselves. :) Let's start with something35 simpler:3637manpage_intro: |38 jq(1) -- Command-line JSON processor39 ====================================4041 ## SYNOPSIS4243 `jq` [<options>...] <filter> [<files>...]4445 `jq` can transform JSON in various ways, by selecting, iterating,46 reducing and otherwise mangling JSON documents. For instance,47 running the command `jq 'map(.price) | add'` will take an array of48 JSON objects as input and return the sum of their "price" fields.4950 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.5354 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.5859 ## FILTERS6061manpage_epilogue: |62 ## BUGS6364 Presumably. Report them or discuss them at:6566 https://github.com/stedolan/jq/issues6768 ## AUTHOR6970 Stephen Dolan `<mu@netsoc.tcd.ie>`7172sections:73 - title: Invoking jq74 body: |7576 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.8182 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.9293 You can affect how jq reads and writes its input and output94 using some command-line options:9596 * `--version`:9798 Output the jq version and exit with zero.99100 * `--slurp`/`-s`:101102 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.105106 * `--online-input`/`-I`:107108 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.111112 * `--raw-input`/`-R`:113114 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.118119 * `--null-input`/`-n`:120121 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.124125 * `--compact-output` / `-c`:126127 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.130131 * `--color-output` / `-C` and `--monochrome-output` / `-M`:132133 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`.136137 * `--ascii-output` / `-a`:138139 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.144145 * `--unbuffered`146147 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).150151 * `--sort-keys` / `-S`:152153 Output the fields of each object with the keys in sorted order.154155 * `--raw-output` / `-r`:156157 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.161162 * `-f filename` / `--from-file filename`:163164 Read filter from the file rather than from a command line, like165 awk's -f option. You can also use '#' to make comments.166167 * `-e` / `--exit-status`:168169 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.175176 * `--arg name value`:177178 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"`.181182 * `--argfile name filename`:183184 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`.189190 - title: Basic filters191 entries:192 - title: "`.`"193 body: |194195 The absolute simplest (and least interesting) filter196 is `.`. This is a filter that takes its input and197 produces it unchanged as output.198199 Since jq by default pretty-prints all output, this trivial200 program can be a useful way of formatting JSON output from,201 say, `curl`.202203 examples:204 - program: '.'205 input: '"Hello, world!"'206 output: ['"Hello, world!"']207208 - title: "`.foo`, `.foo.bar`"209 body: |210211 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.214215 If the key contains special characters, you need to surround216 it with double quotes like this: `."foo$"`.217218 A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.219220 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]230231 - title: "`.foo?`"232 body: |233234 Just like `.foo`, but does not output even an error when `.`235 is not an array or an object.236237 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: ['[]']250251 - title: "`.[<string>]`, `.[2]`, `.[10:15]`"252 body: |253254 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.259260 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).267268 The `?` "operator" can also be used with the slice operator,269 as in `.[10:15]?`, which outputs values where the inputs are270 slice-able.271272 examples:273 - program: '.[0]'274 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'275 output: ['{"name":"JSON", "good":true}']276277 - program: '.[2]'278 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'279 output: ['null']280281 - program: '.[2:4]'282 input: '["a","b","c","d","e"]'283 output: ['["c", "d"]']284285 - program: '.[2:4]'286 input: '"abcdefghi"'287 output: ['"cd"']288289 - program: '.[:3]'290 input: '["a","b","c","d","e"]'291 output: ['["a", "b", "c"]']292293 - program: '.[-2:]'294 input: '["a","b","c","d","e"]'295 output: ['["d", "e"]']296297 - title: "`.[]`"298 body: |299300 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.305306 You can also use this on an object, and it will return all307 the values of the object.308309 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}'315316 - program: '.[]'317 input: '[]'318 output: []319320 - program: '.[]'321 input: '{"a": 1, "b": 1}'322 output: ['1', '1']323324 - title: "`.[]?`"325 body: |326327 Like `.[]`, but no errors will be output if . is not an array328 or object.329330 - title: "`,`"331 body: |332333 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.339340 examples:341 - program: '.foo, .bar'342 input: '{"foo": 42, "bar": "something else", "baz": true}'343 output: ['42', '"something else"']344345 - program: ".user, .projects[]"346 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'347 output: ['"stedolan"', '"jq"', '"wikiflow"']348349 - program: '.[4,2]'350 input: '["a","b","c","d","e"]'351 output: ['"e"', '"c"']352353 - 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.359360 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.364365 examples:366 - program: '.[] | .name'367 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'368 output: ['"JSON"', '"XML"']369370 - title: Types and Values371 body: |372373 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".376377 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.382383 entries:384 - title: Array construction - `[]`385 body: |386387 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]`)394395 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).400401 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.404405 examples:406 - program: "[.user, .projects[]]"407 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'408 output: ['["stedolan", "jq", "wikiflow"]']409 - title: Objects - `{}`410 body: |411412 Like JSON, `{}` is for constructing objects (aka413 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.414415 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).421422 {foo: .bar}423424 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 write429430 {user: .user, title: .title}431432 Because that's so common, there's a shortcut syntax: `{user, title}`.433434 If one of the expressions produces multiple results,435 multiple dictionaries will be produced. If the input's436437 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}438439 then the expression440441 {user, title: .titles[]}442443 will produce two outputs:444445 {"user":"stedolan", "title": "JQ Primer"}446 {"user":"stedolan", "title": "More JQ"}447448 Putting parentheses around the key means it will be evaluated as an449 expression. With the same input as above,450451 {(.user): .titles}452453 produces454455 {"stedolan": ["JQ Primer", "More JQ"]}456457 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"]}']466467 - title: Builtin operators and functions468 body: |469470 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.475476 entries:477 - title: Addition - `+`478 body: |479480 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:483484 - **Numbers** are added by normal arithmetic.485486 - **Arrays** are added by being concatenated into a larger array.487488 - **Strings** are added by being joined into a larger string.489490 - **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.)495496 `null` can be added to any value, and returns the other497 value unchanged.498499 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}']515516 - title: Subtraction - `-`517 body: |518519 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.522523 examples:524 - program: '4 - .a'525 input: '{"a":3}'526 output: ['1']527 - program: . - ["xml", "yaml"]528 input: '["xml", "yaml", "json"]'529 output: ['["json"]']530531 - title: Multiplication, division, modulo - `*`, `/`, and `%`532 body: |533534 These operators only work on numbers, and do the expected.535536 Multiplying a string by a number produces the concatenation of537 that string that many times.538539 Dividing a string by another splits the first using the second540 as separators.541542 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.546547 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}}']557558 - title: "`length`"559 body: |560561 The builtin function `length` gets the length of various562 different types of value:563564 - 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).567568 - The length of an **array** is the number of elements.569570 - The length of an **object** is the number of key-value pairs.571572 - The length of **null** is zero.573574 examples:575 - program: '.[] | length'576 input: '[[1,2], "string", {"a":2}, null]'577 output: [2, 6, 1, 0]578579 - title: "`keys`"580 body: |581582 The builtin function `keys`, when given an object, returns583 its keys in an array.584585 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.590591 When `keys` is given an array, it returns the valid indices592 for that array: the integers from 0 to length-1.593594 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]']601602 - title: "`has`"603 body: |604605 The builtin function `has` returns whether the input object606 has the given key, or the input array has an element at the607 given index.608609 `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.612613 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]']620621 - title: "`del`"622 body: |623624 The builtin function `del` removes a key and its corresponding625 value from an object.626627 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"]']634635 - title: "`to_entries`, `from_entries`, `with_entries`"636 body: |637638 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}`.642643 `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.647648 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}']658659660 - title: "`select`"661 body: |662663 The function `select(foo)` produces its input unchanged if664 `foo` returns true for that input, and produces no output665 otherwise.666667 It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`668 will give you `[2,3]`.669670 examples:671 - program: 'map(select(. >= 2))'672 input: '[1,5,3,0,7]'673 output: ['[5,3,7]']674675676 - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `strings`, `nulls`, `values`, `scalars`"677 body: |678679 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.682683 examples:684 - program: '.[]|numbers'685 input: '[[],{},1,"foo",null,true,false]'686 output: ['1']687688 - title: "`empty`"689 body: |690691 `empty` returns no results. None at all. Not even `null`.692693 It's useful on occasion. You'll know if you need it :)694695 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]']702703 - title: "`map(x)`"704 body: |705706 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.709710 `map(x)` is equivalent to `[.[] | x]`. In fact, this is how711 it's defined.712713 examples:714 - program: 'map(.+1)'715 input: '[1,2,3]'716 output: ['[2,3,4]']717718 - title: "`paths`"719 body: |720721 Outputs the paths to all the elements in its input (except it722 does not output the empty list, representing . itself).723724 `paths` is equivalent to725726 def paths: path(recurse(if (type|. == "array" or . == "object") then .[] else empty end))|select(length > 0);727728 examples:729 - program: '[paths]'730 input: '[1,[[],{"a":2}]]'731 output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']732733 - title: "`leaf_paths`"734 body: |735736 Outputs the paths to all the leaves (non-array, non-object737 elements) in its input.738739 examples:740 - program: '[leaf_paths]'741 input: '[1,[[],{"a":2}]]'742 output: ['[[0],[1,1,"a"]]']743744 - title: "`add`"745 body: |746747 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).752753 If the input is an empty array, `add` returns `null`.754755 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"]765766 - title: "`any`"767 body: |768769 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`.772773 If the input is an empty array, `any` returns `false`.774775 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"]785786 - title: "`all`"787 body: |788789 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`.792793 If the input is an empty array, `all` returns `true`.794795 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"]805806 - title: "`range`"807 body: |808809 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.813814 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]']821822 - title: "`floor`"823 body: |824825 The `floor` function returns the floor of its numeric input.826827 examples:828 - program: 'floor'829 input: '3.14159'830 output: ['3']831832 - title: "`sqrt`"833 body: |834835 The `sqrt` function returns the square root of its numeric input.836837 examples:838 - program: 'sqrt'839 input: '9'840 output: ['3']841842 - title: "`tonumber`"843 body: |844845 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.848849 examples:850 - program: '.[] | tonumber'851 input: '[1, "1"]'852 output: [1, 1]853854 - title: "`tostring`"855 body: |856857 The `tostring` function prints its input as a858 string. Strings are left unchanged, and all other values are859 JSON-encoded.860861 examples:862 - program: '.[] | tostring'863 input: '[1, "1", [1]]'864 output: ['"1"', '"1"', '"[1]"']865866 - title: "`type`"867 body: |868869 The `type` function returns the type of its argument as a870 string, which is one of null, boolean, number, string, array871 or object.872873 examples:874 - program: 'map(type)'875 input: '[0, false, [], {}, null, "hello"]'876 output: ['["number", "boolean", "array", "object", "null", "string"]']877878 - title: "`sort, sort_by`"879 body: |880881 The `sort` functions sorts its input, which must be an882 array. Values are sorted in the following order:883884 * `null`885 * `false`886 * `true`887 * numbers888 * strings, in alphabetical order (by unicode codepoint value)889 * arrays, in lexical order890 * objects891892 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.896897 `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.901902 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}]']909910 - title: "`group_by`"911 body: |912913 `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.917918 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.921922 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}]]']926927 - title: "`min`, `max`, `min_by`, `max_by`"928 body: |929930 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.934935 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}']942943 - title: "`unique`"944 body: |945946 The `unique` function takes as input an array and produces947 an array of the same elements, in sorted order, with948 duplicates removed.949950 examples:951 - program: 'unique'952 input: '[1,2,5,3,5,3,1,3]'953 output: ['[1,2,3,5]']954955 - title: "`unique_by`"956 body: |957958 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`.963964 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"]']971972973 - title: "`reverse`"974 body: |975976 This function reverses an array.977978 examples:979 - program: 'reverse'980 input: '[1,2,3,4]'981 output: ['[4,3,2,1]']982983 - title: "`contains`"984 body: |985986 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.994995 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']10111012 - title: "`indices(s)`"1013 body: |10141015 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`.10191020 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]']10301031 - title: "`index(s)`, `rindex(s)`"1032 body: |10331034 Outputs the index of the first (`index`) or last (`rindex`)1035 occurrence of `s` in the input.10361037 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']10441045 - title: "`startswith`"1046 body: |10471048 Outputs `true` if . starts with the given string argument.10491050 examples:1051 - program: '[.[]|startswith("foo")]'1052 input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1053 output: ['[false, true, false, true, false]']10541055 - title: "`endswith`"1056 body: |10571058 Outputs `true` if . ends with the given string argument.10591060 examples:1061 - program: '[.[]|endswith("foo")]'1062 input: '["foobar", "barfoo"]'1063 output: ['[false, true]']10641065 - title: "`ltrimstr`"1066 body: |10671068 Outputs its input with the given prefix string removed, if it1069 starts with it.10701071 examples:1072 - program: '[.[]|ltrimstr("foo")]'1073 input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1074 output: ['["fo","","barfoo","bar","afoo"]']10751076 - title: "`rtrimstr`"1077 body: |10781079 Outputs its input with the given suffix string removed, if it1080 starts with it.10811082 examples:1083 - program: '[.[]|rtrimstr("foo")]'1084 input: '["fo", "foo", "barfoo", "foobar", "foob"]'1085 output: ['["fo","","bar","foobar","foob"]']10861087 - title: "`explode`"1088 body: |10891090 Converts an input string into an array of the string's1091 codepoint numbers.10921093 examples:1094 - program: 'explode'1095 input: '"foobar"'1096 output: ['[102,111,111,98,97,114]']10971098 - title: "`implode`"1099 body: |11001101 The inverse of explode.11021103 examples:1104 - program: 'implode'1105 input: '[65, 66, 67]'1106 output: ['"ABC"']11071108 - title: "`split`"1109 body: |11101111 Splits an input string on the separator argument.11121113 examples:1114 - program: 'split(", ")'1115 input: '"a, b,c,d, e"'1116 output: ['["a","b,c,d","e"]']11171118 - title: "`join`"1119 body: |11201121 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.11251126 examples:1127 - program: 'join(", ")'1128 input: '["a","b,c,d","e"]'1129 output: ['"a, b,c,d, e"']113011311132 - title: "`recurse`"1133 body: |11341135 The `recurse` function allows you to search through a1136 recursive structure, and extract interesting data from all1137 levels. Suppose your input represents a filesystem:11381139 {"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": []}]}]}]}11461147 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:11511152 recurse(.children[]) | .name11531154 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":[]}'11621163 - title: "`recurse_down`"1164 body: |11651166 A quieter version of `recurse(.[])`, equivalent to:11671168 def recurse_down: recurse(.[]?);11691170 - title: "`..`"1171 body: |11721173 Short-hand for `recurse_down`. This is intended to resemble1174 the XPath `//` operator. Note that `..a` does not work; use1175 `..|a` instead.11761177 examples:1178 - program: '..|.a?'1179 input: '[[{"a":1}]]'1180 output: ['1']11811182 - title: "String interpolation - `\\(foo)`"1183 body: |11841185 Inside a string, you can put an expression inside parens1186 after a backslash. Whatever the expression returns will be1187 interpolated into the string.11881189 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"']11931194 - title: "Convert to/from JSON"1195 body: |11961197 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.12011202 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"]]']12121213 - title: "Format strings and escaping"1214 body: |12151216 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:12201221 * `@text`:12221223 Calls `tostring`, see that function for details.12241225 * `@json`:12261227 Serialises the input as JSON.12281229 * `@html`:12301231 Applies HTML/XML escaping, by mapping the characters1232 `<>&'"` to their entity equivalents `&lt;`, `&gt;`,1233 `&amp;`, `&apos;`, `&quot;`.12341235 * `@uri`:12361237 Applies percent-encoding, by mapping all reserved URI1238 characters to a `%xx` sequence.12391240 * `@csv`:12411242 The input must be an array, and it is rendered as CSV1243 with double quotes for strings, and quotes escaped by1244 repetition.12451246 * `@sh`:12471248 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.12511252 * `@base64`:12531254 The input is converted to base64 as specified by RFC 4648.12551256 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,12611262 @uri "https://www.google.com/search?q=\(.search)"12631264 will produce the following output for the input1265 `{"search":"what is jq?"}`:12661267 "https://www.google.com/search?q=what%20is%20jq%3f"12681269 Note that the slashes, question mark, etc. in the URL are1270 not escaped, as they were part of the string literal.12711272 examples:1273 - program: '@html'1274 input: '"This works if x < y"'1275 output: ['"This works if x &lt; y"']12761277# - program: '@html "<span>Anonymous said: \(.)</span>"'1278# input: '"<script>alert(\"lol hax\");</script>"'1279# output: ["<span>Anonymous said: &lt;script&gt;alert(&quot;lol hax&quot;);&lt;/script&gt;</span>"]12801281 - program: '@sh "echo \(.)"'1282 input: "\"O'Hara's Ale\""1283 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]12841285 - title: Conditionals and Comparisons1286 entries:1287 - title: "`==`, `!=`"1288 body: |12891290 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.12961297 != is "not equal", and 'a != b' returns the opposite value of 'a == b'12981299 examples:1300 - program: '.[] == 1'1301 input: '[1, 1.0, "1", "banana"]'1302 output: ['true', 'true', 'false', 'false']1303 - title: if-then-else1304 body: |13051306 `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.13091310 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.13171318 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.13211322 More cases can be added to an if using `elif A then B` syntax.13231324 examples:1325 - program: |-1326 if . == 0 then1327 "zero"1328 elif . == 1 then1329 "one"1330 else1331 "many"1332 end1333 input: 21334 output: ['"many"']13351336 - title: "`>, >=, <=, <`"1337 body: |13381339 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).13431344 The ordering is the same as that described for `sort`, above.13451346 examples:1347 - program: '. < 5'1348 input: 21349 output: ['true']13501351 - title: and/or/not1352 body: |13531354 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".13571358 If an operand of one of these operators produces multiple1359 results, the operator itself will produce a result for each input.13601361 `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`.13651366 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.13721373 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]']13891390 - title: Alternative operator - `//`1391 body: |13921393 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`.13961397 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).14021403 examples:1404 - program: '.foo // 42'1405 input: '{"foo": 19}'1406 output: [19]1407 - program: '.foo // 42'1408 input: '{}'1409 output: [42]14101411 - title: Advanced features1412 body: |1413 Variables are an absolute necessity in most programming languages, but1414 they're relegated to an "advanced feature" in jq.14151416 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.14221423 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).14271428 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.14311432 entries:1433 - title: Variables1434 body: |14351436 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.14421443 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.14491450 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:14551456 length as $array_length | add / $array_length14571458 We'll need a more complicated problem to find a situation where using1459 variables actually makes our lives easier.146014611462 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:14651466 {"posts": [{"title": "Frist psot", "author": "anon"},1467 {"title": "A well-written article", "author": "person1"}],1468 "realnames": {"anon": "Anonymous Coward",1469 "person1": "Person McPherson"}}14701471 We want to produce the posts with the author field containing a real1472 name, as in:14731474 {"title": "Frist psot", "author": "Anonymous Coward"}1475 {"title": "A well-written article", "author": "Person McPherson"}14761477 We use a variable, $names, to store the realnames object, so that we1478 can refer to it later when looking up author usernames:14791480 .realnames as $names | .posts[] | {title, author: $names[.author]}14811482 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.14861487 Variables are scoped over the rest of the expression that defines1488 them, so14891490 .realnames as $names | (.posts[] | {title, author: $names[.author]})14911492 will work, but14931494 (.realnames as $names | .posts[]) | {title, author: $names[.author]}14951496 won't.14971498 examples:1499 - program: '.bar as $x | .foo | . + $x'1500 input: '{"foo":10, "bar":200}'1501 output: ['210']15021503 - title: 'Defining Functions'1504 body: |15051506 You can give a filter a name using "def" syntax:15071508 def increment: . + 1;15091510 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:15131514 def map(f): [.[] | f];15151516 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.15211522 If you want the value-argument behaviour for defining simple1523 functions, you can just use a variable:15241525 def addvalue(f): f as $value | map(. + $value);15261527 With that definition, `addvalue(.foo)` will add the current1528 input's `.foo` field to each element of the array.15291530 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]]']15371538 - title: Reduce1539 body: |15401541 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:15441545 reduce .[] as $item (0; . + $item)15461547 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:15511552 0 | (3 as $item | . + $item) |1553 (2 as $item | . + $item) |1554 (1 as $item | . + $item)15551556 examples:1557 - program: 'reduce .[] as $item (0; . + $item)'1558 input: '[10,2,5,3]'1559 output: ['20']156015611562 - title: Assignment1563 body: |15641565 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".15701571 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).15781579 entries:1580 - title: "`=`"1581 body: |15821583 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,15871588 .foo = .bar | .foo.baz = 115891590 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.15981599 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.16031604 - 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.16111612 This example should show the difference between '=' and '|=':16131614 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:16151616 .a = .b1617 .a |= .b16181619 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}.16221623 - title: "`+=`, `-=`, `*=`, `/=`, `%=`, `//=`"1624 body: |16251626 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.16281629 examples:1630 - program: .foo += 11631 input: '{"foo": 42}'1632 output: ['{"foo": 43}']16331634 - 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:16401641 .posts[0].title = "JQ Manual"16421643 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:16461647 .posts[].comments |= . + ["this is great"]16481649 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).16521653 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.16591660 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:16641665 .posts[] | select(.author == "stedolan")16661667 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:16701671 (.posts[] | select(.author == "stedolan") | .comments) |=1672 . + ["terrible."]
deleted:docs/content/3.manual/v1.5/manual.yml-2878 removed
1---2headline: jq 1.5 Manual34history: |56 *The manual for the development version of jq can be found7 [here](/jq/manual).*89body: |1011 A jq program is a "filter": it takes an input, and produces an12 output. There are a lot of builtin filters for extracting a13 particular field of an object, or converting a number to a string,14 or various other standard tasks.1516 Filters can be combined in various ways - you can pipe the output of17 one filter into another filter, or collect the output of a filter18 into an array.1920 Some filters produce multiple results, for instance there's one that21 produces all the elements of its input array. Piping that filter22 into a second runs the second filter for each element of the23 array. Generally, things that would be done with loops and iteration24 in other languages are just done by gluing filters together in jq.2526 It's important to remember that every filter has an input and an27 output. Even literals like "hello" or 42 are filters - they take an28 input but always produce the same literal as output. Operations that29 combine two filters, like addition, generally feed the same input to30 both and combine the results. So, you can implement an averaging31 filter as `add / length` - feeding the input array both to the `add`32 filter and the `length` filter and then performing the division.3334 But that's getting ahead of ourselves. :) Let's start with something35 simpler:3637manpage_intro: |38 jq(1) -- Command-line JSON processor39 ====================================4041 ## SYNOPSIS4243 `jq` [<options>...] <filter> [<files>...]4445 `jq` can transform JSON in various ways, by selecting, iterating,46 reducing and otherwise mangling JSON documents. For instance,47 running the command `jq 'map(.price) | add'` will take an array of48 JSON objects as input and return the sum of their "price" fields.4950 `jq` can accept text input as well, but by default, `jq` reads a51 stream of JSON entities (including numbers and other literals) from52 `stdin`. Whitespace is only needed to separate entities such as 153 and 2, and true and false. One or more <files> may be specified, in54 which case `jq` will read input from those instead.5556 The <options> are described in the [INVOKING JQ] section; they57 mostly concern input and output formatting. The <filter> is written58 in the jq language and specifies how to transform the input59 file or document.6061 ## FILTERS6263manpage_epilogue: |64 ## BUGS6566 Presumably. Report them or discuss them at:6768 https://github.com/stedolan/jq/issues6970 ## AUTHOR7172 Stephen Dolan `<mu@netsoc.tcd.ie>`7374sections:75 - title: Invoking jq76 body: |7778 jq filters run on a stream of JSON data. The input to jq is79 parsed as a sequence of whitespace-separated JSON values which80 are passed through the provided filter one at a time. The81 output(s) of the filter are written to standard out, again as a82 sequence of whitespace-separated JSON data.8384 Note: it is important to mind the shell's quoting rules. As a85 general rule it's best to always quote (with single-quote86 characters) the jq program, as too many characters with special87 meaning to jq are also shell meta-characters. For example, `jq88 "foo"` will fail on most Unix shells because that will be the same89 as `jq foo`, which will generally fail because `foo is not90 defined`. When using the Windows command shell (cmd.exe) it's91 best to use double quotes around your jq program when given on the92 command-line (instead of the `-f program-file` option), but then93 double-quotes in the jq program need backslash escaping.9495 You can affect how jq reads and writes its input and output96 using some command-line options:9798 * `--version`:99100 Output the jq version and exit with zero.101102 * `--seq`:103104 Use the `application/json-seq` MIME type scheme for separating105 JSON texts in jq's input and output. This means that an ASCII106 RS (record separator) character is printed before each value on107 output and an ASCII LF (line feed) is printed after every108 output. Input JSON texts that fail to parse are ignored (but109 warned about), discarding all subsequent input until the next110 RS. This more also parses the output of jq without the `--seq`111 option.112113 * `--stream`:114115 Parse the input in streaming fashion, outputing arrays of path116 and leaf values (scalars and empty arrays or empty objects).117 For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]`118 becomes `[[0],[]]`, `[[1],"a"]`, and `[[1,0],"b"]`.119120 This is useful for processing very large inputs. Use this in121 conjunction with filtering and the `reduce` and `foreach` syntax122 to reduce large inputs incrementally.123124 * `--slurp`/`-s`:125126 Instead of running the filter for each JSON object in the127 input, read the entire input stream into a large array and run128 the filter just once.129130 * `--raw-input`/`-R`:131132 Don't parse the input as JSON. Instead, each line of text is133 passed to the filter as a string. If combined with `--slurp`,134 then the entire input is passed to the filter as a single long135 string.136137 * `--null-input`/`-n`:138139 Don't read any input at all! Instead, the filter is run once140 using `null` as the input. This is useful when using jq as a141 simple calculator or to construct JSON data from scratch.142143 * `--compact-output` / `-c`:144145 By default, jq pretty-prints JSON output. Using this option146 will result in more compact output by instead putting each147 JSON object on a single line.148149 * `--tab`:150151 Use a tab for each indentation level instead of two spaces.152153 * `--indent n`:154155 Use the given number of spaces (no more than 8) for indentation.156157 * `--color-output` / `-C` and `--monochrome-output` / `-M`:158159 By default, jq outputs colored JSON if writing to a160 terminal. You can force it to produce color even if writing to161 a pipe or a file using `-C`, and disable color with `-M`.162163 * `--ascii-output` / `-a`:164165 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.170171 * `--unbuffered`172173 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).176177 * `--sort-keys` / `-S`:178179 Output the fields of each object with the keys in sorted order.180181 * `--raw-output` / `-r`:182183 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.187188 * `--join-output` / `-j`:189190 Like `-r` but jq won't print a newline after each output.191192 * `-f filename` / `--from-file filename`:193194 Read filter from the file rather than from a command line, like195 awk's -f option. You can also use '#' to make comments.196197 * `-Ldirectory` / `-L directory`:198199 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.202203 * `-e` / `--exit-status`:204205 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.211212 * `--arg name value`:213214 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"`.219220 * `--argjson name JSON-text`:221222 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`.225226 * `--slurpfile variable-name filename`:227228 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`.233234 * `--argfile variable-name filename`:235236 Do not use. Use `--slurpfile` instead.237238 (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`.)241242 * `--run-tests [filename]`:243244 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.253254 Be warned that this option can change backwards-incompatibly.255256 - title: Basic filters257 entries:258 - title: "`.`"259 body: |260261 The absolute simplest (and least interesting) filter262 is `.`. This is a filter that takes its input and263 produces it unchanged as output.264265 Since jq by default pretty-prints all output, this trivial266 program can be a useful way of formatting JSON output from,267 say, `curl`.268269 examples:270 - program: '.'271 input: '"Hello, world!"'272 output: ['"Hello, world!"']273274 - title: "`.foo`, `.foo.bar`"275 body: |276277 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.280281 If the key contains special characters, you need to surround282 it with double quotes like this: `."foo$"`.283284 A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.285286 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]296297 - title: "`.foo?`"298 body: |299300 Just like `.foo`, but does not output even an error when `.`301 is not an array or an object.302303 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: ['[]']316317 - title: "`.[<string>]`, `.[2]`, `.[10:15]`"318 body: |319320 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.325326 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).333334 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.338339 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.344345 The `?` "operator" can also be used with the slice operator,346 as in `.[10:15]?`, which outputs values where the inputs are347 slice-able.348349 examples:350 - program: '.[0]'351 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'352 output: ['{"name":"JSON", "good":true}']353354 - program: '.[2]'355 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'356 output: ['null']357358 - program: '.[2:4]'359 input: '["a","b","c","d","e"]'360 output: ['["c", "d"]']361362 - program: '.[2:4]'363 input: '"abcdefghi"'364 output: ['"cd"']365366 - program: '.[:3]'367 input: '["a","b","c","d","e"]'368 output: ['["a", "b", "c"]']369370 - program: '.[-2:]'371 input: '["a","b","c","d","e"]'372 output: ['["d", "e"]']373374 - program: '.[-2]'375 input: '[1,2,3]'376 output: ['2']377378 - title: "`.[]`"379 body: |380381 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.386387 You can also use this on an object, and it will return all388 the values of the object.389390 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}'396397 - program: '.[]'398 input: '[]'399 output: []400401 - program: '.[]'402 input: '{"a": 1, "b": 1}'403 output: ['1', '1']404405 - title: "`.[]?`"406 body: |407408 Like `.[]`, but no errors will be output if . is not an array409 or object.410411 - title: "`,`"412 body: |413414 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.420421 examples:422 - program: '.foo, .bar'423 input: '{"foo": 42, "bar": "something else", "baz": true}'424 output: ['42', '"something else"']425426 - program: ".user, .projects[]"427 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'428 output: ['"stedolan"', '"jq"', '"wikiflow"']429430 - program: '.[4,2]'431 input: '["a","b","c","d","e"]'432 output: ['"e"', '"c"']433434 - 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.440441 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.445446 examples:447 - program: '.[] | .name'448 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'449 output: ['"JSON"', '"XML"']450451 - title: Types and Values452 body: |453454 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".457458 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.463464 entries:465 - title: Array construction - `[]`466 body: |467468 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]`)475476 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).481482 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.485486 examples:487 - program: "[.user, .projects[]]"488 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'489 output: ['["stedolan", "jq", "wikiflow"]']490 - title: Objects - `{}`491 body: |492493 Like JSON, `{}` is for constructing objects (aka494 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.495496 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).502503 {foo: .bar}504505 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 write510511 {user: .user, title: .title}512513 Because that's so common, there's a shortcut syntax: `{user, title}`.514515 If one of the expressions produces multiple results,516 multiple dictionaries will be produced. If the input's517518 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}519520 then the expression521522 {user, title: .titles[]}523524 will produce two outputs:525526 {"user":"stedolan", "title": "JQ Primer"}527 {"user":"stedolan", "title": "More JQ"}528529 Putting parentheses around the key means it will be evaluated as an530 expression. With the same input as above,531532 {(.user): .titles}533534 produces535536 {"stedolan": ["JQ Primer", "More JQ"]}537538 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"]}']547548 - title: Builtin operators and functions549 body: |550551 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.556557 entries:558 - title: Addition - `+`559 body: |560561 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:564565 - **Numbers** are added by normal arithmetic.566567 - **Arrays** are added by being concatenated into a larger array.568569 - **Strings** are added by being joined into a larger string.570571 - **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.)576577 `null` can be added to any value, and returns the other578 value unchanged.579580 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}']596597 - title: Subtraction - `-`598 body: |599600 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.603604 examples:605 - program: '4 - .a'606 input: '{"a":3}'607 output: ['1']608 - program: . - ["xml", "yaml"]609 input: '["xml", "yaml", "json"]'610 output: ['["json"]']611612 - title: Multiplication, division, modulo - `*`, `/`, and `%`613 body: |614615 These infix operators behave as expected when given two numbers.616 Division by zero raises an error. `x % y` computes x modulo y.617618 Multiplying a string by a number produces the concatenation of619 that string that many times. `"x" * 0` produces **null**.620621 Dividing a string by another splits the first using the second622 as separators.623624 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.628629 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']642643644 - title: "`length`"645 body: |646647 The builtin function `length` gets the length of various648 different types of value:649650 - 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).653654 - The length of an **array** is the number of elements.655656 - The length of an **object** is the number of key-value pairs.657658 - The length of **null** is zero.659660 examples:661 - program: '.[] | length'662 input: '[[1,2], "string", {"a":2}, null]'663 output: [2, 6, 1, 0]664665 - title: "`keys`, `keys_unsorted`"666 body: |667668 The builtin function `keys`, when given an object, returns669 its keys in an array.670671 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.676677 When `keys` is given an array, it returns the valid indices678 for that array: the integers from 0 to length-1.679680 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.683684 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]']691692 - title: "`has(key)`"693 body: |694695 The builtin function `has` returns whether the input object696 has the given key, or the input array has an element at the697 given index.698699 `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.702703 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]']710711 - title: "`in`"712 body: |713714 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`.718719 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]']726727 - title: "`path(path_expression)`"728 body: |729730 Outputs array representations of the given path expression731 in `.`. The outputs are arrays of strings (object keys)732 and/or numbers (array indices).733734 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.738739 `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.742743 `path(pattern)` will produce array representations of the744 paths matching `pattern` if the paths exist in `.`.745746 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.750751 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"]]']758759 - title: "`del(path_expression)`"760 body: |761762 The builtin function `del` removes a key and its corresponding763 value from an object.764765 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"]']772773 - title: "`to_entries`, `from_entries`, `with_entries`"774 body: |775776 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}`.780781 `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.786787 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}']797798799 - title: "`select(boolean_expression)`"800 body: |801802 The function `select(foo)` produces its input unchanged if803 `foo` returns true for that input, and produces no output804 otherwise.805806 It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`807 will give you `[2,3]`.808809 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}']816817818 - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"819 body: |820821 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.825826 examples:827 - program: '.[]|numbers'828 input: '[[],{},1,"foo",null,true,false]'829 output: ['1']830831 - title: "`empty`"832 body: |833834 `empty` returns no results. None at all. Not even `null`.835836 It's useful on occasion. You'll know if you need it :)837838 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]']845846 - title: "`error(message)`"847 body: |848849 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.852853 - title: "`$__loc__`"854 body: |855856 Produces an object with a "file" key and a "line" key, with857 the filename and line number where `$__loc__` occurs, as858 values.859860 examples:861 - program: 'try error("\($__loc__)") catch .'862 input: 'null'863 output: ['"{\"file\":\"<top-level>\",\"line\":1}"']864865 - title: "`map(x)`, `map_values(x)`"866 body: |867868 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.871872 Similarly, `map_values(x)` will run that filter for each element,873 but it will return an object when an object is passed.874875 `map(x)` is equivalent to `[.[] | x]`. In fact, this is how876 it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`.877878 examples:879 - program: 'map(.+1)'880 input: '[1,2,3]'881 output: ['[2,3,4]']882883 - program: 'map_values(.+1)'884 input: '{"a": 1, "b": 2, "c": 3}'885 output: ['{"a": 2, "b": 3, "c": 4}']886887 - title: "`paths`, `paths(node_filter)`, `leaf_paths`"888 body: |889890 `paths` outputs the paths to all the elements in its input891 (except it does not output the empty list, representing .892 itself).893894 `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.897898 `leaf_paths` is an alias of `paths(scalars)`; `leaf_paths` is899 *deprecated* and will be removed in the next major release.900901 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"]]']908909 - title: "`add`"910 body: |911912 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).917918 If the input is an empty array, `add` returns `null`.919920 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"]930931 - title: "`any`, `any(condition)`, `any(generator; condition)`"932 body: |933934 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`.937938 If the input is an empty array, `any` returns `false`.939940 The `any(condition)` form applies the given condition to the941 elements of the input array.942943 The `any(generator; condition)` form applies the given944 condition to all the outputs of the given generator.945946 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"]956957 - title: "`all`, `all(condition)`, `all(generator; condition)`"958 body: |959960 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`.963964 The `all(condition)` form applies the given condition to the965 elements of the input array.966967 The `all(generator; condition)` form applies the given968 condition to all the outputs of the given generator.969970 If the input is an empty array, `all` returns `true`.971972 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"]982983 - title: "`flatten`, `flatten(depth)`"984 body: |985986 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.990991 `flatten(2)` is like `flatten`, but going only up to two992 levels deep.993994 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"}]']10071008 - title: "`range(upto)`, `range(from;upto)` `range(from;upto;by)`"1009 body: |10101011 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.10151016 The one argument form generates numbers from 0 to the given1017 number, with an increment of 1.10181019 The two argument form generates numbers from `from` to `upto`1020 with an increment of 1.10211022 The three argument form generates numbers `from` to `upto`1023 with an increment of `by`.10241025 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]']10441045 - title: "`floor`"1046 body: |10471048 The `floor` function returns the floor of its numeric input.10491050 examples:1051 - program: 'floor'1052 input: '3.14159'1053 output: ['3']10541055 - title: "`sqrt`"1056 body: |10571058 The `sqrt` function returns the square root of its numeric input.10591060 examples:1061 - program: 'sqrt'1062 input: '9'1063 output: ['3']10641065 - title: "`tonumber`"1066 body: |10671068 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.10711072 examples:1073 - program: '.[] | tonumber'1074 input: '[1, "1"]'1075 output: [1, 1]10761077 - title: "`tostring`"1078 body: |10791080 The `tostring` function prints its input as a1081 string. Strings are left unchanged, and all other values are1082 JSON-encoded.10831084 examples:1085 - program: '.[] | tostring'1086 input: '[1, "1", [1]]'1087 output: ['"1"', '"1"', '"[1]"']10881089 - title: "`type`"1090 body: |10911092 The `type` function returns the type of its argument as a1093 string, which is one of null, boolean, number, string, array1094 or object.10951096 examples:1097 - program: 'map(type)'1098 input: '[0, false, [], {}, null, "hello"]'1099 output: ['["number", "boolean", "array", "object", "null", "string"]']11001101 - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1102 body: |11031104 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.11111112 Note that division by zero raises an error.11131114 Currently most arithmetic operations operating on infinities,1115 NaNs, and sub-normals do not raise errors.11161117 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"']11241125 - title: "`sort, sort_by(path_expression)`"1126 body: |11271128 The `sort` functions sorts its input, which must be an1129 array. Values are sorted in the following order:11301131 * `null`1132 * `false`1133 * `true`1134 * numbers1135 * strings, in alphabetical order (by unicode codepoint value)1136 * arrays, in lexical order1137 * objects11381139 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.11431144 `sort` may be used to sort by a particular field of an1145 object, or by applying any jq filter.11461147 `sort_by(foo)` compares two elements by comparing the result of1148 `foo` on each element.11491150 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}]']11571158 - title: "`group_by(path_expression)`"1159 body: |11601161 `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.11651166 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.11691170 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}]]']11741175 - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1176 body: |11771178 Find the minimum or maximum element of the input array.11791180 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.11831184 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}']11911192 - title: "`unique`, `unique_by(path_exp)`"1193 body: |11941195 The `unique` function takes as input an array and produces1196 an array of the same elements, in sorted order, with1197 duplicates removed.11981199 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`.12031204 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"]']12141215 - title: "`reverse`"1216 body: |12171218 This function reverses an array.12191220 examples:1221 - program: 'reverse'1222 input: '[1,2,3,4]'1223 output: ['[4,3,2,1]']12241225 - title: "`contains(element)`"1226 body: |12271228 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.12361237 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']12531254 - title: "`indices(s)`"1255 body: |12561257 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`.12611262 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]']12721273 - title: "`index(s)`, `rindex(s)`"1274 body: |12751276 Outputs the index of the first (`index`) or last (`rindex`)1277 occurrence of `s` in the input.12781279 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']12861287 - title: "`inside`"1288 body: |12891290 The filter `inside(b)` will produce true if the input is1291 completely contained within b. It is, essentially, an1292 inversed version of `contains`.12931294 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']13101311 - title: "`startswith(str)`"1312 body: |13131314 Outputs `true` if . starts with the given string argument.13151316 examples:1317 - program: '[.[]|startswith("foo")]'1318 input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1319 output: ['[false, true, false, true, false]']13201321 - title: "`endswith(str)`"1322 body: |13231324 Outputs `true` if . ends with the given string argument.13251326 examples:1327 - program: '[.[]|endswith("foo")]'1328 input: '["foobar", "barfoo"]'1329 output: ['[false, true]']13301331 - title: "`combinations`, `combinations(n)`"1332 body: |13331334 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.13371338 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]']13451346 - title: "`ltrimstr(str)`"1347 body: |13481349 Outputs its input with the given prefix string removed, if it1350 starts with it.13511352 examples:1353 - program: '[.[]|ltrimstr("foo")]'1354 input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1355 output: ['["fo","","barfoo","bar","afoo"]']13561357 - title: "`rtrimstr(str)`"1358 body: |13591360 Outputs its input with the given suffix string removed, if it1361 ends with it.13621363 examples:1364 - program: '[.[]|rtrimstr("foo")]'1365 input: '["fo", "foo", "barfoo", "foobar", "foob"]'1366 output: ['["fo","","bar","foobar","foob"]']13671368 - title: "`explode`"1369 body: |13701371 Converts an input string into an array of the string's1372 codepoint numbers.13731374 examples:1375 - program: 'explode'1376 input: '"foobar"'1377 output: ['[102,111,111,98,97,114]']13781379 - title: "`implode`"1380 body: |13811382 The inverse of explode.13831384 examples:1385 - program: 'implode'1386 input: '[65, 66, 67]'1387 output: ['"ABC"']13881389 - title: "`split`"1390 body: |13911392 Splits an input string on the separator argument.13931394 examples:1395 - program: 'split(", ")'1396 input: '"a, b,c,d, e, "'1397 output: ['["a","b,c,d","e",""]']13981399 - title: "`join(str)`"1400 body: |14011402 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.14061407 examples:1408 - program: 'join(", ")'1409 input: '["a","b,c,d","e"]'1410 output: ['"a, b,c,d, e"']141114121413 - title: "`ascii_downcase`, `ascii_upcase`"1414 body: |14151416 Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1417 converted to the specified case.14181419 example:1420 - program: 'ascii_upcase'1421 input: '"useful but not for é"'1422 output: '"USEFUL BUT NOT FOR é"'14231424 - title: "`while(cond; update)`"1425 body: |14261427 The `while(cond; update)` function allows you to repeatedly1428 apply an update to `.` until `cond` is false.14291430 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.14341435 examples:1436 - program: '[while(.<100; .*2)]'1437 input: '1'1438 output: ['[1,2,4,8,16,32,64]']14391440 - title: "`until(cond; next)`"1441 body: |14421443 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).14471448 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.14521453 examples:1454 - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1455 input: '4'1456 output: ['24']145714581459 - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`, `recurse_down`"1460 body: |14611462 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:14651466 {"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": []}]}]}]}14731474 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:14781479 recurse(.children[]) | .name14801481 When called without an argument, `recurse` is equivalent to1482 `recurse(.[]?)`.14831484 `recurse(f)` is identical to `recurse(f; . != null)` and can be1485 used without concerns about recursion depth.14861487 `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)`.14921493 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.14961497 The recursive calls in `recurse` will not consume additional1498 memory whenever `f` produces at most a single output for each1499 input.15001501 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":[]}'15091510 - program: 'recurse'1511 input: '{"a":0,"b":[1]}'1512 output:1513 - '{"a":0,"b":[1]}'1514 - '0'1515 - '[1]'1516 - '1'15171518 - program: 'recurse(. * .; . < 20)'1519 input: 21520 output:1521 - 21522 - 41523 - 1615241525 - title: "`..`"1526 body: |15271528 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" `.`.15331534 examples:1535 - program: '..|.a?'1536 input: '[[{"a":1}]]'1537 output: ['1']15381539 - title: "`env`"1540 body: |15411542 Outputs an object representing jq's environment.15431544 examples:1545 - program: 'env.PAGER'1546 input: 'null'1547 output: ['"less"']15481549 - title: "`transpose`"1550 body: |15511552 Transpose a possibly jagged matrix (an array of arrays).1553 Rows are padded with nulls so the result is always rectangular.15541555 examples:1556 - program: 'transpose'1557 input: '[[1], [2,3]]'1558 output: ['[[1,2],[null,3]]']15591560 - title: "`bsearch(x)`"1561 body: |15621563 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.15711572 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]']15821583 - title: "String interpolation - `\\(foo)`"1584 body: |15851586 Inside a string, you can put an expression inside parens1587 after a backslash. Whatever the expression returns will be1588 interpolated into the string.15891590 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"']15941595 - title: "Convert to/from JSON"1596 body: |15971598 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.16021603 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"]]']16131614 - title: "Format strings and escaping"1615 body: |16161617 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:16211622 * `@text`:16231624 Calls `tostring`, see that function for details.16251626 * `@json`:16271628 Serializes the input as JSON.16291630 * `@html`:16311632 Applies HTML/XML escaping, by mapping the characters1633 `<>&'"` to their entity equivalents `&lt;`, `&gt;`,1634 `&amp;`, `&apos;`, `&quot;`.16351636 * `@uri`:16371638 Applies percent-encoding, by mapping all reserved URI1639 characters to a `%XX` sequence.16401641 * `@csv`:16421643 The input must be an array, and it is rendered as CSV1644 with double quotes for strings, and quotes escaped by1645 repetition.16461647 * `@tsv`:16481649 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.16561657 * `@sh`:16581659 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.16621663 * `@base64`:16641665 The input is converted to base64 as specified by RFC 4648.16661667 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,16721673 @uri "https://www.google.com/search?q=\(.search)"16741675 will produce the following output for the input1676 `{"search":"what is jq?"}`:16771678 "https://www.google.com/search?q=what%20is%20jq%3F"16791680 Note that the slashes, question mark, etc. in the URL are1681 not escaped, as they were part of the string literal.16821683 examples:1684 - program: '@html'1685 input: '"This works if x < y"'1686 output: ['"This works if x &lt; y"']16871688# - program: '@html "<span>Anonymous said: \(.)</span>"'1689# input: '"<script>alert(\"lol hax\");</script>"'1690# output: ["<span>Anonymous said: &lt;script&gt;alert(&quot;lol hax&quot;);&lt;/script&gt;</span>"]16911692 - program: '@sh "echo \(.)"'1693 input: "\"O'Hara's Ale\""1694 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]16951696 - title: "Dates"1697 body: |16981699 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.17021703 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.17071708 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.17121713 The `todate` builtin is an alias for `todateiso8601`.17141715 The `now` builtin outputs the current time, in seconds since1716 the Unix epoch.17171718 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.17241725 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.17321733 The `mktime` builtin consumes "broken down time"1734 representations of time output by `gmtime` and `strptime`.17351736 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`.17391740 The `strftime(fmt)` builtin formats a time with the given1741 format.17421743 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"`.17461747 jq may not support some or all of this date functionality on1748 some systems.17491750 examples:1751 - program: 'fromdate'1752 input: '"2015-03-05T23:51:47Z"'1753 output: ['1425599507']17541755 - 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]']17581759 - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'1760 input: '"2015-03-05T23:51:47Z"'1761 output: ['1425599507']17621763 - title: Conditionals and Comparisons1764 entries:1765 - title: "`==`, `!=`"1766 body: |17671768 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.17741775 != is "not equal", and 'a != b' returns the opposite value of 'a == b'17761777 examples:1778 - program: '.[] == 1'1779 input: '[1, 1.0, "1", "banana"]'1780 output: ['true', 'true', 'false', 'false']17811782 - title: if-then-else1783 body: |17841785 `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.17881789 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.17961797 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.18001801 More cases can be added to an if using `elif A then B` syntax.18021803 examples:1804 - program: |-1805 if . == 0 then1806 "zero"1807 elif . == 1 then1808 "one"1809 else1810 "many"1811 end1812 input: 21813 output: ['"many"']18141815 - title: "`>, >=, <=, <`"1816 body: |18171818 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).18221823 The ordering is the same as that described for `sort`, above.18241825 examples:1826 - program: '. < 5'1827 input: 21828 output: ['true']18291830 - title: and/or/not1831 body: |18321833 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".18361837 If an operand of one of these operators produces multiple1838 results, the operator itself will produce a result for each input.18391840 `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`.18441845 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.18511852 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]']18681869 - title: Alternative operator - `//`1870 body: |18711872 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`.18751876 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).18811882 examples:1883 - program: '.foo // 42'1884 input: '{"foo": 19}'1885 output: [19]1886 - program: '.foo // 42'1887 input: '{}'1888 output: [42]18891890 - title: try-catch1891 body: |18921893 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.18981899 The `try EXP` form uses `empty` as the exception handler.19001901 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"']19111912 - title: Breaking out of control structures1913 body: |19141915 A convenient use of try/catch is to break out of control1916 structures like `reduce`, `foreach`, `while`, and so on.19171918 For example:19191920 # 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;19241925 jq has a syntax for named lexical labels to "break" or "go (back) to":19261927 label $out | ... break $out ...19281929 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`.19321933 The relationship between the `break` and corresponding `label`1934 is lexical: the label has to be "visible" from the break.19351936 To break out of a `reduce`, for example:19371938 label $out | reduce .[] as $item (null; if .==false then break $out else ... end)19391940 The following jq program produces a syntax error:19411942 break $out19431944 because no label `$out` is visible.19451946 - title: "`?` operator"1947 body: |19481949 The `?` operator, used as `EXP?`, is shorthand for `try EXP`.19501951 examples:1952 - program: '[.[]|(.a)?]'1953 input: '[{}, true, {"a":1}]'1954 output: ['[null, 1]']195519561957 - title: Regular expressions (PCRE)1958 body: |19591960 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.19631964 The jq regex filters are defined so that they can be used using1965 one of these patterns:19661967 STRING | FILTER( REGEX )1968 STRING | FILTER( REGEX; FLAGS )1969 STRING | FILTER( [REGEX] )1970 STRING | FILTER( [REGEX, FLAGS] )19711972 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.19761977 FLAGS is a string consisting of one of more of the supported flags:19781979 * `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)19871988 To match whitespace in an x pattern use an escape such as \s, e.g.19891990 * test( "a\\sb", "x" ).19911992 Note that certain flags may also be specified within REGEX, e.g.19931994 * jq -n '("test", "TEst", "teST", "TEST") | test( "(?i)te(?-i)st" )'19951996 evaluates to: true, true, false, false.19971998 entries:1999 - title: "`test(val)`, `test(regex; flags)`"2000 body: |20012002 Like `match`, but does not return match objects, only `true` or `false`2003 for whether or not the regex matches the input.20042005 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']20122013 - title: "`match(val)`, `match(regex; flags)`"2014 body: |20152016 **match** outputs an object for each match it finds. Matches have2017 the following fields:20182019 * `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.20232024 Capturing group objects have the following fields:20252026 * `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)20302031 Capturing groups that did not match anything return an offset of -120322033 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"}]}'20522053 - program: '[ match("."; "g")] | length'2054 input: '"abc"'2055 output: [3]205620572058 - title: "`capture(val)`, `capture(regex; flags)`"2059 body: |20602061 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.20642065 examples:2066 - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2067 input: '"xyzzy-14"'2068 output: ['{ "a": "xyzzy", "n": "14" }']20692070 - title: "`scan(regex)`, `scan(regex; flags)`"2071 body: |20722073 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) ]`.20782079 example:2080 - program: 'scan("c")'2081 input: '"abcdefabc"'2082 output: ['"c"', '"c"']20832084 - program: 'scan("b")'2085 input: ("", "")2086 output: ['[]', '[]']20872088 - title: "`split(regex; flags)`"2089 body: |20902091 For backwards compatibility, `split` splits on a string, not a regex.20922093 example:2094 - program: 'split(", *"; null)'2095 input: '"ab,cd, ef"'2096 output: ['"ab","cd","ef"']209720982099 - title: "`splits(regex)`, `splits(regex; flags)`"2100 body: |21012102 These provide the same results as their `split` counterparts,2103 but as a stream instead of an array.21042105 example:2106 - program: 'splits(", *")'2107 input: '("ab,cd", "ef, gh")'2108 output: ['"ab"', '"cd"', '"ef"', '"gh"']21092110 - title: "`sub(regex; tostring)` `sub(regex; string; flags)`"2111 body: |21122113 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)".21192120 example:2121 - program: 'sub("^[^a-z]*(?<x>[a-z]*).*")'2122 input: '"123abc456"'2123 output: '"ZabcZabc"'212421252126 - title: "`gsub(regex; string)`, `gsub(regex; string; flags)`"2127 body: |21282129 `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2130 replaced by the string, after interpolation.21312132 example:2133 - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2134 input: '"Abcabc"'2135 output: '"+A-+a-"'213621372138 - title: Advanced features2139 body: |2140 Variables are an absolute necessity in most programming languages, but2141 they're relegated to an "advanced feature" in jq.21422143 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.21492150 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).21542155 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.21582159 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.21622163 Some minimal I/O support (besides reading JSON from standard2164 input, and writing JSON to standard output) is available.21652166 Finally, there is a module/library system.21672168 entries:2169 - title: Variables2170 body: |21712172 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.21782179 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.21852186 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:21912192 length as $array_length | add / $array_length21932194 We'll need a more complicated problem to find a situation where using2195 variables actually makes our lives easier.219621972198 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:22012202 {"posts": [{"title": "Frist psot", "author": "anon"},2203 {"title": "A well-written article", "author": "person1"}],2204 "realnames": {"anon": "Anonymous Coward",2205 "person1": "Person McPherson"}}22062207 We want to produce the posts with the author field containing a real2208 name, as in:22092210 {"title": "Frist psot", "author": "Anonymous Coward"}2211 {"title": "A well-written article", "author": "Person McPherson"}22122213 We use a variable, $names, to store the realnames object, so that we2214 can refer to it later when looking up author usernames:22152216 .realnames as $names | .posts[] | {title, author: $names[.author]}22172218 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.22222223 Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2224 `{$foo}` is a handy way of writing `{foo:$foo}`.22252226 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"):22292230 . as {realnames: $names, posts: [$first, $second]} | ...22312232 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.22372238 Variables are scoped over the rest of the expression that defines2239 them, so22402241 .realnames as $names | (.posts[] | {title, author: $names[.author]})22422243 will work, but22442245 (.realnames as $names | .posts[]) | {title, author: $names[.author]}22462247 won't.22482249 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.22542255 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}']22682269 - title: 'Defining Functions'2270 body: |22712272 You can give a filter a name using "def" syntax:22732274 def increment: . + 1;22752276 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:22792280 def map(f): [.[] | f];22812282 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:22882289 def foo(f): f|f;2290 5|foo(.*2)22912292 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.22972298 If you want the value-argument behaviour for defining simple2299 functions, you can just use a variable:23002301 def addvalue(f): f as $f | map(. + $f);23022303 Or use the short-hand:23042305 def addvalue($f): ...;23062307 With either definition, `addvalue(.foo)` will add the current2308 input's `.foo` field to each element of the array.23092310 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.23142315 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]]']23222323 - title: Reduce2324 body: |23252326 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:23292330 reduce .[] as $item (0; . + $item)23312332 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:23362337 0 | (3 as $item | . + $item) |2338 (2 as $item | . + $item) |2339 (1 as $item | . + $item)23402341 examples:2342 - program: 'reduce .[] as $item (0; . + $item)'2343 input: '[10,2,5,3]'2344 output: ['20']23452346 - title: "`limit(n; exp)`"2347 body: |23482349 The `limit` function extracts up to `n` outputs from `exp`.23502351 examples:2352 - program: '[limit(3;.[])]'2353 input: '[0,1,2,3,4,5,6,7,8,9]'2354 output: ['[0,1,2]']23552356 - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"2357 body: |23582359 The `first(expr)` and `last(expr)` functions extract the first2360 and last values from `expr`, respectively.23612362 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`.23662367 examples:2368 - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'2369 input: '10'2370 output: ['[0,9,5]']23712372 - title: "`first`, `last`, `nth(n)`"2373 body: |23742375 The `first` and `last` functions extract the first2376 and last values from any array at `.`.23772378 The `nth(n)` function extracts the nth value of any array at `.`.23792380 examples:2381 - program: '[range(.)]|[first, last, nth(5)]'2382 input: '10'2383 output: ['[0,9,5]']23842385 - title: "`foreach`"2386 body: |23872388 The `foreach` syntax is similar to `reduce`, but intended to2389 allow the construction of `limit` and reducers that produce2390 intermediate results (see example).23912392 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`.23992400 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).24032404 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"]]']24112412 - title: Recursion2413 body: |24142415 As described above, `recurse` uses recursion, and any jq2416 function can be recursive. The `while` builtin is also2417 implemented in terms of recursion.24182419 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.24232424 For example:24252426 def recurse(f): def r: ., (f | select(. != null) | r); r;24272428 def while(cond; update):2429 def _while:2430 if cond then ., (update | _while) else empty end;2431 _while;24322433 def repeat(exp):2434 def _repeat:2435 exp, _repeat;2436 _repeat;24372438 - title: Generators and iterators2439 body: |24402441 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.24482449 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.24532454 The `empty` builtin is the generator that produces zero2455 outputs. The `empty` builtin backtracks to the preceding2456 generator expression.24572458 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.24662467 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]']24852486 - title: 'Math'2487 body: |24882489 jq currently only has IEEE754 double-precision (64-bit) floating2490 point number support.24912492 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 `.`.24982499 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.25032504 - title: 'I/O'2505 body: |25062507 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.25132514 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.25192520 entries:2521 - title: "`input`"2522 body: |25232524 Outputs one new input.25252526 - title: "`inputs`"2527 body: |25282529 Outputs all remaining inputs, one by one.25302531 This is primarily useful for reductions over a program's2532 inputs.25332534 - title: "`debug`"2535 body: |25362537 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.25412542 - title: "`input_filename`"2543 body: |25442545 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.25482549 - title: "`input_line_number`"2550 body: |25512552 Returns the line number of the input currently being filtered.25532554 - title: 'Streaming'2555 body: |25562557 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.25622563 However, streaming isn't easy to deal with as the jq program will2564 have `[<path>, <leaf-value>]` (and a few other forms) as inputs.25652566 Several builtins are provided to make handling streams easier.25672568 The examples below use the streamed form of `[0,[1]]`, which2569 is `[[0],0],[[1,0],1],[[1,0]],[[1]]`.25702571 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.25762577 entries:2578 - title: "`truncate_stream(stream_expression)`"2579 body: |25802581 Consumes a number as input and truncates the corresponding2582 number of path elements from the left of the outputs of the2583 given streaming expression.25842585 examples:2586 - program: '[1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]'2587 input: '1'2588 output: ['[[[0],2],[[0]]]']25892590 - title: "`fromstream(stream_expression)`"2591 body: |25922593 Outputs values corresponding to the stream expression's2594 outputs.25952596 examples:2597 - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'2598 input: 'null'2599 output: ['[2]']26002601 - title: "`tostream`"2602 body: |26032604 The `tostream` builtin outputs the streamed form of its input.26052606 examples:2607 - program: '. as $dot|fromstream($dot|tostream)|.==$dot'2608 input: '[0,[1,{"a":1},{"b":2}]]'2609 output: ['true']26102611 - title: Assignment2612 body: |26132614 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".26192620 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).26272628 All the assignment operators in jq have path expressions on the2629 left-hand side.26302631 entries:2632 - title: "`=`"2633 body: |26342635 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,26392640 .foo = .bar | .foo.baz = 126412642 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.26502651 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.26552656 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.26602661 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.26672668 Note too that `.a,.b=0` does not set `.a` and `.b`, but2669 `(.a,.b)=0` sets both.26702671 - 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.26792680 This example should show the difference between '=' and '|=':26812682 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:26832684 .a = .b2685 .a |= .b26862687 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}.26902691 The left-hand side can be any general path expression; see `path()`.26922693 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.26972698 If the right-hand side outputs multiple values, only the last2699 one will be used.27002701 examples:27022703 - 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]]']27062707 - title: "`+=`, `-=`, `*=`, `/=`, `%=`, `//=`"2708 body: |27092710 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.27122713 examples:2714 - program: .foo += 12715 input: '{"foo": 42}'2716 output: ['{"foo": 43}']27172718 - 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:27242725 .posts[0].title = "JQ Manual"27262727 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:27302731 .posts[].comments |= . + ["this is great"]27322733 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).27362737 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.27432744 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:27482749 .posts[] | select(.author == "stedolan")27502751 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:27542755 (.posts[] | select(.author == "stedolan") | .comments) |=2756 . + ["terrible."]27572758 - title: Modules2759 body: |27602761 jq has a library/module system. Modules are files whose names end2762 in `.jq`.27632764 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.27672768 Paths in the a search path are subject to various substitutions.27692770 For paths starting with "~/", the user's home directory is2771 substituted for "~".27722773 For paths starting with "$ORIGIN/", the path of the jq executable2774 is substituted for "$ORIGIN".27752776 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.27792780 Import directives can optionally specify a search path to which2781 the default is appended.27822783 The default search path is the search path given to the `-L`2784 command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",2785 "$ORIGIN/../lib"]`.27862787 Null and empty string path elements terminate search path2788 processing.27892790 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.27952796 Consecutive components with the same name are not allowed to avoid2797 ambiguities (e.g., "foo/foo").27982799 For example, with `-L$HOME/.jq` a module `foo` can be found in2800 `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.28012802 If "$HOME/.jq" is a file, it is sourced into the main program.28032804 entries:2805 - title: "`import RelativePathString as NAME [<metadata>];`"2806 body: |28072808 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::".28122813 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.28182819 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.28222823 - title: "`include RelativePathString [<metadata>];`"2824 body: |28252826 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.28312832 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.28372838 - title: "`import RelativePathString as $NAME [<metadata>];`"2839 body: |28402841 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`.28452846 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.28512852 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.28552856 - title: "`module <metadata>;`"2857 body: |28582859 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.28622863 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.28672868 - title: "`modulemeta`"2869 body: |28702871 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.28742875 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---2headline: jq 1.6 Manual34history: |56 *The manual for the development version of jq can be found7 [here](/jq/manual).*89body: |1011 A jq program is a "filter": it takes an input, and produces an12 output. There are a lot of builtin filters for extracting a13 particular field of an object, or converting a number to a string,14 or various other standard tasks.1516 Filters can be combined in various ways - you can pipe the output of17 one filter into another filter, or collect the output of a filter18 into an array.1920 Some filters produce multiple results, for instance there's one that21 produces all the elements of its input array. Piping that filter22 into a second runs the second filter for each element of the23 array. Generally, things that would be done with loops and iteration24 in other languages are just done by gluing filters together in jq.2526 It's important to remember that every filter has an input and an27 output. Even literals like "hello" or 42 are filters - they take an28 input but always produce the same literal as output. Operations that29 combine two filters, like addition, generally feed the same input to30 both and combine the results. So, you can implement an averaging31 filter as `add / length` - feeding the input array both to the `add`32 filter and the `length` filter and then performing the division.3334 But that's getting ahead of ourselves. :) Let's start with something35 simpler:3637manpage_intro: |38 jq(1) -- Command-line JSON processor39 ====================================4041 ## SYNOPSIS4243 `jq` [<options>...] <filter> [<files>...]4445 `jq` can transform JSON in various ways, by selecting, iterating,46 reducing and otherwise mangling JSON documents. For instance,47 running the command `jq 'map(.price) | add'` will take an array of48 JSON objects as input and return the sum of their "price" fields.4950 `jq` can accept text input as well, but by default, `jq` reads a51 stream of JSON entities (including numbers and other literals) from52 `stdin`. Whitespace is only needed to separate entities such as 153 and 2, and true and false. One or more <files> may be specified, in54 which case `jq` will read input from those instead.5556 The <options> are described in the [INVOKING JQ] section; they57 mostly concern input and output formatting. The <filter> is written58 in the jq language and specifies how to transform the input59 file or document.6061 ## FILTERS6263manpage_epilogue: |64 ## BUGS6566 Presumably. Report them or discuss them at:6768 https://github.com/stedolan/jq/issues6970 ## AUTHOR7172 Stephen Dolan `<mu@netsoc.tcd.ie>`7374sections:75 - title: Invoking jq76 body: |7778 jq filters run on a stream of JSON data. The input to jq is79 parsed as a sequence of whitespace-separated JSON values which80 are passed through the provided filter one at a time. The81 output(s) of the filter are written to standard out, again as a82 sequence of whitespace-separated JSON data.8384 Note: it is important to mind the shell's quoting rules. As a85 general rule it's best to always quote (with single-quote86 characters) the jq program, as too many characters with special87 meaning to jq are also shell meta-characters. For example, `jq88 "foo"` will fail on most Unix shells because that will be the same89 as `jq foo`, which will generally fail because `foo is not90 defined`. When using the Windows command shell (cmd.exe) it's91 best to use double quotes around your jq program when given on the92 command-line (instead of the `-f program-file` option), but then93 double-quotes in the jq program need backslash escaping.9495 You can affect how jq reads and writes its input and output96 using some command-line options:9798 * `--version`:99100 Output the jq version and exit with zero.101102 * `--seq`:103104 Use the `application/json-seq` MIME type scheme for separating105 JSON texts in jq's input and output. This means that an ASCII106 RS (record separator) character is printed before each value on107 output and an ASCII LF (line feed) is printed after every108 output. Input JSON texts that fail to parse are ignored (but109 warned about), discarding all subsequent input until the next110 RS. This mode also parses the output of jq without the `--seq`111 option.112113 * `--stream`:114115 Parse the input in streaming fashion, outputing arrays of path116 and leaf values (scalars and empty arrays or empty objects).117 For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]`118 becomes `[[0],[]]`, `[[1],"a"]`, and `[[1,0],"b"]`.119120 This is useful for processing very large inputs. Use this in121 conjunction with filtering and the `reduce` and `foreach` syntax122 to reduce large inputs incrementally.123124 * `--slurp`/`-s`:125126 Instead of running the filter for each JSON object in the127 input, read the entire input stream into a large array and run128 the filter just once.129130 * `--raw-input`/`-R`:131132 Don't parse the input as JSON. Instead, each line of text is133 passed to the filter as a string. If combined with `--slurp`,134 then the entire input is passed to the filter as a single long135 string.136137 * `--null-input`/`-n`:138139 Don't read any input at all! Instead, the filter is run once140 using `null` as the input. This is useful when using jq as a141 simple calculator or to construct JSON data from scratch.142143 * `--compact-output` / `-c`:144145 By default, jq pretty-prints JSON output. Using this option146 will result in more compact output by instead putting each147 JSON object on a single line.148149 * `--tab`:150151 Use a tab for each indentation level instead of two spaces.152153 * `--indent n`:154155 Use the given number of spaces (no more than 8) for indentation.156157 * `--color-output` / `-C` and `--monochrome-output` / `-M`:158159 By default, jq outputs colored JSON if writing to a160 terminal. You can force it to produce color even if writing to161 a pipe or a file using `-C`, and disable color with `-M`.162163 Colors can be configured with the `JQ_COLORS` environment164 variable (see below).165166 * `--ascii-output` / `-a`:167168 jq usually outputs non-ASCII Unicode codepoints as UTF-8, even169 if the input specified them as escape sequences (like170 "\u03bc"). Using this option, you can force jq to produce pure171 ASCII output with every non-ASCII character replaced with the172 equivalent escape sequence.173174 * `--unbuffered`175176 Flush the output after each JSON object is printed (useful if177 you're piping a slow data source into jq and piping jq's178 output elsewhere).179180 * `--sort-keys` / `-S`:181182 Output the fields of each object with the keys in sorted order.183184 * `--raw-output` / `-r`:185186 With this option, if the filter's result is a string then it187 will be written directly to standard output rather than being188 formatted as a JSON string with quotes. This can be useful for189 making jq filters talk to non-JSON-based systems.190191 * `--join-output` / `-j`:192193 Like `-r` but jq won't print a newline after each output.194195 * `-f filename` / `--from-file filename`:196197 Read filter from the file rather than from a command line, like198 awk's -f option. You can also use '#' to make comments.199200 * `-Ldirectory` / `-L directory`:201202 Prepend `directory` to the search list for modules. If this203 option is used then no builtin search list is used. See the204 section on modules below.205206 * `-e` / `--exit-status`:207208 Sets the exit status of jq to 0 if the last output values was209 neither `false` nor `null`, 1 if the last output value was210 either `false` or `null`, or 4 if no valid result was ever211 produced. Normally jq exits with 2 if there was any usage212 problem or system error, 3 if there was a jq program compile213 error, or 0 if the jq program ran.214215 Another way to set the exit status is with the `halt_error`216 builtin function.217218 * `--arg name value`:219220 This option passes a value to the jq program as a predefined221 variable. If you run jq with `--arg foo bar`, then `$foo` is222 available in the program and has the value `"bar"`. Note that223 `value` will be treated as a string, so `--arg foo 123` will224 bind `$foo` to `"123"`.225226 Named arguments are also available to the jq program as227 `$ARGS.named`.228229 * `--argjson name JSON-text`:230231 This option passes a JSON-encoded value to the jq program as a232 predefined variable. If you run jq with `--argjson foo 123`, then233 `$foo` is available in the program and has the value `123`.234235 * `--slurpfile variable-name filename`:236237 This option reads all the JSON texts in the named file and binds238 an array of the parsed JSON values to the given global variable.239 If you run jq with `--slurpfile foo bar`, then `$foo` is available240 in the program and has an array whose elements correspond to the241 texts in the file named `bar`.242243 * `--rawfile variable-name filename`:244245 This option reads in the named file and binds its contents to the given246 global variable. If you run jq with `--rawfile foo bar`, then `$foo` is247 available in the program and has a string whose contents are to the texs248 in the file named `bar`.249250 * `--argfile variable-name filename`:251252 Do not use. Use `--slurpfile` instead.253254 (This option is like `--slurpfile`, but when the file has just255 one text, then that is used, else an array of texts is used as256 in `--slurpfile`.)257258 * `--args`:259260 Remaining arguments are positional string arguments. These are261 available to the jq program as `$ARGS.positional[]`.262263 * `--jsonargs`:264265 Remaining arguments are positional JSON text arguments. These266 are available to the jq program as `$ARGS.positional[]`.267268 * `--run-tests [filename]`:269270 Runs the tests in the given file or standard input. This must271 be the last option given and does not honor all preceding272 options. The input consists of comment lines, empty lines, and273 program lines followed by one input line, as many lines of274 output as are expected (one per output), and a terminating empty275 line. Compilation failure tests start with a line containing276 only "%%FAIL", then a line containing the program to compile,277 then a line containing an error message to compare to the278 actual.279280 Be warned that this option can change backwards-incompatibly.281282 - title: Basic filters283 entries:284 - title: "Identity: `.`"285 body: |286287 The absolute simplest filter is `.` . This is a filter that288 takes its input and produces it unchanged as output. That is,289 this is the identity operator.290291 Since jq by default pretty-prints all output, this trivial292 program can be a useful way of formatting JSON output from,293 say, `curl`.294295 examples:296 - program: '.'297 input: '"Hello, world!"'298 output: ['"Hello, world!"']299300 - title: "Object Identifier-Index: `.foo`, `.foo.bar`"301 body: |302303 The simplest *useful* filter is `.foo`. When given a304 JSON object (aka dictionary or hash) as input, it produces305 the value at the key "foo", or null if there's none present.306307 A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.308309 This syntax only works for simple, identifier-like keys, that310 is, keys that are all made of alphanumeric characters and311 underscore, and which do not start with a digit.312313 If the key contains special characters, you need to surround314 it with double quotes like this: `."foo$"`, or else `.["foo$"]`.315316 For example `.["foo::bar"]` and `.["foo.bar"]` work while317 `.foo::bar` does not, and `.foo.bar` means `.["foo"].["bar"]`.318319 examples:320 - program: '.foo'321 input: '{"foo": 42, "bar": "less interesting data"}'322 output: [42]323 - program: '.foo'324 input: '{"notfoo": true, "alsonotfoo": false}'325 output: ['null']326 - program: '.["foo"]'327 input: '{"foo": 42}'328 output: [42]329330 - title: "Optional Object Identifier-Index: `.foo?`"331 body: |332333 Just like `.foo`, but does not output even an error when `.`334 is not an array or an object.335336 examples:337 - program: '.foo?'338 input: '{"foo": 42, "bar": "less interesting data"}'339 output: [42]340 - program: '.foo?'341 input: '{"notfoo": true, "alsonotfoo": false}'342 output: ['null']343 - program: '.["foo"]?'344 input: '{"foo": 42}'345 output: [42]346 - program: '[.foo?]'347 input: '[1,2]'348 output: ['[]']349350 - title: "Generic Object Index: `.[<string>]`"351 body: |352353 You can also look up fields of an object using syntax like354 `.["foo"]` (.foo above is a shorthand version of this, but355 only for identifier-like strings).356357 - title: "Array Index: `.[2]`"358 body: |359360 When the index value is an integer, `.[<value>]` can index361 arrays. Arrays are zero-based, so `.[2]` returns the third362 element.363364 Negative indices are allowed, with -1 referring to the last365 element, -2 referring to the next to last element, and so on.366367 examples:368 - program: '.[0]'369 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'370 output: ['{"name":"JSON", "good":true}']371372 - program: '.[2]'373 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'374 output: ['null']375376 - program: '.[-2]'377 input: '[1,2,3]'378 output: ['2']379380 - title: "Array/String Slice: `.[10:15]`"381 body: |382383 The `.[10:15]` syntax can be used to return a subarray of an384 array or substring of a string. The array returned by385 `.[10:15]` will be of length 5, containing the elements from386 index 10 (inclusive) to index 15 (exclusive). Either index may387 be negative (in which case it counts backwards from the end of388 the array), or omitted (in which case it refers to the start389 or end of the array).390391 examples:392 - program: '.[2:4]'393 input: '["a","b","c","d","e"]'394 output: ['["c", "d"]']395396 - program: '.[2:4]'397 input: '"abcdefghi"'398 output: ['"cd"']399400 - program: '.[:3]'401 input: '["a","b","c","d","e"]'402 output: ['["a", "b", "c"]']403404 - program: '.[-2:]'405 input: '["a","b","c","d","e"]'406 output: ['["d", "e"]']407408 - title: "Array/Object Value Iterator: `.[]`"409 body: |410411 If you use the `.[index]` syntax, but omit the index412 entirely, it will return *all* of the elements of an413 array. Running `.[]` with the input `[1,2,3]` will produce the414 numbers as three separate results, rather than as a single415 array.416417 You can also use this on an object, and it will return all418 the values of the object.419420 examples:421 - program: '.[]'422 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'423 output:424 - '{"name":"JSON", "good":true}'425 - '{"name":"XML", "good":false}'426427 - program: '.[]'428 input: '[]'429 output: []430431 - program: '.[]'432 input: '{"a": 1, "b": 1}'433 output: ['1', '1']434435 - title: "`.[]?`"436 body: |437438 Like `.[]`, but no errors will be output if . is not an array439 or object.440441 - title: "Comma: `,`"442 body: |443444 If two filters are separated by a comma, then the445 same input will be fed into both and the two filters' output446 value streams will be concatenated in order: first, all of the447 outputs produced by the left expression, and then all of the448 outputs produced by the right. For instance, filter `.foo,449 .bar`, produces both the "foo" fields and "bar" fields as450 separate outputs.451452 examples:453 - program: '.foo, .bar'454 input: '{"foo": 42, "bar": "something else", "baz": true}'455 output: ['42', '"something else"']456457 - program: ".user, .projects[]"458 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'459 output: ['"stedolan"', '"jq"', '"wikiflow"']460461 - program: '.[4,2]'462 input: '["a","b","c","d","e"]'463 output: ['"e"', '"c"']464465 - title: "Pipe: `|`"466 body: |467468 The | operator combines two filters by feeding the output(s) of469 the one on the left into the input of the one on the right. It's470 pretty much the same as the Unix shell's pipe, if you're used to471 that.472473 If the one on the left produces multiple results, the one on474 the right will be run for each of those results. So, the475 expression `.[] | .foo` retrieves the "foo" field of each476 element of the input array.477478 Note that `.a.b.c` is the same as `.a | .b | .c`.479480 Note too that `.` is the input value at the particular stage481 in a "pipeline", specifically: where the `.` expression appears.482 Thus `.a | . | .b` is the same as `.a.b`, as the `.` in the483 middle refers to whatever value `.a` produced.484485 examples:486 - program: '.[] | .name'487 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'488 output: ['"JSON"', '"XML"']489490 - title: "Parenthesis"491 body: |492493 Parenthesis work as a grouping operator just as in any typical494 programming language.495496 examples:497 - program: '(. + 2) * 5'498 input: '1'499 output: [15]500501 - title: Types and Values502 body: |503504 jq supports the same set of datatypes as JSON - numbers,505 strings, booleans, arrays, objects (which in JSON-speak are506 hashes with only string keys), and "null".507508 Booleans, null, strings and numbers are written the same way as509 in javascript. Just like everything else in jq, these simple510 values take an input and produce an output - `42` is a valid jq511 expression that takes an input, ignores it, and returns 42512 instead.513514 entries:515 - title: "Array construction: `[]`"516 body: |517518 As in JSON, `[]` is used to construct arrays, as in519 `[1,2,3]`. The elements of the arrays can be any jq520 expression, including a pipeline. All of the results produced521 by all of the expressions are collected into one big array.522 You can use it to construct an array out of a known quantity523 of values (as in `[.foo, .bar, .baz]`) or to "collect" all the524 results of a filter into an array (as in `[.items[].name]`)525526 Once you understand the "," operator, you can look at jq's array527 syntax in a different light: the expression `[1,2,3]` is not using a528 built-in syntax for comma-separated arrays, but is instead applying529 the `[]` operator (collect results) to the expression 1,2,3 (which530 produces three different results).531532 If you have a filter `X` that produces four results,533 then the expression `[X]` will produce a single result, an534 array of four elements.535536 examples:537 - program: "[.user, .projects[]]"538 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'539 output: ['["stedolan", "jq", "wikiflow"]']540 - program: "[ .[] | . * 2]"541 input: '[1, 2, 3]'542 output: ['[2, 4, 6]']543544 - title: "Object Construction: `{}`"545 body: |546547 Like JSON, `{}` is for constructing objects (aka548 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.549550 If the keys are "identifier-like", then the quotes can be left551 off, as in `{a:42, b:17}`. Keys generated by expressions need552 to be parenthesized, e.g., `{("a"+"b"):59}`.553554 The value can be any expression (although you may need to555 wrap it in parentheses if it's a complicated one), which gets556 applied to the {} expression's input (remember, all filters557 have an input and an output).558559 {foo: .bar}560561 will produce the JSON object `{"foo": 42}` if given the JSON562 object `{"bar":42, "baz":43}` as its input. You can use this563 to select particular fields of an object: if the input is an564 object with "user", "title", "id", and "content" fields and565 you just want "user" and "title", you can write566567 {user: .user, title: .title}568569 Because that is so common, there's a shortcut syntax for it:570 `{user, title}`.571572 If one of the expressions produces multiple results,573 multiple dictionaries will be produced. If the input's574575 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}576577 then the expression578579 {user, title: .titles[]}580581 will produce two outputs:582583 {"user":"stedolan", "title": "JQ Primer"}584 {"user":"stedolan", "title": "More JQ"}585586 Putting parentheses around the key means it will be evaluated as an587 expression. With the same input as above,588589 {(.user): .titles}590591 produces592593 {"stedolan": ["JQ Primer", "More JQ"]}594595 examples:596 - program: '{user, title: .titles[]}'597 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'598 output:599 - '{"user":"stedolan", "title": "JQ Primer"}'600 - '{"user":"stedolan", "title": "More JQ"}'601 - program: '{(.user): .titles}'602 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'603 output: ['{"stedolan": ["JQ Primer", "More JQ"]}']604605 - title: "Recursive Descent: `..`"606 body: |607608 Recursively descends `.`, producing every value. This is the609 same as the zero-argument `recurse` builtin (see below). This610 is intended to resemble the XPath `//` operator. Note that611 `..a` does not work; use `..|.a` instead. In the example612 below we use `..|.a?` to find all the values of object keys613 "a" in any object found "below" `.`.614615 This is particularly useful in conjunction with `path(EXP)`616 (also see below) and the `?` operator.617618 examples:619 - program: '..|.a?'620 input: '[[{"a":1}]]'621 output: ['1']622623 - title: Builtin operators and functions624 body: |625626 Some jq 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.631632 entries:633 - title: "Addition: `+`"634 body: |635636 The operator `+` takes two filters, applies them both637 to the same input, and adds the results together. What638 "adding" means depends on the types involved:639640 - **Numbers** are added by normal arithmetic.641642 - **Arrays** are added by being concatenated into a larger array.643644 - **Strings** are added by being joined into a larger string.645646 - **Objects** are added by merging, that is, inserting all647 the key-value pairs from both objects into a single648 combined object. If both objects contain a value for the649 same key, the object on the right of the `+` wins. (For650 recursive merge use the `*` operator.)651652 `null` can be added to any value, and returns the other653 value unchanged.654655 examples:656 - program: '.a + 1'657 input: '{"a": 7}'658 output: ['8']659 - program: '.a + .b'660 input: '{"a": [1,2], "b": [3,4]}'661 output: ['[1,2,3,4]']662 - program: '.a + null'663 input: '{"a": 1}'664 output: ['1']665 - program: '.a + 1'666 input: '{}'667 output: ['1']668 - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'669 input: 'null'670 output: ['{"a": 42, "b": 2, "c": 3}']671672 - title: "Subtraction: `-`"673 body: |674675 As well as normal arithmetic subtraction on numbers, the `-`676 operator can be used on arrays to remove all occurrences of677 the second array's elements from the first array.678679 examples:680 - program: '4 - .a'681 input: '{"a":3}'682 output: ['1']683 - program: . - ["xml", "yaml"]684 input: '["xml", "yaml", "json"]'685 output: ['["json"]']686687 - title: "Multiplication, division, modulo: `*`, `/`, and `%`"688 body: |689690 These infix operators behave as expected when given two numbers.691 Division by zero raises an error. `x % y` computes x modulo y.692693 Multiplying a string by a number produces the concatenation of694 that string that many times. `"x" * 0` produces **null**.695696 Dividing a string by another splits the first using the second697 as separators.698699 Multiplying two objects will merge them recursively: this works700 like addition but if both objects contain a value for the701 same key, and the values are objects, the two are merged with702 the same strategy.703704 examples:705 - program: '10 / . * 3'706 input: 5707 output: [6]708 - program: '. / ", "'709 input: '"a, b,c,d, e"'710 output: ['["a","b,c,d","e"]']711 - program: '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'712 input: 'null'713 output: ['{"k": {"a": 0, "b": 2, "c": 3}}']714 - program: '.[] | (1 / .)?'715 input: '[1,0,-1]'716 output: ['1', '-1']717718719 - title: "`length`"720 body: |721722 The builtin function `length` gets the length of various723 different types of value:724725 - The length of a **string** is the number of Unicode726 codepoints it contains (which will be the same as its727 JSON-encoded length in bytes if it's pure ASCII).728729 - The length of an **array** is the number of elements.730731 - The length of an **object** is the number of key-value pairs.732733 - The length of **null** is zero.734735 examples:736 - program: '.[] | length'737 input: '[[1,2], "string", {"a":2}, null]'738 output: [2, 6, 1, 0]739740741 - title: "`utf8bytelength`"742 body: |743744 The builtin function `utf8bytelength` outputs the number of745 bytes used to encode a string in UTF-8.746747 examples:748 - program: 'utf8bytelength'749 input: '"\u03bc"'750 output: [2]751752 - title: "`keys`, `keys_unsorted`"753 body: |754755 The builtin function `keys`, when given an object, returns756 its keys in an array.757758 The keys are sorted "alphabetically", by unicode codepoint759 order. This is not an order that makes particular sense in760 any particular language, but you can count on it being the761 same for any two objects with the same set of keys,762 regardless of locale settings.763764 When `keys` is given an array, it returns the valid indices765 for that array: the integers from 0 to length-1.766767 The `keys_unsorted` function is just like `keys`, but if768 the input is an object then the keys will not be sorted,769 instead the keys will roughly be in insertion order.770771 examples:772 - program: 'keys'773 input: '{"abc": 1, "abcd": 2, "Foo": 3}'774 output: ['["Foo", "abc", "abcd"]']775 - program: 'keys'776 input: '[42,3,35]'777 output: ['[0,1,2]']778779 - title: "`has(key)`"780 body: |781782 The builtin function `has` returns whether the input object783 has the given key, or the input array has an element at the784 given index.785786 `has($key)` has the same effect as checking whether `$key`787 is a member of the array returned by `keys`, although `has`788 will be faster.789790 examples:791 - program: 'map(has("foo"))'792 input: '[{"foo": 42}, {}]'793 output: ['[true, false]']794 - program: 'map(has(2))'795 input: '[[0,1], ["a","b","c"]]'796 output: ['[false, true]']797798 - title: "`in`"799 body: |800801 The builtin function `in` returns whether or not the input key is in the802 given object, or the input index corresponds to an element803 in the given array. It is, essentially, an inversed version804 of `has`.805806 examples:807 - program: '.[] | in({"foo": 42})'808 input: '["foo", "bar"]'809 output: ['true', 'false']810 - program: 'map(in([0,1]))'811 input: '[2, 0]'812 output: ['[false, true]']813814 - title: "`map(x)`, `map_values(x)`"815 body: |816817 For any filter `x`, `map(x)` will run that filter for each818 element of the input array, and return the outputs in a new819 array. `map(.+1)` will increment each element of an array of numbers.820821 Similarly, `map_values(x)` will run that filter for each element,822 but it will return an object when an object is passed.823824 `map(x)` is equivalent to `[.[] | x]`. In fact, this is how825 it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`.826827 examples:828 - program: 'map(.+1)'829 input: '[1,2,3]'830 output: ['[2,3,4]']831832 - program: 'map_values(.+1)'833 input: '{"a": 1, "b": 2, "c": 3}'834 output: ['{"a": 2, "b": 3, "c": 4}']835836 - title: "`path(path_expression)`"837 body: |838839 Outputs array representations of the given path expression840 in `.`. The outputs are arrays of strings (object keys)841 and/or numbers (array indices).842843 Path expressions are jq expressions like `.a`, but also `.[]`.844 There are two types of path expressions: ones that can match845 exactly, and ones that cannot. For example, `.a.b.c` is an846 exact match path expression, while `.a[].b` is not.847848 `path(exact_path_expression)` will produce the array849 representation of the path expression even if it does not850 exist in `.`, if `.` is `null` or an array or an object.851852 `path(pattern)` will produce array representations of the853 paths matching `pattern` if the paths exist in `.`.854855 Note that the path expressions are not different from normal856 expressions. The expression857 `path(..|select(type=="boolean"))` outputs all the paths to858 boolean values in `.`, and only those paths.859860 examples:861 - program: 'path(.a[0].b)'862 input: 'null'863 output: ['["a",0,"b"]']864 - program: '[path(..)]'865 input: '{"a":[{"b":1}]}'866 output: ['[[],["a"],["a",0],["a",0,"b"]]']867868 - title: "`del(path_expression)`"869 body: |870871 The builtin function `del` removes a key and its corresponding872 value from an object.873874 examples:875 - program: 'del(.foo)'876 input: '{"foo": 42, "bar": 9001, "baz": 42}'877 output: ['{"bar": 9001, "baz": 42}']878 - program: 'del(.[1, 2])'879 input: '["foo", "bar", "baz"]'880 output: ['["foo"]']881882 - title: "`getpath(PATHS)`"883 body: |884885 The builtin function `getpath` outputs the values in `.` found886 at each path in `PATHS`.887888 examples:889 - program: 'getpath(["a","b"])'890 input: 'null'891 output: ['null']892 - program: '[getpath(["a","b"], ["a","c"])]'893 input: '{"a":{"b":0, "c":1}}'894 output: ['[0, 1]']895896 - title: "`setpath(PATHS; VALUE)`"897 body: |898899 The builtin function `setpath` sets the `PATHS` in `.` to `VALUE`.900901 examples:902 - program: 'setpath(["a","b"]; 1)'903 input: 'null'904 output: ['{"a": {"b": 1}}']905 - program: 'setpath(["a","b"]; 1)'906 input: '{"a":{"b":0}}'907 output: ['{"a": {"b": 1}}']908 - program: 'setpath([0,"a"]; 1)'909 input: 'null'910 output: ['[{"a":1}]']911912 - title: "`delpaths(PATHS)`"913 body: |914915 The builtin function `delpaths` sets the `PATHS` in `.`.916 `PATHS` must be an array of paths, where each path is an array917 of strings and numbers.918919 examples:920 - program: 'delpaths([["a","b"]])'921 input: '{"a":{"b":1},"x":{"y":2}}'922 output: ['{"a":{},"x":{"y":2}}']923924 - title: "`to_entries`, `from_entries`, `with_entries`"925 body: |926927 These functions convert between an object and an array of928 key-value pairs. If `to_entries` is passed an object, then929 for each `k: v` entry in the input, the output array930 includes `{"key": k, "value": v}`.931932 `from_entries` does the opposite conversion, and933 `with_entries(foo)` is a shorthand for `to_entries |934 map(foo) | from_entries`, useful for doing some operation to935 all keys and values of an object. `from_entries` accepts key, Key,936 name, Name, value and Value as keys.937938 examples:939 - program: 'to_entries'940 input: '{"a": 1, "b": 2}'941 output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']942 - program: 'from_entries'943 input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'944 output: ['{"a": 1, "b": 2}']945 - program: 'with_entries(.key |= "KEY_" + .)'946 input: '{"a": 1, "b": 2}'947 output: ['{"KEY_a": 1, "KEY_b": 2}']948949950 - title: "`select(boolean_expression)`"951 body: |952953 The function `select(foo)` produces its input unchanged if954 `foo` returns true for that input, and produces no output955 otherwise.956957 It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`958 will give you `[2,3]`.959960 examples:961 - program: 'map(select(. >= 2))'962 input: '[1,5,3,0,7]'963 output: ['[5,3,7]']964 - program: '.[] | select(.id == "second")'965 input: '[{"id": "first", "val": 1}, {"id": "second", "val": 2}]'966 output: ['{"id": "second", "val": 2}']967968969 - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"970 body: |971972 These built-ins select only inputs that are arrays, objects,973 iterables (arrays or objects), booleans, numbers, normal974 numbers, finite numbers, strings, null, non-null values, and975 non-iterables, respectively.976977 examples:978 - program: '.[]|numbers'979 input: '[[],{},1,"foo",null,true,false]'980 output: ['1']981982 - title: "`empty`"983 body: |984985 `empty` returns no results. None at all. Not even `null`.986987 It's useful on occasion. You'll know if you need it :)988989 examples:990 - program: '1, empty, 2'991 input: 'null'992 output: [1, 2]993 - program: '[1,2,empty,3]'994 input: 'null'995 output: ['[1,2,3]']996997 - title: "`error(message)`"998 body: |9991000 Produces an error, just like `.a` applied to values other than1001 null and objects would, but with the given message as the1002 error's value. Errors can be caught with try/catch; see below.10031004 - title: "`halt`"1005 body: |10061007 Stops the jq program with no further outputs. jq will exit1008 with exit status `0`.10091010 - title: "`halt_error`, `halt_error(exit_code)`"1011 body: |10121013 Stops the jq program with no further outputs. The input will1014 be printed on `stderr` as raw output (i.e., strings will not1015 have double quotes) with no decoration, not even a newline.10161017 The given `exit_code` (defaulting to `5`) will be jq's exit1018 status.10191020 For example, `"Error: somthing went wrong\n"|halt_error(1)`.10211022 - title: "`$__loc__`"1023 body: |10241025 Produces an object with a "file" key and a "line" key, with1026 the filename and line number where `$__loc__` occurs, as1027 values.10281029 examples:1030 - program: 'try error("\($__loc__)") catch .'1031 input: 'null'1032 output: ['"{\"file\":\"<top-level>\",\"line\":1}"']10331034 - title: "`paths`, `paths(node_filter)`, `leaf_paths`"1035 body: |10361037 `paths` outputs the paths to all the elements in its input1038 (except it does not output the empty list, representing .1039 itself).10401041 `paths(f)` outputs the paths to any values for which `f` is true.1042 That is, `paths(numbers)` outputs the paths to all numeric1043 values.10441045 `leaf_paths` is an alias of `paths(scalars)`; `leaf_paths` is1046 *deprecated* and will be removed in the next major release.10471048 examples:1049 - program: '[paths]'1050 input: '[1,[[],{"a":2}]]'1051 output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']1052 - program: '[paths(scalars)]'1053 input: '[1,[[],{"a":2}]]'1054 output: ['[[0],[1,1,"a"]]']10551056 - title: "`add`"1057 body: |10581059 The filter `add` takes as input an array, and produces as1060 output the elements of the array added together. This might1061 mean summed, concatenated or merged depending on the types1062 of the elements of the input array - the rules are the same1063 as those for the `+` operator (described above).10641065 If the input is an empty array, `add` returns `null`.10661067 examples:1068 - program: add1069 input: '["a","b","c"]'1070 output: ['"abc"']1071 - program: add1072 input: '[1, 2, 3]'1073 output: [6]1074 - program: add1075 input: '[]'1076 output: ["null"]10771078 - title: "`any`, `any(condition)`, `any(generator; condition)`"1079 body: |10801081 The filter `any` takes as input an array of boolean values,1082 and produces `true` as output if any of the elements of1083 the array are `true`.10841085 If the input is an empty array, `any` returns `false`.10861087 The `any(condition)` form applies the given condition to the1088 elements of the input array.10891090 The `any(generator; condition)` form applies the given1091 condition to all the outputs of the given generator.10921093 examples:1094 - program: any1095 input: '[true, false]'1096 output: ["true"]1097 - program: any1098 input: '[false, false]'1099 output: ["false"]1100 - program: any1101 input: '[]'1102 output: ["false"]11031104 - title: "`all`, `all(condition)`, `all(generator; condition)`"1105 body: |11061107 The filter `all` takes as input an array of boolean values,1108 and produces `true` as output if all of the elements of1109 the array are `true`.11101111 The `all(condition)` form applies the given condition to the1112 elements of the input array.11131114 The `all(generator; condition)` form applies the given1115 condition to all the outputs of the given generator.11161117 If the input is an empty array, `all` returns `true`.11181119 examples:1120 - program: all1121 input: '[true, false]'1122 output: ["false"]1123 - program: all1124 input: '[true, true]'1125 output: ["true"]1126 - program: all1127 input: '[]'1128 output: ["true"]11291130 - title: "`flatten`, `flatten(depth)`"1131 body: |11321133 The filter `flatten` takes as input an array of nested arrays,1134 and produces a flat array in which all arrays inside the original1135 array have been recursively replaced by their values. You can pass1136 an argument to it to specify how many levels of nesting to flatten.11371138 `flatten(2)` is like `flatten`, but going only up to two1139 levels deep.11401141 examples:1142 - program: flatten1143 input: '[1, [2], [[3]]]'1144 output: ["[1, 2, 3]"]1145 - program: flatten(1)1146 input: '[1, [2], [[3]]]'1147 output: ["[1, 2, [3]]"]1148 - program: flatten1149 input: '[[]]'1150 output: ["[]"]1151 - program: flatten1152 input: '[{"foo": "bar"}, [{"foo": "baz"}]]'1153 output: ['[{"foo": "bar"}, {"foo": "baz"}]']11541155 - title: "`range(upto)`, `range(from;upto)` `range(from;upto;by)`"1156 body: |11571158 The `range` function produces a range of numbers. `range(4;10)`1159 produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers1160 are produced as separate outputs. Use `[range(4;10)]` to get a range as1161 an array.11621163 The one argument form generates numbers from 0 to the given1164 number, with an increment of 1.11651166 The two argument form generates numbers from `from` to `upto`1167 with an increment of 1.11681169 The three argument form generates numbers `from` to `upto`1170 with an increment of `by`.11711172 examples:1173 - program: 'range(2;4)'1174 input: 'null'1175 output: ['2', '3']1176 - program: '[range(2;4)]'1177 input: 'null'1178 output: ['[2,3]']1179 - program: '[range(4)]'1180 input: 'null'1181 output: ['[0,1,2,3]']1182 - program: '[range(0;10;3)]'1183 input: 'null'1184 output: ['[0,3,6,9]']1185 - program: '[range(0;10;-1)]'1186 input: 'null'1187 output: ['[]']1188 - program: '[range(0;-5;-1)]'1189 input: 'null'1190 output: ['[0,-1,-2,-3,-4]']11911192 - title: "`floor`"1193 body: |11941195 The `floor` function returns the floor of its numeric input.11961197 examples:1198 - program: 'floor'1199 input: '3.14159'1200 output: ['3']12011202 - title: "`sqrt`"1203 body: |12041205 The `sqrt` function returns the square root of its numeric input.12061207 examples:1208 - program: 'sqrt'1209 input: '9'1210 output: ['3']12111212 - title: "`tonumber`"1213 body: |12141215 The `tonumber` function parses its input as a number. It1216 will convert correctly-formatted strings to their numeric1217 equivalent, leave numbers alone, and give an error on all other input.12181219 examples:1220 - program: '.[] | tonumber'1221 input: '[1, "1"]'1222 output: [1, 1]12231224 - title: "`tostring`"1225 body: |12261227 The `tostring` function prints its input as a1228 string. Strings are left unchanged, and all other values are1229 JSON-encoded.12301231 examples:1232 - program: '.[] | tostring'1233 input: '[1, "1", [1]]'1234 output: ['"1"', '"1"', '"[1]"']12351236 - title: "`type`"1237 body: |12381239 The `type` function returns the type of its argument as a1240 string, which is one of null, boolean, number, string, array1241 or object.12421243 examples:1244 - program: 'map(type)'1245 input: '[0, false, [], {}, null, "hello"]'1246 output: ['["number", "boolean", "array", "object", "null", "string"]']12471248 - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1249 body: |12501251 Some arithmetic operations can yield infinities and "not a1252 number" (NaN) values. The `isinfinite` builtin returns `true`1253 if its input is infinite. The `isnan` builtin returns `true`1254 if its input is a NaN. The `infinite` builtin returns a1255 positive infinite value. The `nan` builtin returns a NaN.1256 The `isnormal` builtin returns true if its input is a normal1257 number.12581259 Note that division by zero raises an error.12601261 Currently most arithmetic operations operating on infinities,1262 NaNs, and sub-normals do not raise errors.12631264 examples:1265 - program: '.[] | (infinite * .) < 0'1266 input: '[-1, 1]'1267 output: ['true', 'false']1268 - program: 'infinite, nan | type'1269 input: 'null'1270 output: ['"number"', '"number"']12711272 - title: "`sort, sort_by(path_expression)`"1273 body: |12741275 The `sort` functions sorts its input, which must be an1276 array. Values are sorted in the following order:12771278 * `null`1279 * `false`1280 * `true`1281 * numbers1282 * strings, in alphabetical order (by unicode codepoint value)1283 * arrays, in lexical order1284 * objects12851286 The ordering for objects is a little complex: first they're1287 compared by comparing their sets of keys (as arrays in1288 sorted order), and if their keys are equal then the values1289 are compared key by key.12901291 `sort` may be used to sort by a particular field of an1292 object, or by applying any jq filter.12931294 `sort_by(foo)` compares two elements by comparing the result of1295 `foo` on each element.12961297 examples:1298 - program: 'sort'1299 input: '[8,3,null,6]'1300 output: ['[null,3,6,8]']1301 - program: 'sort_by(.foo)'1302 input: '[{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}]'1303 output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']13041305 - title: "`group_by(path_expression)`"1306 body: |13071308 `group_by(.foo)` takes as input an array, groups the1309 elements having the same `.foo` field into separate arrays,1310 and produces all of these arrays as elements of a larger1311 array, sorted by the value of the `.foo` field.13121313 Any jq expression, not just a field access, may be used in1314 place of `.foo`. The sorting order is the same as described1315 in the `sort` function above.13161317 examples:1318 - program: 'group_by(.foo)'1319 input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'1320 output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']13211322 - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1323 body: |13241325 Find the minimum or maximum element of the input array.13261327 The `min_by(path_exp)` and `max_by(path_exp)` functions allow1328 you to specify a particular field or property to examine, e.g.1329 `min_by(.foo)` finds the object with the smallest `foo` field.13301331 examples:1332 - program: 'min'1333 input: '[5,4,2,7]'1334 output: ['2']1335 - program: 'max_by(.foo)'1336 input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'1337 output: ['{"foo":2, "bar":3}']13381339 - title: "`unique`, `unique_by(path_exp)`"1340 body: |13411342 The `unique` function takes as input an array and produces1343 an array of the same elements, in sorted order, with1344 duplicates removed.13451346 The `unique_by(path_exp)` function will keep only one element1347 for each value obtained by applying the argument. Think of it1348 as making an array by taking one element out of every group1349 produced by `group`.13501351 examples:1352 - program: 'unique'1353 input: '[1,2,5,3,5,3,1,3]'1354 output: ['[1,2,3,5]']1355 - program: 'unique_by(.foo)'1356 input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'1357 output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']1358 - program: 'unique_by(length)'1359 input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'1360 output: ['["bacon", "chunky", "asparagus"]']13611362 - title: "`reverse`"1363 body: |13641365 This function reverses an array.13661367 examples:1368 - program: 'reverse'1369 input: '[1,2,3,4]'1370 output: ['[4,3,2,1]']13711372 - title: "`contains(element)`"1373 body: |13741375 The filter `contains(b)` will produce true if b is1376 completely contained within the input. A string B is1377 contained in a string A if B is a substring of A. An array B1378 is contained in an array A if all elements in B are1379 contained in any element in A. An object B is contained in1380 object A if all of the values in B are contained in the1381 value in A with the same key. All other types are assumed to1382 be contained in each other if they are equal.13831384 examples:1385 - program: 'contains("bar")'1386 input: '"foobar"'1387 output: ['true']1388 - program: 'contains(["baz", "bar"])'1389 input: '["foobar", "foobaz", "blarp"]'1390 output: ['true']1391 - program: 'contains(["bazzzzz", "bar"])'1392 input: '["foobar", "foobaz", "blarp"]'1393 output: ['false']1394 - program: 'contains({foo: 12, bar: [{barp: 12}]})'1395 input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1396 output: ['true']1397 - program: 'contains({foo: 12, bar: [{barp: 15}]})'1398 input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1399 output: ['false']14001401 - title: "`indices(s)`"1402 body: |14031404 Outputs an array containing the indices in `.` where `s`1405 occurs. The input may be an array, in which case if `s` is an1406 array then the indices output will be those where all elements1407 in `.` match those of `s`.14081409 examples:1410 - program: 'indices(", ")'1411 input: '"a,b, cd, efg, hijk"'1412 output: ['[3,7,12]']1413 - program: 'indices(1)'1414 input: '[0,1,2,1,3,1,4]'1415 output: ['[1,3,5]']1416 - program: 'indices([1,2])'1417 input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1418 output: ['[1,8]']14191420 - title: "`index(s)`, `rindex(s)`"1421 body: |14221423 Outputs the index of the first (`index`) or last (`rindex`)1424 occurrence of `s` in the input.14251426 examples:1427 - program: 'index(", ")'1428 input: '"a,b, cd, efg, hijk"'1429 output: ['3']1430 - program: 'rindex(", ")'1431 input: '"a,b, cd, efg, hijk"'1432 output: ['12']14331434 - title: "`inside`"1435 body: |14361437 The filter `inside(b)` will produce true if the input is1438 completely contained within b. It is, essentially, an1439 inversed version of `contains`.14401441 examples:1442 - program: 'inside("foobar")'1443 input: '"bar"'1444 output: ['true']1445 - program: 'inside(["foobar", "foobaz", "blarp"])'1446 input: '["baz", "bar"]'1447 output: ['true']1448 - program: 'inside(["foobar", "foobaz", "blarp"])'1449 input: '["bazzzzz", "bar"]'1450 output: ['false']1451 - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1452 input: '{"foo": 12, "bar": [{"barp": 12}]}'1453 output: ['true']1454 - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1455 input: '{"foo": 12, "bar": [{"barp": 15}]}'1456 output: ['false']14571458 - title: "`startswith(str)`"1459 body: |14601461 Outputs `true` if . starts with the given string argument.14621463 examples:1464 - program: '[.[]|startswith("foo")]'1465 input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1466 output: ['[false, true, false, true, false]']14671468 - title: "`endswith(str)`"1469 body: |14701471 Outputs `true` if . ends with the given string argument.14721473 examples:1474 - program: '[.[]|endswith("foo")]'1475 input: '["foobar", "barfoo"]'1476 output: ['[false, true]']14771478 - title: "`combinations`, `combinations(n)`"1479 body: |14801481 Outputs all combinations of the elements of the arrays in the1482 input array. If given an argument `n`, it outputs all combinations1483 of `n` repetitions of the input array.14841485 examples:1486 - program: 'combinations'1487 input: '[[1,2], [3, 4]]'1488 output: ['[1, 3]', '[1, 4]', '[2, 3]', '[2, 4]']1489 - program: 'combinations(2)'1490 input: '[0, 1]'1491 output: ['[0, 0]', '[0, 1]', '[1, 0]', '[1, 1]']14921493 - title: "`ltrimstr(str)`"1494 body: |14951496 Outputs its input with the given prefix string removed, if it1497 starts with it.14981499 examples:1500 - program: '[.[]|ltrimstr("foo")]'1501 input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1502 output: ['["fo","","barfoo","bar","afoo"]']15031504 - title: "`rtrimstr(str)`"1505 body: |15061507 Outputs its input with the given suffix string removed, if it1508 ends with it.15091510 examples:1511 - program: '[.[]|rtrimstr("foo")]'1512 input: '["fo", "foo", "barfoo", "foobar", "foob"]'1513 output: ['["fo","","bar","foobar","foob"]']15141515 - title: "`explode`"1516 body: |15171518 Converts an input string into an array of the string's1519 codepoint numbers.15201521 examples:1522 - program: 'explode'1523 input: '"foobar"'1524 output: ['[102,111,111,98,97,114]']15251526 - title: "`implode`"1527 body: |15281529 The inverse of explode.15301531 examples:1532 - program: 'implode'1533 input: '[65, 66, 67]'1534 output: ['"ABC"']15351536 - title: "`split(str)`"1537 body: |15381539 Splits an input string on the separator argument.15401541 examples:1542 - program: 'split(", ")'1543 input: '"a, b,c,d, e, "'1544 output: ['["a","b,c,d","e",""]']15451546 - title: "`join(str)`"1547 body: |15481549 Joins the array of elements given as input, using the1550 argument as separator. It is the inverse of `split`: that is,1551 running `split("foo") | join("foo")` over any input string1552 returns said input string.15531554 Numbers and booleans in the input are converted to strings.1555 Null values are treated as empty strings. Arrays and objects1556 in the input are not supported.15571558 examples:1559 - program: 'join(", ")'1560 input: '["a","b,c,d","e"]'1561 output: ['"a, b,c,d, e"']1562 - program: 'join(" ")'1563 input: '["a",1,2.3,true,null,false]'1564 output: ['"a 1 2.3 true false"']15651566 - title: "`ascii_downcase`, `ascii_upcase`"1567 body: |15681569 Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1570 converted to the specified case.15711572 example:1573 - program: 'ascii_upcase'1574 input: '"useful but not for é"'1575 output: '"USEFUL BUT NOT FOR é"'15761577 - title: "`while(cond; update)`"1578 body: |15791580 The `while(cond; update)` function allows you to repeatedly1581 apply an update to `.` until `cond` is false.15821583 Note that `while(cond; update)` is internally defined as a1584 recursive jq function. Recursive calls within `while` will1585 not consume additional memory if `update` produces at most one1586 output for each input. See advanced topics below.15871588 examples:1589 - program: '[while(.<100; .*2)]'1590 input: '1'1591 output: ['[1,2,4,8,16,32,64]']15921593 - title: "`until(cond; next)`"1594 body: |15951596 The `until(cond; next)` function allows you to repeatedly1597 apply the expression `next`, initially to `.` then to its own1598 output, until `cond` is true. For example, this can be used1599 to implement a factorial function (see below).16001601 Note that `until(cond; next)` is internally defined as a1602 recursive jq function. Recursive calls within `until()` will1603 not consume additional memory if `next` produces at most one1604 output for each input. See advanced topics below.16051606 examples:1607 - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1608 input: '4'1609 output: ['24']161016111612 - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`, `recurse_down`"1613 body: |16141615 The `recurse(f)` function allows you to search through a1616 recursive structure, and extract interesting data from all1617 levels. Suppose your input represents a filesystem:16181619 {"name": "/", "children": [1620 {"name": "/bin", "children": [1621 {"name": "/bin/ls", "children": []},1622 {"name": "/bin/sh", "children": []}]},1623 {"name": "/home", "children": [1624 {"name": "/home/stephen", "children": [1625 {"name": "/home/stephen/jq", "children": []}]}]}]}16261627 Now suppose you want to extract all of the filenames1628 present. You need to retrieve `.name`, `.children[].name`,1629 `.children[].children[].name`, and so on. You can do this1630 with:16311632 recurse(.children[]) | .name16331634 When called without an argument, `recurse` is equivalent to1635 `recurse(.[]?)`.16361637 `recurse(f)` is identical to `recurse(f; . != null)` and can be1638 used without concerns about recursion depth.16391640 `recurse(f; condition)` is a generator which begins by1641 emitting . and then emits in turn .|f, .|f|f, .|f|f|f, ... so long1642 as the computed value satisfies the condition. For example,1643 to generate all the integers, at least in principle, one1644 could write `recurse(.+1; true)`.16451646 For legacy reasons, `recurse_down` exists as an alias to1647 calling `recurse` without arguments. This alias is considered1648 *deprecated* and will be removed in the next major release.16491650 The recursive calls in `recurse` will not consume additional1651 memory whenever `f` produces at most a single output for each1652 input.16531654 examples:1655 - program: 'recurse(.foo[])'1656 input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'1657 output:1658 - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'1659 - '{"foo":[]}'1660 - '{"foo":[{"foo":[]}]}'1661 - '{"foo":[]}'16621663 - program: 'recurse'1664 input: '{"a":0,"b":[1]}'1665 output:1666 - '{"a":0,"b":[1]}'1667 - '0'1668 - '[1]'1669 - '1'16701671 - program: 'recurse(. * .; . < 20)'1672 input: 21673 output:1674 - 21675 - 41676 - 1616771678 - title: "`walk(f)`"1679 body: |16801681 The `walk(f)` function applies f recursively to every1682 component of the input entity. When an array is1683 encountered, f is first applied to its elements and then to1684 the array itself; when an object is encountered, f is first1685 applied to all the values and then to the object. In1686 practice, f will usually test the type of its input, as1687 illustrated in the following examples. The first example1688 highlights the usefulness of processing the elements of an1689 array of arrays before processing the array itself. The second1690 example shows how all the keys of all the objects within the1691 input can be considered for alteration.16921693 examples:1694 - program: 'walk(if type == "array" then sort else . end)'1695 input: '[[4, 1, 7], [8, 5, 2], [3, 6, 9]]'1696 output:1697 - '[[1,4,7],[2,5,8],[3,6,9]]'16981699 - program: 'walk( if type == "object" then with_entries( .key |= sub( "^_+"; "") ) else . end )'1700 input: '[ { "_a": { "__b": 2 } } ]'1701 output:1702 - '[{"a":{"b":2}}]'17031704 - title: "`$ENV`, `env`"1705 body: |17061707 `$ENV` is an object representing the environment variables as1708 set when the jq program started.17091710 `env` outputs an object representing jq's current environment.17111712 At the moment there is no builtin for setting environment1713 variables.17141715 examples:1716 - program: '$ENV.PAGER'1717 input: 'null'1718 output: ['"less"']17191720 - program: 'env.PAGER'1721 input: 'null'1722 output: ['"less"']17231724 - title: "`transpose`"1725 body: |17261727 Transpose a possibly jagged matrix (an array of arrays).1728 Rows are padded with nulls so the result is always rectangular.17291730 examples:1731 - program: 'transpose'1732 input: '[[1], [2,3]]'1733 output: ['[[1,2],[null,3]]']17341735 - title: "`bsearch(x)`"1736 body: |17371738 bsearch(x) conducts a binary search for x in the input1739 array. If the input is sorted and contains x, then1740 bsearch(x) will return its index in the array; otherwise, if1741 the array is sorted, it will return (-1 - ix) where ix is an1742 insertion point such that the array would still be sorted1743 after the insertion of x at ix. If the array is not sorted,1744 bsearch(x) will return an integer that is probably of no1745 interest.17461747 examples:1748 - program: 'bsearch(0)'1749 input: '[0,1]'1750 output: ['0']1751 - program: 'bsearch(0)'1752 input: '[1,2,3]'1753 output: ['-1']1754 - program: 'bsearch(4) as $ix | if $ix < 0 then .[-(1+$ix)] = 4 else . end'1755 input: '[1,2,3]'1756 output: ['[1,2,3,4]']17571758 - title: "String interpolation - `\\(foo)`"1759 body: |17601761 Inside a string, you can put an expression inside parens1762 after a backslash. Whatever the expression returns will be1763 interpolated into the string.17641765 examples:1766 - program: '"The input was \(.), which is one less than \(.+1)"'1767 input: '42'1768 output: ['"The input was 42, which is one less than 43"']17691770 - title: "Convert to/from JSON"1771 body: |17721773 The `tojson` and `fromjson` builtins dump values as JSON texts1774 or parse JSON texts into values, respectively. The tojson1775 builtin differs from tostring in that tostring returns strings1776 unmodified, while tojson encodes strings as JSON strings.17771778 examples:1779 - program: '[.[]|tostring]'1780 input: '[1, "foo", ["foo"]]'1781 output: ['["1","foo","[\"foo\"]"]']1782 - program: '[.[]|tojson]'1783 input: '[1, "foo", ["foo"]]'1784 output: ['["1","\"foo\"","[\"foo\"]"]']1785 - program: '[.[]|tojson|fromjson]'1786 input: '[1, "foo", ["foo"]]'1787 output: ['[1,"foo",["foo"]]']17881789 - title: "Format strings and escaping"1790 body: |17911792 The `@foo` syntax is used to format and escape strings,1793 which is useful for building URLs, documents in a language1794 like HTML or XML, and so forth. `@foo` can be used as a1795 filter on its own, the possible escapings are:17961797 * `@text`:17981799 Calls `tostring`, see that function for details.18001801 * `@json`:18021803 Serializes the input as JSON.18041805 * `@html`:18061807 Applies HTML/XML escaping, by mapping the characters1808 `<>&'"` to their entity equivalents `&lt;`, `&gt;`,1809 `&amp;`, `&apos;`, `&quot;`.18101811 * `@uri`:18121813 Applies percent-encoding, by mapping all reserved URI1814 characters to a `%XX` sequence.18151816 * `@csv`:18171818 The input must be an array, and it is rendered as CSV1819 with double quotes for strings, and quotes escaped by1820 repetition.18211822 * `@tsv`:18231824 The input must be an array, and it is rendered as TSV1825 (tab-separated values). Each input array will be printed as1826 a single line. Fields are separated by a single1827 tab (ascii `0x09`). Input characters line-feed (ascii `0x0a`),1828 carriage-return (ascii `0x0d`), tab (ascii `0x09`) and1829 backslash (ascii `0x5c`) will be output as escape sequences1830 `\n`, `\r`, `\t`, `\\` respectively.18311832 * `@sh`:18331834 The input is escaped suitable for use in a command-line1835 for a POSIX shell. If the input is an array, the output1836 will be a series of space-separated strings.18371838 * `@base64`:18391840 The input is converted to base64 as specified by RFC 4648.18411842 * `@base64d`:18431844 The inverse of `@base64`, input is decoded as specified by RFC 4648.1845 Note\: If the decoded string is not UTF-8, the results are undefined.18461847 This syntax can be combined with string interpolation in a1848 useful way. You can follow a `@foo` token with a string1849 literal. The contents of the string literal will *not* be1850 escaped. However, all interpolations made inside that string1851 literal will be escaped. For instance,18521853 @uri "https://www.google.com/search?q=\(.search)"18541855 will produce the following output for the input1856 `{"search":"what is jq?"}`:18571858 "https://www.google.com/search?q=what%20is%20jq%3F"18591860 Note that the slashes, question mark, etc. in the URL are1861 not escaped, as they were part of the string literal.18621863 examples:1864 - program: '@html'1865 input: '"This works if x < y"'1866 output: ['"This works if x &lt; y"']18671868# - program: '@html "<span>Anonymous said: \(.)</span>"'1869# input: '"<script>alert(\"lol hax\");</script>"'1870# output: ["<span>Anonymous said: &lt;script&gt;alert(&quot;lol hax&quot;);&lt;/script&gt;</span>"]18711872 - program: '@sh "echo \(.)"'1873 input: "\"O'Hara's Ale\""1874 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]18751876 - program: '@base64'1877 input: '"This is a message"'1878 output: ['"VGhpcyBpcyBhIG1lc3NhZ2U="']18791880 - program: '@base64d'1881 input: '"VGhpcyBpcyBhIG1lc3NhZ2U="'1882 output: ['"This is a message"']18831884 - title: "Dates"1885 body: |18861887 jq provides some basic date handling functionality, with some1888 high-level and low-level builtins. In all cases these1889 builtins deal exclusively with time in UTC.18901891 The `fromdateiso8601` builtin parses datetimes in the ISO 86011892 format to a number of seconds since the Unix epoch1893 (1970-01-01T00:00:00Z). The `todateiso8601` builtin does the1894 inverse.18951896 The `fromdate` builtin parses datetime strings. Currently1897 `fromdate` only supports ISO 8601 datetime strings, but in the1898 future it will attempt to parse datetime strings in more1899 formats.19001901 The `todate` builtin is an alias for `todateiso8601`.19021903 The `now` builtin outputs the current time, in seconds since1904 the Unix epoch.19051906 Low-level jq interfaces to the C-library time functions are1907 also provided: `strptime`, `strftime`, `strflocaltime`,1908 `mktime`, `gmtime`, and `localtime`. Refer to your host1909 operating system's documentation for the format strings used1910 by `strptime` and `strftime`. Note: these are not necessarily1911 stable interfaces in jq, particularly as to their localization1912 functionality.19131914 The `gmtime` builtin consumes a number of seconds since the1915 Unix epoch and outputs a "broken down time" representation of1916 Greenwhich Meridian time as an array of numbers representing1917 (in this order): the year, the month (zero-based), the day of1918 the month (one-based), the hour of the day, the minute of the1919 hour, the second of the minute, the day of the week, and the1920 day of the year -- all one-based unless otherwise stated. The1921 day of the week number may be wrong on some systems for dates1922 before March 1st 1900, or after December 31 2099.19231924 The `localtime` builtin works like the `gmtime` builtin, but1925 using the local timezone setting.19261927 The `mktime` builtin consumes "broken down time"1928 representations of time output by `gmtime` and `strptime`.19291930 The `strptime(fmt)` builtin parses input strings matching the1931 `fmt` argument. The output is in the "broken down time"1932 representation consumed by `gmtime` and output by `mktime`.19331934 The `strftime(fmt)` builtin formats a time (GMT) with the1935 given format. The `strflocaltime` does the same, but using1936 the local timezone setting.19371938 The format strings for `strptime` and `strftime` are described1939 in typical C library documentation. The format string for ISO1940 8601 datetime is `"%Y-%m-%dT%H:%M:%SZ"`.19411942 jq may not support some or all of this date functionality on1943 some systems. In particular, the `%u` and `%j` specifiers for1944 `strptime(fmt)` are not supported on macOS.19451946 examples:1947 - program: 'fromdate'1948 input: '"2015-03-05T23:51:47Z"'1949 output: ['1425599507']19501951 - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")'1952 input: '"2015-03-05T23:51:47Z"'1953 output: ['[2015,2,5,23,51,47,4,63]']19541955 - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'1956 input: '"2015-03-05T23:51:47Z"'1957 output: ['1425599507']19581959 - title: "SQL-Style Operators"1960 body: |19611962 jq provides a few SQL-style operators.19631964 * INDEX(stream; index_expression):19651966 This builtin produces an object whose keys are computed by1967 the given index expression applied to each value from the1968 given stream.19691970 * JOIN($idx; stream; idx_expr; join_expr):19711972 This builtin joins the values from the given stream to the1973 given index. The index's keys are computed by applying the1974 given index expression to each value from the given stream.1975 An array of the value in the stream and the corresponding1976 value from the index is fed to the given join expression to1977 produce each result.19781979 * JOIN($idx; stream; idx_expr):19801981 Same as `JOIN($idx; stream; idx_expr; .)`.19821983 * JOIN($idx; idx_expr):19841985 This builtin joins the input `.` to the given index, applying1986 the given index expression to `.` to compute the index key.1987 The join operation is as described above.19881989 * IN(s):19901991 This builtin outputs `true` if `.` appears in the given1992 stream, otherwise it outputs `false`.19931994 * IN(source; s):19951996 This builtin outputs `true` if any value in the source stream1997 appears in the second stream, otherwise it outputs `false`.19981999 - title: "`builtins`"2000 body: |20012002 Returns a list of all builtin functions in the format `name/arity`.2003 Since functions with the same name but different arities are considered2004 separate functions, `all/0`, `all/1`, and `all/2` would all be present2005 in the list.20062007 - title: Conditionals and Comparisons2008 entries:2009 - title: "`==`, `!=`"2010 body: |20112012 The expression 'a == b' will produce 'true' if the result of a and b2013 are equal (that is, if they represent equivalent JSON documents) and2014 'false' otherwise. In particular, strings are never considered equal2015 to numbers. If you're coming from Javascript, jq's == is like2016 Javascript's === - considering values equal only when they have the2017 same type as well as the same value.20182019 != is "not equal", and 'a != b' returns the opposite value of 'a == b'20202021 examples:2022 - program: '.[] == 1'2023 input: '[1, 1.0, "1", "banana"]'2024 output: ['true', 'true', 'false', 'false']20252026 - title: if-then-else2027 body: |20282029 `if A then B else C end` will act the same as `B` if `A`2030 produces a value other than false or null, but act the same2031 as `C` otherwise.20322033 Checking for false or null is a simpler notion of2034 "truthiness" than is found in Javascript or Python, but it2035 means that you'll sometimes have to be more explicit about2036 the condition you want: you can't test whether, e.g. a2037 string is empty using `if .name then A else B end`, you'll2038 need something more like `if (.name | length) > 0 then A else2039 B end` instead.20402041 If the condition `A` produces multiple results, then `B` is evaluated2042 once for each result that is not false or null, and `C` is evaluated2043 once for each false or null.20442045 More cases can be added to an if using `elif A then B` syntax.20462047 examples:2048 - program: |-2049 if . == 0 then2050 "zero"2051 elif . == 1 then2052 "one"2053 else2054 "many"2055 end2056 input: 22057 output: ['"many"']20582059 - title: "`>, >=, <=, <`"2060 body: |20612062 The comparison operators `>`, `>=`, `<=`, `<` return whether2063 their left argument is greater than, greater than or equal2064 to, less than or equal to or less than their right argument2065 (respectively).20662067 The ordering is the same as that described for `sort`, above.20682069 examples:2070 - program: '. < 5'2071 input: 22072 output: ['true']20732074 - title: and/or/not2075 body: |20762077 jq supports the normal Boolean operators and/or/not. They have the2078 same standard of truth as if expressions - false and null are2079 considered "false values", and anything else is a "true value".20802081 If an operand of one of these operators produces multiple2082 results, the operator itself will produce a result for each input.20832084 `not` is in fact a builtin function rather than an operator,2085 so it is called as a filter to which things can be piped2086 rather than with special syntax, as in `.foo and .bar |2087 not`.20882089 These three only produce the values "true" and "false", and2090 so are only useful for genuine Boolean operations, rather2091 than the common Perl/Python/Ruby idiom of2092 "value_that_may_be_null or default". If you want to use this2093 form of "or", picking between two values rather than2094 evaluating a condition, see the "//" operator below.20952096 examples:2097 - program: '42 and "a string"'2098 input: 'null'2099 output: ['true']2100 - program: '(true, false) or false'2101 input: 'null'2102 output: ['true', 'false']2103# - program: '(true, false) and (true, false)'2104# input: 'null'2105# output: ['true', 'false', 'false', 'false']2106 - program: '(true, true) and (true, false)'2107 input: 'null'2108 output: ['true', 'false', 'true', 'false']2109 - program: '[true, false | not]'2110 input: 'null'2111 output: ['[false, true]']21122113 - title: "Alternative operator: `//`"2114 body: |21152116 A filter of the form `a // b` produces the same2117 results as `a`, if `a` produces results other than `false`2118 and `null`. Otherwise, `a // b` produces the same results as `b`.21192120 This is useful for providing defaults: `.foo // 1` will2121 evaluate to `1` if there's no `.foo` element in the2122 input. It's similar to how `or` is sometimes used in Python2123 (jq's `or` operator is reserved for strictly Boolean2124 operations).21252126 examples:2127 - program: '.foo // 42'2128 input: '{"foo": 19}'2129 output: [19]2130 - program: '.foo // 42'2131 input: '{}'2132 output: [42]21332134 - title: try-catch2135 body: |21362137 Errors can be caught by using `try EXP catch EXP`. The first2138 expression is executed, and if it fails then the second is2139 executed with the error message. The output of the handler,2140 if any, is output as if it had been the output of the2141 expression to try.21422143 The `try EXP` form uses `empty` as the exception handler.21442145 examples:2146 - program: 'try .a catch ". is not an object"'2147 input: 'true'2148 output: ['". is not an object"']2149 - program: '[.[]|try .a]'2150 input: '[{}, true, {"a":1}]'2151 output: ['[null, 1]']2152 - program: 'try error("some exception") catch .'2153 input: 'true'2154 output: ['"some exception"']21552156 - title: Breaking out of control structures2157 body: |21582159 A convenient use of try/catch is to break out of control2160 structures like `reduce`, `foreach`, `while`, and so on.21612162 For example:21632164 # Repeat an expression until it raises "break" as an2165 # error, then stop repeating without re-raising the error.2166 # But if the error caught is not "break" then re-raise it.2167 try repeat(exp) catch .=="break" then empty else error;21682169 jq has a syntax for named lexical labels to "break" or "go (back) to":21702171 label $out | ... break $out ...21722173 The `break $label_name` expression will cause the program to2174 to act as though the nearest (to the left) `label $label_name`2175 produced `empty`.21762177 The relationship between the `break` and corresponding `label`2178 is lexical: the label has to be "visible" from the break.21792180 To break out of a `reduce`, for example:21812182 label $out | reduce .[] as $item (null; if .==false then break $out else ... end)21832184 The following jq program produces a syntax error:21852186 break $out21872188 because no label `$out` is visible.21892190 - title: "Error Suppression / Optional Operator: `?`"2191 body: |21922193 The `?` operator, used as `EXP?`, is shorthand for `try EXP`.21942195 examples:2196 - program: '[.[]|(.a)?]'2197 input: '[{}, true, {"a":1}]'2198 output: ['[null, 1]']219922002201 - title: Regular expressions (PCRE)2202 body: |22032204 jq uses the Oniguruma regular expression library, as do php,2205 ruby, TextMate, Sublime Text, etc, so the description here2206 will focus on jq specifics.22072208 The jq regex filters are defined so that they can be used using2209 one of these patterns:22102211 STRING | FILTER( REGEX )2212 STRING | FILTER( REGEX; FLAGS )2213 STRING | FILTER( [REGEX] )2214 STRING | FILTER( [REGEX, FLAGS] )22152216 where:2217 * STRING, REGEX and FLAGS are jq strings and subject to jq string interpolation;2218 * REGEX, after string interpolation, should be a valid PCRE regex;2219 * FILTER is one of `test`, `match`, or `capture`, as described below.22202221 FLAGS is a string consisting of one of more of the supported flags:22222223 * `g` - Global search (find all matches, not just the first)2224 * `i` - Case insensitive search2225 * `m` - Multi line mode ('.' will match newlines)2226 * `n` - Ignore empty matches2227 * `p` - Both s and m modes are enabled2228 * `s` - Single line mode ('^' -> '\A', '$' -> '\Z')2229 * `l` - Find longest possible matches2230 * `x` - Extended regex format (ignore whitespace and comments)22312232 To match whitespace in an x pattern use an escape such as \s, e.g.22332234 * test( "a\\sb", "x" ).22352236 Note that certain flags may also be specified within REGEX, e.g.22372238 * jq -n '("test", "TEst", "teST", "TEST") | test( "(?i)te(?-i)st" )'22392240 evaluates to: true, true, false, false.22412242 entries:2243 - title: "`test(val)`, `test(regex; flags)`"2244 body: |22452246 Like `match`, but does not return match objects, only `true` or `false`2247 for whether or not the regex matches the input.22482249 examples:2250 - program: 'test("foo")'2251 input: '"foo"'2252 output: ['true']2253 - program: '.[] | test("a b c # spaces are ignored"; "ix")'2254 input: '["xabcd", "ABC"]'2255 output: ['true', 'true']22562257 - title: "`match(val)`, `match(regex; flags)`"2258 body: |22592260 **match** outputs an object for each match it finds. Matches have2261 the following fields:22622263 * `offset` - offset in UTF-8 codepoints from the beginning of the input2264 * `length` - length in UTF-8 codepoints of the match2265 * `string` - the string that it matched2266 * `captures` - an array of objects representing capturing groups.22672268 Capturing group objects have the following fields:22692270 * `offset` - offset in UTF-8 codepoints from the beginning of the input2271 * `length` - length in UTF-8 codepoints of this capturing group2272 * `string` - the string that was captured2273 * `name` - the name of the capturing group (or `null` if it was unnamed)22742275 Capturing groups that did not match anything return an offset of -122762277 examples:2278 - program: 'match("(abc)+"; "g")'2279 input: '"abc abc"'2280 output:2281 - '{"offset": 0, "length": 3, "string": "abc", "captures": [{"offset": 0, "length": 3, "string": "abc", "name": null}]}'2282 - '{"offset": 4, "length": 3, "string": "abc", "captures": [{"offset": 4, "length": 3, "string": "abc", "name": null}]}'2283 - program: 'match("foo")'2284 input: '"foo bar foo"'2285 output: ['{"offset": 0, "length": 3, "string": "foo", "captures": []}']2286 - program: 'match(["foo", "ig"])'2287 input: '"foo bar FOO"'2288 output:2289 - '{"offset": 0, "length": 3, "string": "foo", "captures": []}'2290 - '{"offset": 8, "length": 3, "string": "FOO", "captures": []}'2291 - program: 'match("foo (?<bar123>bar)? foo"; "ig")'2292 input: '"foo bar foo foo foo"'2293 output:2294 - '{"offset": 0, "length": 11, "string": "foo bar foo", "captures": [{"offset": 4, "length": 3, "string": "bar", "name": "bar123"}]}'2295 - '{"offset": 12, "length": 8, "string": "foo foo", "captures": [{"offset": -1, "length": 0, "string": null, "name": "bar123"}]}'22962297 - program: '[ match("."; "g")] | length'2298 input: '"abc"'2299 output: [3]230023012302 - title: "`capture(val)`, `capture(regex; flags)`"2303 body: |23042305 Collects the named captures in a JSON object, with the name2306 of each capture as the key, and the matched string as the2307 corresponding value.23082309 examples:2310 - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2311 input: '"xyzzy-14"'2312 output: ['{ "a": "xyzzy", "n": "14" }']23132314 - title: "`scan(regex)`, `scan(regex; flags)`"2315 body: |23162317 Emit a stream of the non-overlapping substrings of the input2318 that match the regex in accordance with the flags, if any2319 have been specified. If there is no match, the stream is empty.2320 To capture all the matches for each input string, use the idiom2321 `[ expr ]`, e.g. `[ scan(regex) ]`.23222323 example:2324 - program: 'scan("c")'2325 input: '"abcdefabc"'2326 output: ['"c"', '"c"']23272328 - program: 'scan("b")'2329 input: ("", "")2330 output: ['[]', '[]']23312332 - title: "`split(regex; flags)`"2333 body: |23342335 For backwards compatibility, `split` splits on a string, not a regex.23362337 example:2338 - program: 'split(", *"; null)'2339 input: '"ab,cd, ef"'2340 output: ['"ab","cd","ef"']234123422343 - title: "`splits(regex)`, `splits(regex; flags)`"2344 body: |23452346 These provide the same results as their `split` counterparts,2347 but as a stream instead of an array.23482349 example:2350 - program: 'splits(", *")'2351 input: '("ab,cd", "ef, gh")'2352 output: ['"ab"', '"cd"', '"ef"', '"gh"']23532354 - title: "`sub(regex; tostring)` `sub(regex; string; flags)`"2355 body: |23562357 Emit the string obtained by replacing the first match of regex in the2358 input string with `tostring`, after interpolation. `tostring` should2359 be a jq string, and may contain references to named captures. The2360 named captures are, in effect, presented as a JSON object (as2361 constructed by `capture`) to `tostring`, so a reference to a captured2362 variable named "x" would take the form: "\(.x)".23632364 example:2365 - program: 'sub("^[^a-z]*(?<x>[a-z]*).*")'2366 input: '"123abc456"'2367 output: '"ZabcZabc"'236823692370 - title: "`gsub(regex; string)`, `gsub(regex; string; flags)`"2371 body: |23722373 `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2374 replaced by the string, after interpolation.23752376 example:2377 - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2378 input: '"Abcabc"'2379 output: '"+A-+a-"'238023812382 - title: Advanced features2383 body: |2384 Variables are an absolute necessity in most programming languages, but2385 they're relegated to an "advanced feature" in jq.23862387 In most languages, variables are the only means of passing around2388 data. If you calculate a value, and you want to use it more than once,2389 you'll need to store it in a variable. To pass a value to another part2390 of the program, you'll need that part of the program to define a2391 variable (as a function parameter, object member, or whatever) in2392 which to place the data.23932394 It is also possible to define functions in jq, although this is2395 is a feature whose biggest use is defining jq's standard library2396 (many jq functions such as `map` and `find` are in fact written2397 in jq).23982399 jq has reduction operators, which are very powerful but a bit2400 tricky. Again, these are mostly used internally, to define some2401 useful bits of jq's standard library.24022403 It may not be obvious at first, but jq is all about generators2404 (yes, as often found in other languages). Some utilities are2405 provided to help deal with generators.24062407 Some minimal I/O support (besides reading JSON from standard2408 input, and writing JSON to standard output) is available.24092410 Finally, there is a module/library system.24112412 entries:2413 - title: "Variable / Symbolic Binding Operator: `... as $identifier | ...`"2414 body: |24152416 In jq, all filters have an input and an output, so manual2417 plumbing is not necessary to pass a value from one part of a program2418 to the next. Many expressions, for instance `a + b`, pass their input2419 to two distinct subexpressions (here `a` and `b` are both passed the2420 same input), so variables aren't usually necessary in order to use a2421 value twice.24222423 For instance, calculating the average value of an array of numbers2424 requires a few variables in most languages - at least one to hold the2425 array, perhaps one for each element or for a loop counter. In jq, it's2426 simply `add / length` - the `add` expression is given the array and2427 produces its sum, and the `length` expression is given the array and2428 produces its length.24292430 So, there's generally a cleaner way to solve most problems in jq than2431 defining variables. Still, sometimes they do make things easier, so jq2432 lets you define variables using `expression as $variable`. All2433 variable names start with `$`. Here's a slightly uglier version of the2434 array-averaging example:24352436 length as $array_length | add / $array_length24372438 We'll need a more complicated problem to find a situation where using2439 variables actually makes our lives easier.244024412442 Suppose we have an array of blog posts, with "author" and "title"2443 fields, and another object which is used to map author usernames to2444 real names. Our input looks like:24452446 {"posts": [{"title": "Frist psot", "author": "anon"},2447 {"title": "A well-written article", "author": "person1"}],2448 "realnames": {"anon": "Anonymous Coward",2449 "person1": "Person McPherson"}}24502451 We want to produce the posts with the author field containing a real2452 name, as in:24532454 {"title": "Frist psot", "author": "Anonymous Coward"}2455 {"title": "A well-written article", "author": "Person McPherson"}24562457 We use a variable, $names, to store the realnames object, so that we2458 can refer to it later when looking up author usernames:24592460 .realnames as $names | .posts[] | {title, author: $names[.author]}24612462 The expression `exp as $x | ...` means: for each value of expression2463 `exp`, run the rest of the pipeline with the entire original input, and2464 with `$x` set to that value. Thus `as` functions as something of a2465 foreach loop.24662467 Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2468 `{$foo}` is a handy way of writing `{foo:$foo}`.24692470 Multiple variables may be declared using a single `as` expression by2471 providing a pattern that matches the structure of the input2472 (this is known as "destructuring"):24732474 . as {realnames: $names, posts: [$first, $second]} | ...24752476 The variable declarations in array patterns (e.g., `. as2477 [$first, $second]`) bind to the elements of the array in from2478 the element at index zero on up, in order. When there is no2479 value at the index for an array pattern element, `null` is2480 bound to that variable.24812482 Variables are scoped over the rest of the expression that defines2483 them, so24842485 .realnames as $names | (.posts[] | {title, author: $names[.author]})24862487 will work, but24882489 (.realnames as $names | .posts[]) | {title, author: $names[.author]}24902491 won't.24922493 For programming language theorists, it's more accurate to2494 say that jq variables are lexically-scoped bindings. In2495 particular there's no way to change the value of a binding;2496 one can only setup a new binding with the same name, but which2497 will not be visible where the old one was.24982499 examples:2500 - program: '.bar as $x | .foo | . + $x'2501 input: '{"foo":10, "bar":200}'2502 output: ['210']2503 - program: '. as $i|[(.*2|. as $i| $i), $i]'2504 input: '5'2505 output: ['[10,5]']2506 - program: '. as [$a, $b, {c: $c}] | $a + $b + $c'2507 input: '[2, 3, {"c": 4, "d": 5}]'2508 output: ['9']2509 - program: '.[] as [$a, $b] | {a: $a, b: $b}'2510 input: '[[0], [0, 1], [2, 1, 0]]'2511 output: ['{"a":0,"b":null}', '{"a":0,"b":1}', '{"a":2,"b":1}']25122513 - title: 'Destructuring Alternative Operator: `?//`'2514 body: |2515 2516 The destructuring alternative operator provides a concise mechanism2517 for destructuring an input that can take one of several forms.25182519 Suppose we have an API that returns a list of resources and events2520 associated with them, and we want to get the user_id and timestamp of2521 the first event for each resource. The API (having been clumsily2522 converted from XML) will only wrap the events in an array if the resource2523 has multiple events:2524 2525 {"resources": [{"id": 1, "kind": "widget", "events": {"action": "create", "user_id": 1, "ts": 13}},2526 {"id": 2, "kind": "widget", "events": [{"action": "create", "user_id": 1, "ts": 14}, {"action": "destroy", "user_id": 1, "ts": 15}]}]}2527 2528 We can use the destructuring alternative operator to handle this structural change simply:25292530 .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$user_id, $ts}]} | {$user_id, $kind, $id, $ts}25312532 Or, if we aren't sure if the input is an array of values or an object:25332534 .[] as [$id, $kind, $user_id, $ts] ?// {$id, $kind, $user_id, $ts} | ...25352536 Each alternative need not define all of the same variables, but all named2537 variables will be available to the subsequent expression. Variables not2538 matched in the alternative that succeeded will be `null`:25392540 .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$first_user_id, $first_ts}]} | {$user_id, $first_user_id, $kind, $id, $ts, $first_ts}25412542 Additionally, if the subsequent expression returns an error, the2543 alternative operator will attempt to try the next binding. Errors2544 that occur during the final alternative are passed through.25452546 [[3]] | .[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end25472548 examples:2549 - program: '.[] as {$a, $b, c: {$d, $e}} ?// {$a, $b, c: [{$d, $e}]} | {$a, $b, $d, $e}'2550 input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2551 output: ['{"a":1,"b":2,"d":3,"e":4}', '{"a":1,"b":2,"d":3,"e":4}']2552 - program: '.[] as {$a, $b, c: {$d}} ?// {$a, $b, c: [{$e}]} | {$a, $b, $d, $e}'2553 input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2554 output: ['{"a":1,"b":2,"d":3,"e":null}', '{"a":1,"b":2,"d":null,"e":4}']2555 - program: '.[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end'2556 input: '[[3]]'2557 output: ['{"a":null,"b":3}']25582559 - title: 'Defining Functions'2560 body: |25612562 You can give a filter a name using "def" syntax:25632564 def increment: . + 1;25652566 From then on, `increment` is usable as a filter just like a2567 builtin function (in fact, this is how many of the builtins2568 are defined). A function may take arguments:25692570 def map(f): [.[] | f];25712572 Arguments are passed as _filters_ (functions with no2573 arguments), _not_ as values. The same argument may be2574 referenced multiple times with different inputs (here `f` is2575 run for each element of the input array). Arguments to a2576 function work more like callbacks than like value arguments.2577 This is important to understand. Consider:25782579 def foo(f): f|f;2580 5|foo(.*2)25812582 The result will be 20 because `f` is `.*2`, and during the2583 first invocation of `f` `.` will be 5, and the second time it2584 will be 10 (5 * 2), so the result will be 20. Function2585 arguments are filters, and filters expect an input when2586 invoked.25872588 If you want the value-argument behaviour for defining simple2589 functions, you can just use a variable:25902591 def addvalue(f): f as $f | map(. + $f);25922593 Or use the short-hand:25942595 def addvalue($f): ...;25962597 With either definition, `addvalue(.foo)` will add the current2598 input's `.foo` field to each element of the array. Do note2599 that calling `addvalue(.[])` will cause the `map(. + $f)` part2600 to be evaluated once per value in the value of `.` at the call2601 site.26022603 Multiple definitions using the same function name are allowed.2604 Each re-definition replaces the previous one for the same2605 number of function arguments, but only for references from2606 functions (or main program) subsequent to the re-definition.2607 See also the section below on scoping.26082609 examples:2610 - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'2611 input: '[[1,2],[10,20]]'2612 output: ['[[1,2,1], [10,20,10]]']2613 - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'2614 input: '[[1,2],[10,20]]'2615 output: ['[[1,2,1,2], [10,20,1,2]]']26162617 - title: 'Scoping'2618 body: |26192620 There are two types of symbols in jq: value bindings (a.k.a.,2621 "variables"), and functions. Both are scoped lexically,2622 with expressions being able to refer only to symbols that2623 have been defined "to the left" of them. The only exception2624 to this rule is that functions can refer to themselves so as2625 to be able to create recursive functions.26262627 For example, in the following expression there is a binding2628 which is visible "to the right" of it, `... | .*3 as2629 $times_three | [. + $times_three] | ...`, but not "to the2630 left". Consider this expression now, `... | (.*3 as2631 $times_three | [.+ $times_three]) | ...`: here the binding2632 `$times_three` is _not_ visible past the closing parenthesis.26332634 - title: Reduce2635 body: |26362637 The `reduce` syntax in jq allows you to combine all of the2638 results of an expression by accumulating them into a single2639 answer. As an example, we'll pass `[3,2,1]` to this expression:26402641 reduce .[] as $item (0; . + $item)26422643 For each result that `.[]` produces, `. + $item` is run to2644 accumulate a running total, starting from 0. In this2645 example, `.[]` produces the results 3, 2, and 1, so the2646 effect is similar to running something like this:26472648 0 | (3 as $item | . + $item) |2649 (2 as $item | . + $item) |2650 (1 as $item | . + $item)26512652 examples:2653 - program: 'reduce .[] as $item (0; . + $item)'2654 input: '[10,2,5,3]'2655 output: ['20']26562657 - title: "`isempty(exp)`"2658 body: |26592660 Returns true if `exp` produces no outputs, false otherwise.26612662 examples:2663 - program: 'isempty(empty)'2664 input: 'null'2665 output: ['true']26662667 - title: "`limit(n; exp)`"2668 body: |26692670 The `limit` function extracts up to `n` outputs from `exp`.26712672 examples:2673 - program: '[limit(3;.[])]'2674 input: '[0,1,2,3,4,5,6,7,8,9]'2675 output: ['[0,1,2]']26762677 - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"2678 body: |26792680 The `first(expr)` and `last(expr)` functions extract the first2681 and last values from `expr`, respectively.26822683 The `nth(n; expr)` function extracts the nth value output by2684 `expr`. This can be defined as `def nth(n; expr):2685 last(limit(n + 1; expr));`. Note that `nth(n; expr)` doesn't2686 support negative values of `n`.26872688 examples:2689 - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'2690 input: '10'2691 output: ['[0,9,5]']26922693 - title: "`first`, `last`, `nth(n)`"2694 body: |26952696 The `first` and `last` functions extract the first2697 and last values from any array at `.`.26982699 The `nth(n)` function extracts the nth value of any array at `.`.27002701 examples:2702 - program: '[range(.)]|[first, last, nth(5)]'2703 input: '10'2704 output: ['[0,9,5]']27052706 - title: "`foreach`"2707 body: |27082709 The `foreach` syntax is similar to `reduce`, but intended to2710 allow the construction of `limit` and reducers that produce2711 intermediate results (see example).27122713 The form is `foreach EXP as $var (INIT; UPDATE; EXTRACT)`.2714 Like `reduce`, `INIT` is evaluated once to produce a state2715 value, then each output of `EXP` is bound to `$var`, `UPDATE`2716 is evaluated for each output of `EXP` with the current state2717 and with `$var` visible. Each value output by `UPDATE`2718 replaces the previous state. Finally, `EXTRACT` is evaluated2719 for each new state to extract an output of `foreach`.27202721 This is mostly useful only for constructing `reduce`- and2722 `limit`-like functions. But it is much more general, as it2723 allows for partial reductions (see the example below).27242725 examples:2726 - program: '[foreach .[] as $item2727 ([[],[]];2728 if $item == null then [[],.[0]] else [(.[0] + [$item]),[]] end;2729 if $item == null then .[1] else empty end)]'2730 input: '[1,2,3,4,null,"a","b",null]'2731 output: ['[[1,2,3,4],["a","b"]]']27322733 - title: Recursion2734 body: |27352736 As described above, `recurse` uses recursion, and any jq2737 function can be recursive. The `while` builtin is also2738 implemented in terms of recursion.27392740 Tail calls are optimized whenever the expression to the left of2741 the recursive call outputs its last value. In practice this2742 means that the expression to the left of the recursive call2743 should not produce more than one output for each input.27442745 For example:27462747 def recurse(f): def r: ., (f | select(. != null) | r); r;27482749 def while(cond; update):2750 def _while:2751 if cond then ., (update | _while) else empty end;2752 _while;27532754 def repeat(exp):2755 def _repeat:2756 exp, _repeat;2757 _repeat;27582759 - title: Generators and iterators2760 body: |27612762 Some jq operators and functions are actually generators in2763 that they can produce zero, one, or more values for each2764 input, just as one might expect in other programming2765 languages that have generators. For example, `.[]`2766 generates all the values in its input (which must be an2767 array or an object), `range(0; 10)` generates the integers2768 between 0 and 10, and so on.27692770 Even the comma operator is a generator, generating first the2771 values generated by the expression to the left of the comma,2772 then for each of those, the values generate by the2773 expression on the right of the comma.27742775 The `empty` builtin is the generator that produces zero2776 outputs. The `empty` builtin backtracks to the preceding2777 generator expression.27782779 All jq functions can be generators just by using builtin2780 generators. It is also possible to define new generators2781 using only recursion and the comma operator. If the2782 recursive call(s) is(are) "in tail position" then the2783 generator will be efficient. In the example below the2784 recursive call by `_range` to itself is in tail position.2785 The example shows off three advanced topics: tail recursion,2786 generator construction, and sub-functions.27872788 examples:2789 - program: 'def range(init; upto; by):2790 def _range:2791 if (by > 0 and . < upto) or (by < 0 and . > upto)2792 then ., ((.+by)|_range)2793 else . end;2794 if by == 0 then init else init|_range end |2795 select((by > 0 and . < upto) or (by < 0 and . > upto));2796 range(0; 10; 3)'2797 input: 'null'2798 output: ['0', '3', '6', '9']2799 - program: 'def while(cond; update):2800 def _while:2801 if cond then ., (update | _while) else empty end;2802 _while;2803 [while(.<100; .*2)]'2804 input: '1'2805 output: ['[1,2,4,8,16,32,64]']28062807 - title: 'Math'2808 body: |28092810 jq currently only has IEEE754 double-precision (64-bit) floating2811 point number support.28122813 Besides simple arithmetic operators such as `+`, jq also has most2814 standard math functions from the C math library. C math functions2815 that take a single input argument (e.g., `sin()`) are available as2816 zero-argument jq functions. C math functions that take two input2817 arguments (e.g., `pow()`) are available as two-argument jq2818 functions that ignore `.`. C math functions that take three input2819 arguments are available as three-argument jq functions that ignore2820 `.`.28212822 Availability of standard math functions depends on the2823 availability of the corresponding math functions in your operating2824 system and C math library. Unavailable math functions will be2825 defined but will raise an error.28262827 One-input C math functions: `acos` `acosh` `asin` `asinh` `atan`2828 `atanh` `cbrt` `ceil` `cos` `cosh` `erf` `erfc` `exp` `exp10`2829 `exp2` `expm1` `fabs` `floor` `gamma` `j0` `j1` `lgamma` `log`2830 `log10` `log1p` `log2` `logb` `nearbyint` `pow10` `rint` `round`2831 `significand` `sin` `sinh` `sqrt` `tan` `tanh` `tgamma` `trunc`2832 `y0` `y1`.28332834 Two-input C math functions: `atan2` `copysign` `drem` `fdim`2835 `fmax` `fmin` `fmod` `frexp` `hypot` `jn` `ldexp` `modf`2836 `nextafter` `nexttoward` `pow` `remainder` `scalb` `scalbln` `yn`.28372838 Three-input C math functions: `fma`.28392840 See your system's manual for more information on each of these.28412842 - title: 'I/O'2843 body: |28442845 At this time jq has minimal support for I/O, mostly in the2846 form of control over when inputs are read. Two builtins functions2847 are provided for this, `input` and `inputs`, that read from the2848 same sources (e.g., `stdin`, files named on the command-line) as2849 jq itself. These two builtins, and jq's own reading actions, can2850 be interleaved with each other.28512852 Two builtins provide minimal output capabilities, `debug`, and2853 `stderr`. (Recall that a jq program's output values are always2854 output as JSON texts on `stdout`.) The `debug` builtin can have2855 application-specific behavior, such as for executables that use2856 the libjq C API but aren't the jq executable itself. The `stderr`2857 builtin outputs its input in raw mode to stder with no additional2858 decoration, not even a newline.28592860 Most jq builtins are referentially transparent, and yield constant2861 and repeatable value streams when applied to constant inputs.2862 This is not true of I/O builtins.28632864 entries:2865 - title: "`input`"2866 body: |28672868 Outputs one new input.28692870 - title: "`inputs`"2871 body: |28722873 Outputs all remaining inputs, one by one.28742875 This is primarily useful for reductions over a program's2876 inputs.28772878 - title: "`debug`"2879 body: |28802881 Causes a debug message based on the input value to be2882 produced. The jq executable wraps the input value with2883 `["DEBUG:", <input-value>]` and prints that and a newline on2884 stderr, compactly. This may change in the future.28852886 - title: "`stderr`"2887 body: |28882889 Prints its input in raw and compact mode to stderr with no2890 additional decoration, not even a newline.28912892 - title: "`input_filename`"2893 body: |28942895 Returns the name of the file whose input is currently being2896 filtered. Note that this will not work well unless jq is2897 running in a UTF-8 locale.28982899 - title: "`input_line_number`"2900 body: |29012902 Returns the line number of the input currently being filtered.29032904 - title: 'Streaming'2905 body: |29062907 With the `--stream` option jq can parse input texts in a streaming2908 fashion, allowing jq programs to start processing large JSON texts2909 immediately rather than after the parse completes. If you have a2910 single JSON text that is 1GB in size, streaming it will allow you2911 to process it much more quickly.29122913 However, streaming isn't easy to deal with as the jq program will2914 have `[<path>, <leaf-value>]` (and a few other forms) as inputs.29152916 Several builtins are provided to make handling streams easier.29172918 The examples below use the streamed form of `[0,[1]]`, which is2919 `[[0],0],[[1,0],1],[[1,0]],[[1]]`.29202921 Streaming forms include `[<path>, <leaf-value>]` (to indicate any2922 scalar value, empty array, or empty object), and `[<path>]` (to2923 indicate the end of an array or object). Future versions of jq2924 run with `--stream` and `-seq` may output additional forms such as2925 `["error message"]` when an input text fails to parse.29262927 entries:2928 - title: "`truncate_stream(stream_expression)`"2929 body: |29302931 Consumes a number as input and truncates the corresponding2932 number of path elements from the left of the outputs of the2933 given streaming expression.29342935 examples:2936 - program: '[1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]'2937 input: '1'2938 output: ['[[[0],2],[[0]]]']29392940 - title: "`fromstream(stream_expression)`"2941 body: |29422943 Outputs values corresponding to the stream expression's2944 outputs.29452946 examples:2947 - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'2948 input: 'null'2949 output: ['[2]']29502951 - title: "`tostream`"2952 body: |29532954 The `tostream` builtin outputs the streamed form of its input.29552956 examples:2957 - program: '. as $dot|fromstream($dot|tostream)|.==$dot'2958 input: '[0,[1,{"a":1},{"b":2}]]'2959 output: ['true']29602961 - title: Assignment2962 body: |2963 Assignment works a little differently in jq than in most2964 programming languages. jq doesn't distinguish between references2965 to and copies of something - two objects or arrays are either2966 equal or not equal, without any further notion of being "the2967 same object" or "not the same object".29682969 If an object has two fields which are arrays, `.foo` and `.bar`,2970 and you append something to `.foo`, then `.bar` will not get2971 bigger, even if you've previously set `.bar = .foo`. If you're2972 used to programming in languages like Python, Java, Ruby,2973 Javascript, etc. then you can think of it as though jq does a full2974 deep copy of every object before it does the assignment (for2975 performance it doesn't actually do that, but that's the general2976 idea).29772978 This means that it's impossible to build circular values in jq2979 (such as an array whose first element is itself). This is quite2980 intentional, and ensures that anything a jq program can produce2981 can be represented in JSON.29822983 All the assignment operators in jq have path expressions on the2984 left-hand side (LHS). The right-hand side (RHS) provides values2985 to set to the paths named by the LHS path expressions.29862987 Values in jq are always immutable. Internally, assignment works2988 by using a reduction to compute new, replacement values for `.` that2989 have had all the desired assignments applied to `.`, then2990 outputting the modified value. This might be made clear by this2991 example: `{a:{b:{c:1}}} | (.a.b|=3), .`. This will output2992 `{"a":{"b":3}}` and `{"a":{"b":{"c":1}}}` because the last2993 sub-expression, `.`, sees the original value, not the modified2994 value.29952996 Most users will want to use modification assignment operators,2997 such as `|=` or `+=`, rather than `=`.29982999 Note that the LHS of assignment operators refers to a value in3000 `.`. Thus `$var.foo = 1` won't work as expected (`$var.foo` is3001 not a valid or useful path expression in `.`); use `$var | .foo =3002 1` instead.30033004 Note too that `.a,.b=0` does not set `.a` and `.b`, but3005 `(.a,.b)=0` sets both.30063007 entries:3008 - title: "Update-assignment: `|=`"3009 body: |3010 This is the "update" operator '|='. It takes a filter on the3011 right-hand side and works out the new value for the property3012 of `.` being assigned to by running the old value through this3013 expression. For instance, (.foo, .bar) |= .+1 will build an3014 object with the "foo" field set to the input's "foo" plus 1,3015 and the "bar" field set to the input's "bar" plus 1.30163017 The left-hand side can be any general path expression; see `path()`.30183019 Note that the left-hand side of '|=' refers to a value in `.`.3020 Thus `$var.foo |= . + 1` won't work as expected (`$var.foo` is3021 not a valid or useful path expression in `.`); use `$var |3022 .foo |= . + 1` instead.30233024 If the right-hand side outputs no values (i.e., `empty`), then3025 the left-hand side path will be deleted, as with `del(path)`.30263027 If the right-hand side outputs multiple values, only the first3028 one will be used (COMPATIBILITY NOTE: in jq 1.5 and earlier3029 releases, it used to be that only the last one was used).30303031 examples:3032 - program: '(..|select(type=="boolean")) |= if . then 1 else 0 end'3033 input: '[true,false,[5,true,[true,[false]],false]]'3034 output: ['[1,0,[5,1,[1,[0]],0]]']30353036 - title: "Arithmetic update-assignment: `+=`, `-=`, `*=`, `/=`, `%=`, `//=`"3037 body: |30383039 jq has a few operators of the form `a op= b`, which are all3040 equivalent to `a |= . op b`. So, `+= 1` can be used to3041 increment values, being the same as `|= . + 1`.30423043 examples:3044 - program: .foo += 13045 input: '{"foo": 42}'3046 output: ['{"foo": 43}']30473048 - title: "Plain assignment: `=`"3049 body: |30503051 This is the plain assignment operator. Unlike the others, the3052 input to the right-hand-side (RHS) is the same as the input to3053 the left-hand-side (LHS) rather than the value at the LHS3054 path, and all values output by the RHS will be used (as shown3055 below).30563057 If the RHS of '=' produces multiple values, then for each such3058 value jq will set the paths on the left-hand side to the value3059 and then it will output the modified `.`. For example,3060 `(.a,.b)=range(2)` outputs `{"a":0,"b":0}`, then3061 `{"a":1,"b":1}`. The "update" assignment forms (see above) do3062 not do this.30633064 This example should show the difference between '=' and '|=':30653066 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:30673068 .a = .b30693070 .a |= .b30713072 The former will set the "a" field of the input to the "b"3073 field of the input, and produce the output {"a": 20, "b": 20}.3074 The latter will set the "a" field of the input to the "a"3075 field's "b" field, producing {"a": 10, "b": 20}.30763077 Another example of the difference between '=' and '|=':30783079 null|(.a,.b)=range(3)30803081 outputs '{"a":0,"b":0}', '{"a":1,"b":1}', and '{"a":2,"b":2}',3082 while30833084 null|(.a,.b)|=range(3)30853086 outputs just '{"a":0,"b":0}'.30873088 - title: Complex assignments3089 body: |3090 Lots more things are allowed on the left-hand side of a jq assignment3091 than in most languages. We've already seen simple field accesses on3092 the left hand side, and it's no surprise that array accesses work just3093 as well:30943095 .posts[0].title = "JQ Manual"30963097 What may come as a surprise is that the expression on the left may3098 produce multiple results, referring to different points in the input3099 document:31003101 .posts[].comments |= . + ["this is great"]31023103 That example appends the string "this is great" to the "comments"3104 array of each post in the input (where the input is an object with a3105 field "posts" which is an array of posts).31063107 When jq encounters an assignment like 'a = b', it records the "path"3108 taken to select a part of the input document while executing a. This3109 path is then used to find which part of the input to change while3110 executing the assignment. Any filter may be used on the3111 left-hand side of an equals - whichever paths it selects from the3112 input will be where the assignment is performed.31133114 This is a very powerful operation. Suppose we wanted to add a comment3115 to blog posts, using the same "blog" input above. This time, we only3116 want to comment on the posts written by "stedolan". We can find those3117 posts using the "select" function described earlier:31183119 .posts[] | select(.author == "stedolan")31203121 The paths provided by this operation point to each of the posts that3122 "stedolan" wrote, and we can comment on each of them in the same way3123 that we did before:31243125 (.posts[] | select(.author == "stedolan") | .comments) |=3126 . + ["terrible."]31273128 - title: Modules3129 body: |31303131 jq has a library/module system. Modules are files whose names end3132 in `.jq`.31333134 Modules imported by a program are searched for in a default search3135 path (see below). The `import` and `include` directives allow the3136 importer to alter this path.31373138 Paths in the a search path are subject to various substitutions.31393140 For paths starting with "~/", the user's home directory is3141 substituted for "~".31423143 For paths starting with "$ORIGIN/", the path of the jq executable3144 is substituted for "$ORIGIN".31453146 For paths starting with "./" or paths that are ".", the path of3147 the including file is substituted for ".". For top-level programs3148 given on the command-line, the current directory is used.31493150 Import directives can optionally specify a search path to which3151 the default is appended.31523153 The default search path is the search path given to the `-L`3154 command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",3155 "$ORIGIN/../lib"]`.31563157 Null and empty string path elements terminate search path3158 processing.31593160 A dependency with relative path "foo/bar" would be searched for in3161 "foo/bar.jq" and "foo/bar/bar.jq" in the given search path. This3162 is intended to allow modules to be placed in a directory along3163 with, for example, version control files, README files, and so on,3164 but also to allow for single-file modules.31653166 Consecutive components with the same name are not allowed to avoid3167 ambiguities (e.g., "foo/foo").31683169 For example, with `-L$HOME/.jq` a module `foo` can be found in3170 `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.31713172 If "$HOME/.jq" is a file, it is sourced into the main program.31733174 entries:3175 - title: "`import RelativePathString as NAME [<metadata>];`"3176 body: |31773178 Imports a module found at the given path relative to a3179 directory in a search path. A ".jq" suffix will be added to3180 the relative path string. The module's symbols are prefixed3181 with "NAME::".31823183 The optional metadata must be a constant jq expression. It3184 should be an object with keys like "homepage" and so on. At3185 this time jq only uses the "search" key/value of the metadata.3186 The metadata is also made available to users via the3187 `modulemeta` builtin.31883189 The "search" key in the metadata, if present, should have a3190 string or array value (array of strings); this is the search3191 path to be prefixed to the top-level search path.31923193 - title: "`include RelativePathString [<metadata>];`"3194 body: |31953196 Imports a module found at the given path relative to a3197 directory in a search path as if it were included in place. A3198 ".jq" suffix will be added to the relative path string. The3199 module's symbols are imported into the caller's namespace as3200 if the module's content had been included directly.32013202 The optional metadata must be a constant jq expression. It3203 should be an object with keys like "homepage" and so on. At3204 this time jq only uses the "search" key/value of the metadata.3205 The metadata is also made available to users via the3206 `modulemeta` builtin.32073208 - title: "`import RelativePathString as $NAME [<metadata>];`"3209 body: |32103211 Imports a JSON file found at the given path relative to a3212 directory in a search path. A ".json" suffix will be added to3213 the relative path string. The file's data will be available3214 as `$NAME::NAME`.32153216 The optional metadata must be a constant jq expression. It3217 should be an object with keys like "homepage" and so on. At3218 this time jq only uses the "search" key/value of the metadata.3219 The metadata is also made available to users via the3220 `modulemeta` builtin.32213222 The "search" key in the metadata, if present, should have a3223 string or array value (array of strings); this is the search3224 path to be prefixed to the top-level search path.32253226 - title: "`module <metadata>;`"3227 body: |32283229 This directive is entirely optional. It's not required for3230 proper operation. It serves only the purpose of providing3231 metadata that can be read with the `modulemeta` builtin.32323233 The metadata must be a constant jq expression. It should be3234 an object with keys like "homepage". At this time jq doesn't3235 use this metadata, but it is made available to users via the3236 `modulemeta` builtin.32373238 - title: "`modulemeta`"3239 body: |32403241 Takes a module name as input and outputs the module's metadata3242 as an object, with the module's imports (including metadata)3243 as an array value for the "deps" key.32443245 Programs can use this to query a module's metadata, which they3246 could then use to, for example, search for, download, and3247 install missing dependencies.32483249 - title: Colors3250 body: |32513252 To configure alternative colors just set the `JQ_COLORS`3253 environment variable to colon-delimited list of partial terminal3254 escape sequences like `"1;31"`, in this order:32553256 - color for `null`3257 - color for `false`3258 - color for `true`3259 - color for numbers3260 - color for strings3261 - color for arrays3262 - color for objects32633264 The default color scheme is the same as setting3265 `"JQ_COLORS=1;30:0;39:0;39:0;39:0;32:1;39:1;39"`.32663267 This is not a manual for VT100/ANSI escapes. However, each of3268 these color specifications should consist of two numbers separated3269 by a semi-colon, where the first number is one of these:32703271 - 1 (bright)3272 - 2 (dim)3273 - 4 (underscore)3274 - 5 (blink)3275 - 7 (reverse)3276 - 8 (hidden)32773278 and the second is one of these:32793280 - 30 (black)3281 - 31 (red)3282 - 32 (green)3283 - 33 (yellow)3284 - 34 (blue)3285 - 35 (magenta)3286 - 36 (cyan)3287 - 37 (white)
deleted:docs/content/3.manual/manual.yml-3303 removed
1---2headline: jq Manual (development version)34history: |56 *For released versions, see [jq 1.6](/jq/manual/v1.6),7 [jq 1.5](/jq/manual/v1.5), [jq 1.4](/jq/manual/v1.4)8 or [jq 1.3](/jq/manual/v1.3).*910body: |1112 A jq program is a "filter": it takes an input, and produces 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.1617 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.2021 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.2627 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.3435 But that's getting ahead of ourselves. :) Let's start with something36 simpler:3738manpage_intro: |39 jq(1) -- Command-line JSON processor40 ====================================4142 ## SYNOPSIS4344 `jq` [<options>...] <filter> [<files>...]4546 `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.5051 `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.5657 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.6162 ## FILTERS6364manpage_epilogue: |65 ## BUGS6667 Presumably. Report them or discuss them at:6869 https://github.com/stedolan/jq/issues7071 ## AUTHOR7273 Stephen Dolan `<mu@netsoc.tcd.ie>`7475sections:76 - title: Invoking jq77 body: |7879 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.8485 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.9596 You can affect how jq reads and writes its input and output97 using some command-line options:9899 * `--version`:100101 Output the jq version and exit with zero.102103 * `--seq`:104105 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.113114 * `--stream`:115116 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"]`.120121 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.124125 * `--slurp`/`-s`:126127 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.130131 * `--raw-input`/`-R`:132133 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.137138 * `--null-input`/`-n`:139140 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.143144 * `--compact-output` / `-c`:145146 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.149150 * `--tab`:151152 Use a tab for each indentation level instead of two spaces.153154 * `--indent n`:155156 Use the given number of spaces (no more than 8) for indentation.157158 * `--color-output` / `-C` and `--monochrome-output` / `-M`:159160 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`.163164 Colors can be configured with the `JQ_COLORS` environment165 variable (see below).166167 * `--ascii-output` / `-a`:168169 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.174175 * `--unbuffered`176177 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).180181 * `--sort-keys` / `-S`:182183 Output the fields of each object with the keys in sorted order.184185 * `--raw-output` / `-r`:186187 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.191192 * `--join-output` / `-j`:193194 Like `-r` but jq won't print a newline after each output.195196 * `-f filename` / `--from-file filename`:197198 Read filter from the file rather than from a command line, like199 awk's -f option. You can also use '#' to make comments.200201 * `-Ldirectory` / `-L directory`:202203 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.206207 * `-e` / `--exit-status`:208209 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.215216 Another way to set the exit status is with the `halt_error`217 builtin function.218219 * `--arg name value`:220221 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"`.226227 Named arguments are also available to the jq program as228 `$ARGS.named`.229230 * `--argjson name JSON-text`:231232 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`.235236 * `--slurpfile variable-name filename`:237238 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`.243244 * `--rawfile variable-name filename`:245246 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`.250251 * `--argfile variable-name filename`:252253 Do not use. Use `--slurpfile` instead.254255 (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`.)258259 * `--args`:260261 Remaining arguments are positional string arguments. These are262 available to the jq program as `$ARGS.positional[]`.263264 * `--jsonargs`:265266 Remaining arguments are positional JSON text arguments. These267 are available to the jq program as `$ARGS.positional[]`.268269 * `--run-tests [filename]`:270271 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.280281 Be warned that this option can change backwards-incompatibly.282283 - title: Basic filters284 entries:285 - title: "Identity: `.`"286 body: |287288 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.291292 Since jq by default pretty-prints all output, this trivial293 program can be a useful way of formatting JSON output from,294 say, `curl`.295296 examples:297 - program: '.'298 input: '"Hello, world!"'299 output: ['"Hello, world!"']300301 - title: "Object Identifier-Index: `.foo`, `.foo.bar`"302 body: |303304 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.307308 A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.309310 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.313314 If the key contains special characters, you need to surround315 it with double quotes like this: `."foo$"`, or else `.["foo$"]`.316317 For example `.["foo::bar"]` and `.["foo.bar"]` work while318 `.foo::bar` does not, and `.foo.bar` means `.["foo"].["bar"]`.319320 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]330331 - title: "Optional Object Identifier-Index: `.foo?`"332 body: |333334 Just like `.foo`, but does not output even an error when `.`335 is not an array or an object.336337 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: ['[]']350351 - title: "Generic Object Index: `.[<string>]`"352 body: |353354 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).357358 - title: "Array Index: `.[2]`"359 body: |360361 When the index value is an integer, `.[<value>]` can index362 arrays. Arrays are zero-based, so `.[2]` returns the third363 element.364365 Negative indices are allowed, with -1 referring to the last366 element, -2 referring to the next to last element, and so on.367368 examples:369 - program: '.[0]'370 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'371 output: ['{"name":"JSON", "good":true}']372373 - program: '.[2]'374 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'375 output: ['null']376377 - program: '.[-2]'378 input: '[1,2,3]'379 output: ['2']380381 - title: "Array/String Slice: `.[10:15]`"382 body: |383384 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).391392 examples:393 - program: '.[2:4]'394 input: '["a","b","c","d","e"]'395 output: ['["c", "d"]']396397 - program: '.[2:4]'398 input: '"abcdefghi"'399 output: ['"cd"']400401 - program: '.[:3]'402 input: '["a","b","c","d","e"]'403 output: ['["a", "b", "c"]']404405 - program: '.[-2:]'406 input: '["a","b","c","d","e"]'407 output: ['["d", "e"]']408409 - title: "Array/Object Value Iterator: `.[]`"410 body: |411412 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.417418 You can also use this on an object, and it will return all419 the values of the object.420421 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}'427428 - program: '.[]'429 input: '[]'430 output: []431432 - program: '.[]'433 input: '{"a": 1, "b": 1}'434 output: ['1', '1']435436 - title: "`.[]?`"437 body: |438439 Like `.[]`, but no errors will be output if . is not an array440 or object.441442 - title: "Comma: `,`"443 body: |444445 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.452453 examples:454 - program: '.foo, .bar'455 input: '{"foo": 42, "bar": "something else", "baz": true}'456 output: ['42', '"something else"']457458 - program: ".user, .projects[]"459 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'460 output: ['"stedolan"', '"jq"', '"wikiflow"']461462 - program: '.[4,2]'463 input: '["a","b","c","d","e"]'464 output: ['"e"', '"c"']465466 - title: "Pipe: `|`"467 body: |468469 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.473474 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.478479 Note that `.a.b.c` is the same as `.a | .b | .c`.480481 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.485486 examples:487 - program: '.[] | .name'488 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'489 output: ['"JSON"', '"XML"']490491 - title: "Parenthesis"492 body: |493494 Parenthesis work as a grouping operator just as in any typical495 programming language.496497 examples:498 - program: '(. + 2) * 5'499 input: '1'500 output: [15]501502 - title: Types and Values503 body: |504505 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".508509 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.514515 entries:516 - title: "Array construction: `[]`"517 body: |518519 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]`)526527 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).532533 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.536537 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]']544545 - title: "Object Construction: `{}`"546 body: |547548 Like JSON, `{}` is for constructing objects (aka549 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.550551 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}`.557558 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).562563 {foo: .bar}564565 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 write570571 {user: .user, title: .title}572573 Because that is so common, there's a shortcut syntax for it:574 `{user, title}`.575576 If one of the expressions produces multiple results,577 multiple dictionaries will be produced. If the input's578579 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}580581 then the expression582583 {user, title: .titles[]}584585 will produce two outputs:586587 {"user":"stedolan", "title": "JQ Primer"}588 {"user":"stedolan", "title": "More JQ"}589590 Putting parentheses around the key means it will be evaluated as an591 expression. With the same input as above,592593 {(.user): .titles}594595 produces596597 {"stedolan": ["JQ Primer", "More JQ"]}598599 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,602603 "f o o" as $foo | "b a r" as $bar | {$foo, $bar:$foo}604605 produces606607 {"f o o":"f o o","b a r":"f o o"}608609 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"]}']618619 - title: "Recursive Descent: `..`"620 body: |621622 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" `.`.628629 This is particularly useful in conjunction with `path(EXP)`630 (also see below) and the `?` operator.631632 examples:633 - program: '..|.a?'634 input: '[[{"a":1}]]'635 output: ['1']636637 - title: Builtin operators and functions638 body: |639640 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.645646 entries:647 - title: "Addition: `+`"648 body: |649650 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:653654 - **Numbers** are added by normal arithmetic.655656 - **Arrays** are added by being concatenated into a larger array.657658 - **Strings** are added by being joined into a larger string.659660 - **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.)665666 `null` can be added to any value, and returns the other667 value unchanged.668669 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}']685686 - title: "Subtraction: `-`"687 body: |688689 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.692693 examples:694 - program: '4 - .a'695 input: '{"a":3}'696 output: ['1']697 - program: . - ["xml", "yaml"]698 input: '["xml", "yaml", "json"]'699 output: ['["json"]']700701 - title: "Multiplication, division, modulo: `*`, `/`, and `%`"702 body: |703704 These infix operators behave as expected when given two numbers.705 Division by zero raises an error. `x % y` computes x modulo y.706707 Multiplying a string by a number produces the concatenation of708 that string that many times. `"x" * 0` produces **null**.709710 Dividing a string by another splits the first using the second711 as separators.712713 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.717718 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']731732733 - title: "`length`"734 body: |735736 The builtin function `length` gets the length of various737 different types of value:738739 - 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).742743 - The length of an **array** is the number of elements.744745 - The length of an **object** is the number of key-value pairs.746747 - The length of **null** is zero.748749 examples:750 - program: '.[] | length'751 input: '[[1,2], "string", {"a":2}, null]'752 output: [2, 6, 1, 0]753754755 - title: "`utf8bytelength`"756 body: |757758 The builtin function `utf8bytelength` outputs the number of759 bytes used to encode a string in UTF-8.760761 examples:762 - program: 'utf8bytelength'763 input: '"\u03bc"'764 output: [2]765766 - title: "`keys`, `keys_unsorted`"767 body: |768769 The builtin function `keys`, when given an object, returns770 its keys in an array.771772 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.777778 When `keys` is given an array, it returns the valid indices779 for that array: the integers from 0 to length-1.780781 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.784785 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]']792793 - title: "`has(key)`"794 body: |795796 The builtin function `has` returns whether the input object797 has the given key, or the input array has an element at the798 given index.799800 `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.803804 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]']811812 - title: "`in`"813 body: |814815 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`.819820 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]']827828 - title: "`map(x)`, `map_values(x)`"829 body: |830831 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.834835 Similarly, `map_values(x)` will run that filter for each element,836 but it will return an object when an object is passed.837838 `map(x)` is equivalent to `[.[] | x]`. In fact, this is how839 it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`.840841 examples:842 - program: 'map(.+1)'843 input: '[1,2,3]'844 output: ['[2,3,4]']845846 - program: 'map_values(.+1)'847 input: '{"a": 1, "b": 2, "c": 3}'848 output: ['{"a": 2, "b": 3, "c": 4}']849850 - title: "`path(path_expression)`"851 body: |852853 Outputs array representations of the given path expression854 in `.`. The outputs are arrays of strings (object keys)855 and/or numbers (array indices).856857 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.861862 `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.865866 `path(pattern)` will produce array representations of the867 paths matching `pattern` if the paths exist in `.`.868869 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.873874 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"]]']881882 - title: "`del(path_expression)`"883 body: |884885 The builtin function `del` removes a key and its corresponding886 value from an object.887888 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"]']895896 - title: "`getpath(PATHS)`"897 body: |898899 The builtin function `getpath` outputs the values in `.` found900 at each path in `PATHS`.901902 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]']909910 - title: "`setpath(PATHS; VALUE)`"911 body: |912913 The builtin function `setpath` sets the `PATHS` in `.` to `VALUE`.914915 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}]']925926 - title: "`delpaths(PATHS)`"927 body: |928929 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.932933 examples:934 - program: 'delpaths([["a","b"]])'935 input: '{"a":{"b":1},"x":{"y":2}}'936 output: ['{"a":{},"x":{"y":2}}']937938 - title: "`to_entries`, `from_entries`, `with_entries`"939 body: |940941 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}`.945946 `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.951952 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}']962963964 - title: "`select(boolean_expression)`"965 body: |966967 The function `select(foo)` produces its input unchanged if968 `foo` returns true for that input, and produces no output969 otherwise.970971 It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`972 will give you `[2,3]`.973974 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}']981982983 - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"984 body: |985986 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.990991 examples:992 - program: '.[]|numbers'993 input: '[[],{},1,"foo",null,true,false]'994 output: ['1']995996 - title: "`empty`"997 body: |998999 `empty` returns no results. None at all. Not even `null`.10001001 It's useful on occasion. You'll know if you need it :)10021003 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]']10101011 - title: "`error(message)`"1012 body: |10131014 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.10171018 - title: "`halt`"1019 body: |10201021 Stops the jq program with no further outputs. jq will exit1022 with exit status `0`.10231024 - title: "`halt_error`, `halt_error(exit_code)`"1025 body: |10261027 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.10301031 The given `exit_code` (defaulting to `5`) will be jq's exit1032 status.10331034 For example, `"Error: somthing went wrong\n"|halt_error(1)`.10351036 - title: "`$__loc__`"1037 body: |10381039 Produces an object with a "file" key and a "line" key, with1040 the filename and line number where `$__loc__` occurs, as1041 values.10421043 examples:1044 - program: 'try error("\($__loc__)") catch .'1045 input: 'null'1046 output: ['"{\"file\":\"<top-level>\",\"line\":1}"']10471048 - title: "`paths`, `paths(node_filter)`, `leaf_paths`"1049 body: |10501051 `paths` outputs the paths to all the elements in its input1052 (except it does not output the empty list, representing .1053 itself).10541055 `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.10581059 `leaf_paths` is an alias of `paths(scalars)`; `leaf_paths` is1060 *deprecated* and will be removed in the next major release.10611062 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"]]']10691070 - title: "`add`"1071 body: |10721073 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).10781079 If the input is an empty array, `add` returns `null`.10801081 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"]10911092 - title: "`any`, `any(condition)`, `any(generator; condition)`"1093 body: |10941095 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`.10981099 If the input is an empty array, `any` returns `false`.11001101 The `any(condition)` form applies the given condition to the1102 elements of the input array.11031104 The `any(generator; condition)` form applies the given1105 condition to all the outputs of the given generator.11061107 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"]11171118 - title: "`all`, `all(condition)`, `all(generator; condition)`"1119 body: |11201121 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`.11241125 The `all(condition)` form applies the given condition to the1126 elements of the input array.11271128 The `all(generator; condition)` form applies the given1129 condition to all the outputs of the given generator.11301131 If the input is an empty array, `all` returns `true`.11321133 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"]11431144 - title: "`flatten`, `flatten(depth)`"1145 body: |11461147 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.11511152 `flatten(2)` is like `flatten`, but going only up to two1153 levels deep.11541155 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"}]']11681169 - title: "`range(upto)`, `range(from;upto)` `range(from;upto;by)`"1170 body: |11711172 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.11761177 The one argument form generates numbers from 0 to the given1178 number, with an increment of 1.11791180 The two argument form generates numbers from `from` to `upto`1181 with an increment of 1.11821183 The three argument form generates numbers `from` to `upto`1184 with an increment of `by`.11851186 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]']12051206 - title: "`floor`"1207 body: |12081209 The `floor` function returns the floor of its numeric input.12101211 examples:1212 - program: 'floor'1213 input: '3.14159'1214 output: ['3']12151216 - title: "`sqrt`"1217 body: |12181219 The `sqrt` function returns the square root of its numeric input.12201221 examples:1222 - program: 'sqrt'1223 input: '9'1224 output: ['3']12251226 - title: "`tonumber`"1227 body: |12281229 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.12321233 examples:1234 - program: '.[] | tonumber'1235 input: '[1, "1"]'1236 output: [1, 1]12371238 - title: "`tostring`"1239 body: |12401241 The `tostring` function prints its input as a1242 string. Strings are left unchanged, and all other values are1243 JSON-encoded.12441245 examples:1246 - program: '.[] | tostring'1247 input: '[1, "1", [1]]'1248 output: ['"1"', '"1"', '"[1]"']12491250 - title: "`type`"1251 body: |12521253 The `type` function returns the type of its argument as a1254 string, which is one of null, boolean, number, string, array1255 or object.12561257 examples:1258 - program: 'map(type)'1259 input: '[0, false, [], {}, null, "hello"]'1260 output: ['["number", "boolean", "array", "object", "null", "string"]']12611262 - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1263 body: |12641265 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.12721273 Note that division by zero raises an error.12741275 Currently most arithmetic operations operating on infinities,1276 NaNs, and sub-normals do not raise errors.12771278 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"']12851286 - title: "`sort, sort_by(path_expression)`"1287 body: |12881289 The `sort` functions sorts its input, which must be an1290 array. Values are sorted in the following order:12911292 * `null`1293 * `false`1294 * `true`1295 * numbers1296 * strings, in alphabetical order (by unicode codepoint value)1297 * arrays, in lexical order1298 * objects12991300 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.13041305 `sort` may be used to sort by a particular field of an1306 object, or by applying any jq filter.13071308 `sort_by(foo)` compares two elements by comparing the result of1309 `foo` on each element.13101311 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}]']13181319 - title: "`group_by(path_expression)`"1320 body: |13211322 `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.13261327 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.13301331 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}]]']13351336 - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1337 body: |13381339 Find the minimum or maximum element of the input array.13401341 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.13441345 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}']13521353 - title: "`unique`, `unique_by(path_exp)`"1354 body: |13551356 The `unique` function takes as input an array and produces1357 an array of the same elements, in sorted order, with1358 duplicates removed.13591360 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`.13641365 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"]']13751376 - title: "`reverse`"1377 body: |13781379 This function reverses an array.13801381 examples:1382 - program: 'reverse'1383 input: '[1,2,3,4]'1384 output: ['[4,3,2,1]']13851386 - title: "`contains(element)`"1387 body: |13881389 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.13971398 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']14141415 - title: "`indices(s)`"1416 body: |14171418 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`.14221423 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]']14331434 - title: "`index(s)`, `rindex(s)`"1435 body: |14361437 Outputs the index of the first (`index`) or last (`rindex`)1438 occurrence of `s` in the input.14391440 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']14471448 - title: "`inside`"1449 body: |14501451 The filter `inside(b)` will produce true if the input is1452 completely contained within b. It is, essentially, an1453 inversed version of `contains`.14541455 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']14711472 - title: "`startswith(str)`"1473 body: |14741475 Outputs `true` if . starts with the given string argument.14761477 examples:1478 - program: '[.[]|startswith("foo")]'1479 input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1480 output: ['[false, true, false, true, false]']14811482 - title: "`endswith(str)`"1483 body: |14841485 Outputs `true` if . ends with the given string argument.14861487 examples:1488 - program: '[.[]|endswith("foo")]'1489 input: '["foobar", "barfoo"]'1490 output: ['[false, true]']14911492 - title: "`combinations`, `combinations(n)`"1493 body: |14941495 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.14981499 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]']15061507 - title: "`ltrimstr(str)`"1508 body: |15091510 Outputs its input with the given prefix string removed, if it1511 starts with it.15121513 examples:1514 - program: '[.[]|ltrimstr("foo")]'1515 input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1516 output: ['["fo","","barfoo","bar","afoo"]']15171518 - title: "`rtrimstr(str)`"1519 body: |15201521 Outputs its input with the given suffix string removed, if it1522 ends with it.15231524 examples:1525 - program: '[.[]|rtrimstr("foo")]'1526 input: '["fo", "foo", "barfoo", "foobar", "foob"]'1527 output: ['["fo","","bar","foobar","foob"]']15281529 - title: "`explode`"1530 body: |15311532 Converts an input string into an array of the string's1533 codepoint numbers.15341535 examples:1536 - program: 'explode'1537 input: '"foobar"'1538 output: ['[102,111,111,98,97,114]']15391540 - title: "`implode`"1541 body: |15421543 The inverse of explode.15441545 examples:1546 - program: 'implode'1547 input: '[65, 66, 67]'1548 output: ['"ABC"']15491550 - title: "`split(str)`"1551 body: |15521553 Splits an input string on the separator argument.15541555 examples:1556 - program: 'split(", ")'1557 input: '"a, b,c,d, e, "'1558 output: ['["a","b,c,d","e",""]']15591560 - title: "`join(str)`"1561 body: |15621563 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.15671568 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.15711572 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"']15791580 - title: "`ascii_downcase`, `ascii_upcase`"1581 body: |15821583 Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1584 converted to the specified case.15851586 example:1587 - program: 'ascii_upcase'1588 input: '"useful but not for é"'1589 output: '"USEFUL BUT NOT FOR é"'15901591 - title: "`while(cond; update)`"1592 body: |15931594 The `while(cond; update)` function allows you to repeatedly1595 apply an update to `.` until `cond` is false.15961597 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.16011602 examples:1603 - program: '[while(.<100; .*2)]'1604 input: '1'1605 output: ['[1,2,4,8,16,32,64]']16061607 - title: "`until(cond; next)`"1608 body: |16091610 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).16141615 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.16191620 examples:1621 - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1622 input: '4'1623 output: ['24']162416251626 - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`, `recurse_down`"1627 body: |16281629 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:16321633 {"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": []}]}]}]}16401641 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:16451646 recurse(.children[]) | .name16471648 When called without an argument, `recurse` is equivalent to1649 `recurse(.[]?)`.16501651 `recurse(f)` is identical to `recurse(f; . != null)` and can be1652 used without concerns about recursion depth.16531654 `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)`.16591660 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.16631664 The recursive calls in `recurse` will not consume additional1665 memory whenever `f` produces at most a single output for each1666 input.16671668 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":[]}'16761677 - program: 'recurse'1678 input: '{"a":0,"b":[1]}'1679 output:1680 - '{"a":0,"b":[1]}'1681 - '0'1682 - '[1]'1683 - '1'16841685 - program: 'recurse(. * .; . < 20)'1686 input: 21687 output:1688 - 21689 - 41690 - 1616911692 - title: "`walk(f)`"1693 body: |16941695 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.17061707 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]]'17121713 - program: 'walk( if type == "object" then with_entries( .key |= sub( "^_+"; "") ) else . end )'1714 input: '[ { "_a": { "__b": 2 } } ]'1715 output:1716 - '[{"a":{"b":2}}]'17171718 - title: "`$ENV`, `env`"1719 body: |17201721 `$ENV` is an object representing the environment variables as1722 set when the jq program started.17231724 `env` outputs an object representing jq's current environment.17251726 At the moment there is no builtin for setting environment1727 variables.17281729 examples:1730 - program: '$ENV.PAGER'1731 input: 'null'1732 output: ['"less"']17331734 - program: 'env.PAGER'1735 input: 'null'1736 output: ['"less"']17371738 - title: "`transpose`"1739 body: |17401741 Transpose a possibly jagged matrix (an array of arrays).1742 Rows are padded with nulls so the result is always rectangular.17431744 examples:1745 - program: 'transpose'1746 input: '[[1], [2,3]]'1747 output: ['[[1,2],[null,3]]']17481749 - title: "`bsearch(x)`"1750 body: |17511752 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.17601761 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]']17711772 - title: "String interpolation - `\\(foo)`"1773 body: |17741775 Inside a string, you can put an expression inside parens1776 after a backslash. Whatever the expression returns will be1777 interpolated into the string.17781779 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"']17831784 - title: "Convert to/from JSON"1785 body: |17861787 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.17911792 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"]]']18021803 - title: "Format strings and escaping"1804 body: |18051806 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:18101811 * `@text`:18121813 Calls `tostring`, see that function for details.18141815 * `@json`:18161817 Serializes the input as JSON.18181819 * `@html`:18201821 Applies HTML/XML escaping, by mapping the characters1822 `<>&'"` to their entity equivalents `&lt;`, `&gt;`,1823 `&amp;`, `&apos;`, `&quot;`.18241825 * `@uri`:18261827 Applies percent-encoding, by mapping all reserved URI1828 characters to a `%XX` sequence.18291830 * `@csv`:18311832 The input must be an array, and it is rendered as CSV1833 with double quotes for strings, and quotes escaped by1834 repetition.18351836 * `@tsv`:18371838 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.18451846 * `@sh`:18471848 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.18511852 * `@base64`:18531854 The input is converted to base64 as specified by RFC 4648.18551856 * `@base64d`:18571858 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.18601861 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,18661867 @uri "https://www.google.com/search?q=\(.search)"18681869 will produce the following output for the input1870 `{"search":"what is jq?"}`:18711872 "https://www.google.com/search?q=what%20is%20jq%3F"18731874 Note that the slashes, question mark, etc. in the URL are1875 not escaped, as they were part of the string literal.18761877 examples:1878 - program: '@html'1879 input: '"This works if x < y"'1880 output: ['"This works if x &lt; y"']18811882# - program: '@html "<span>Anonymous said: \(.)</span>"'1883# input: '"<script>alert(\"lol hax\");</script>"'1884# output: ["<span>Anonymous said: &lt;script&gt;alert(&quot;lol hax&quot;);&lt;/script&gt;</span>"]18851886 - program: '@sh "echo \(.)"'1887 input: "\"O'Hara's Ale\""1888 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]18891890 - program: '@base64'1891 input: '"This is a message"'1892 output: ['"VGhpcyBpcyBhIG1lc3NhZ2U="']18931894 - program: '@base64d'1895 input: '"VGhpcyBpcyBhIG1lc3NhZ2U="'1896 output: ['"This is a message"']18971898 - title: "Dates"1899 body: |19001901 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.19041905 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.19091910 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.19141915 The `todate` builtin is an alias for `todateiso8601`.19161917 The `now` builtin outputs the current time, in seconds since1918 the Unix epoch.19191920 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.19271928 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.19371938 The `localtime` builtin works like the `gmtime` builtin, but1939 using the local timezone setting.19401941 The `mktime` builtin consumes "broken down time"1942 representations of time output by `gmtime` and `strptime`.19431944 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`.19471948 The `strftime(fmt)` builtin formats a time (GMT) with the1949 given format. The `strflocaltime` does the same, but using1950 the local timezone setting.19511952 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"`.19551956 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.19591960 examples:1961 - program: 'fromdate'1962 input: '"2015-03-05T23:51:47Z"'1963 output: ['1425599507']19641965 - 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]']19681969 - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'1970 input: '"2015-03-05T23:51:47Z"'1971 output: ['1425599507']19721973 - title: "SQL-Style Operators"1974 body: |19751976 jq provides a few SQL-style operators.19771978 * INDEX(stream; index_expression):19791980 This builtin produces an object whose keys are computed by1981 the given index expression applied to each value from the1982 given stream.19831984 * JOIN($idx; stream; idx_expr; join_expr):19851986 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.19921993 * JOIN($idx; stream; idx_expr):19941995 Same as `JOIN($idx; stream; idx_expr; .)`.19961997 * JOIN($idx; idx_expr):19981999 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.20022003 * IN(s):20042005 This builtin outputs `true` if `.` appears in the given2006 stream, otherwise it outputs `false`.20072008 * IN(source; s):20092010 This builtin outputs `true` if any value in the source stream2011 appears in the second stream, otherwise it outputs `false`.20122013 - title: "`builtins`"2014 body: |20152016 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.20202021 - title: Conditionals and Comparisons2022 entries:2023 - title: "`==`, `!=`"2024 body: |20252026 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.20322033 != is "not equal", and 'a != b' returns the opposite value of 'a == b'20342035 examples:2036 - program: '.[] == 1'2037 input: '[1, 1.0, "1", "banana"]'2038 output: ['true', 'true', 'false', 'false']20392040 - title: if-then-else2041 body: |20422043 `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.20462047 `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 `.`.20502051 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.20572058 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.20612062 More cases can be added to an if using `elif A then B` syntax.20632064 examples:2065 - program: 'if . == 0 then2066 "zero"2067 elif . == 1 then2068 "one"2069 else2070 "many"2071 end'2072 input: 22073 output: ['"many"']20742075 - title: "`>, >=, <=, <`"2076 body: |20772078 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).20822083 The ordering is the same as that described for `sort`, above.20842085 examples:2086 - program: '. < 5'2087 input: 22088 output: ['true']20892090 - title: and/or/not2091 body: |20922093 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".20962097 If an operand of one of these operators produces multiple2098 results, the operator itself will produce a result for each input.20992100 `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`.21042105 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.21112112 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]']21282129 - title: "Alternative operator: `//`"2130 body: |21312132 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`.21352136 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).21412142 examples:2143 - program: '.foo // 42'2144 input: '{"foo": 19}'2145 output: [19]2146 - program: '.foo // 42'2147 input: '{}'2148 output: [42]21492150 - title: try-catch2151 body: |21522153 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.21582159 The `try EXP` form uses `empty` as the exception handler.21602161 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"']21712172 - title: Breaking out of control structures2173 body: |21742175 A convenient use of try/catch is to break out of control2176 structures like `reduce`, `foreach`, `while`, and so on.21772178 For example:21792180 # 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;21842185 jq has a syntax for named lexical labels to "break" or "go (back) to":21862187 label $out | ... break $out ...21882189 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`.21922193 The relationship between the `break` and corresponding `label`2194 is lexical: the label has to be "visible" from the break.21952196 To break out of a `reduce`, for example:21972198 label $out | reduce .[] as $item (null; if .==false then break $out else ... end)21992200 The following jq program produces a syntax error:22012202 break $out22032204 because no label `$out` is visible.22052206 - title: "Error Suppression / Optional Operator: `?`"2207 body: |22082209 The `?` operator, used as `EXP?`, is shorthand for `try EXP`.22102211 examples:2212 - program: '[.[]|(.a)?]'2213 input: '[{}, true, {"a":1}]'2214 output: ['[null, 1]']221522162217 - title: Regular expressions (PCRE)2218 body: |22192220 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.22232224 The jq regex filters are defined so that they can be used using2225 one of these patterns:22262227 STRING | FILTER( REGEX )2228 STRING | FILTER( REGEX; FLAGS )2229 STRING | FILTER( [REGEX] )2230 STRING | FILTER( [REGEX, FLAGS] )22312232 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.22362237 FLAGS is a string consisting of one of more of the supported flags:22382239 * `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)22472248 To match whitespace in an x pattern use an escape such as \s, e.g.22492250 * test( "a\\sb", "x" ).22512252 Note that certain flags may also be specified within REGEX, e.g.22532254 * jq -n '("test", "TEst", "teST", "TEST") | test( "(?i)te(?-i)st" )'22552256 evaluates to: true, true, false, false.22572258 entries:2259 - title: "`test(val)`, `test(regex; flags)`"2260 body: |22612262 Like `match`, but does not return match objects, only `true` or `false`2263 for whether or not the regex matches the input.22642265 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']22722273 - title: "`match(val)`, `match(regex; flags)`"2274 body: |22752276 **match** outputs an object for each match it finds. Matches have2277 the following fields:22782279 * `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.22832284 Capturing group objects have the following fields:22852286 * `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)22902291 Capturing groups that did not match anything return an offset of -122922293 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"}]}'23122313 - program: '[ match("."; "g")] | length'2314 input: '"abc"'2315 output: [3]231623172318 - title: "`capture(val)`, `capture(regex; flags)`"2319 body: |23202321 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.23242325 examples:2326 - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2327 input: '"xyzzy-14"'2328 output: ['{ "a": "xyzzy", "n": "14" }']23292330 - title: "`scan(regex)`, `scan(regex; flags)`"2331 body: |23322333 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) ]`.23382339 example:2340 - program: 'scan("c")'2341 input: '"abcdefabc"'2342 output: ['"c"', '"c"']23432344 - program: 'scan("b")'2345 input: ("", "")2346 output: ['[]', '[]']23472348 - title: "`split(regex; flags)`"2349 body: |23502351 For backwards compatibility, `split` splits on a string, not a regex.23522353 example:2354 - program: 'split(", *"; null)'2355 input: '"ab,cd, ef"'2356 output: ['"ab","cd","ef"']235723582359 - title: "`splits(regex)`, `splits(regex; flags)`"2360 body: |23612362 These provide the same results as their `split` counterparts,2363 but as a stream instead of an array.23642365 example:2366 - program: 'splits(", *")'2367 input: '("ab,cd", "ef, gh")'2368 output: ['"ab"', '"cd"', '"ef"', '"gh"']23692370 - title: "`sub(regex; tostring)` `sub(regex; string; flags)`"2371 body: |23722373 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)".23792380 example:2381 - program: 'sub("^[^a-z]*(?<x>[a-z]*).*")'2382 input: '"123abc456"'2383 output: '"ZabcZabc"'238423852386 - title: "`gsub(regex; string)`, `gsub(regex; string; flags)`"2387 body: |23882389 `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2390 replaced by the string, after interpolation.23912392 example:2393 - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2394 input: '"Abcabc"'2395 output: '"+A-+a-"'239623972398 - title: Advanced features2399 body: |2400 Variables are an absolute necessity in most programming languages, but2401 they're relegated to an "advanced feature" in jq.24022403 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.24092410 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).24142415 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.24182419 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.24222423 Some minimal I/O support (besides reading JSON from standard2424 input, and writing JSON to standard output) is available.24252426 Finally, there is a module/library system.24272428 entries:2429 - title: "Variable / Symbolic Binding Operator: `... as $identifier | ...`"2430 body: |24312432 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.24382439 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.24452446 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:24512452 length as $array_length | add / $array_length24532454 We'll need a more complicated problem to find a situation where using2455 variables actually makes our lives easier.245624572458 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:24612462 {"posts": [{"title": "Frist psot", "author": "anon"},2463 {"title": "A well-written article", "author": "person1"}],2464 "realnames": {"anon": "Anonymous Coward",2465 "person1": "Person McPherson"}}24662467 We want to produce the posts with the author field containing a real2468 name, as in:24692470 {"title": "Frist psot", "author": "Anonymous Coward"}2471 {"title": "A well-written article", "author": "Person McPherson"}24722473 We use a variable, $names, to store the realnames object, so that we2474 can refer to it later when looking up author usernames:24752476 .realnames as $names | .posts[] | {title, author: $names[.author]}24772478 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.24822483 Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2484 `{$foo}` is a handy way of writing `{foo:$foo}`.24852486 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"):24892490 . as {realnames: $names, posts: [$first, $second]} | ...24912492 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.24972498 Variables are scoped over the rest of the expression that defines2499 them, so25002501 .realnames as $names | (.posts[] | {title, author: $names[.author]})25022503 will work, but25042505 (.realnames as $names | .posts[]) | {title, author: $names[.author]}25062507 won't.25082509 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.25142515 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}']25282529 - 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.25342535 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:25452546 .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$user_id, $ts}]} | {$user_id, $kind, $id, $ts}25472548 Or, if we aren't sure if the input is an array of values or an object:25492550 .[] as [$id, $kind, $user_id, $ts] ?// {$id, $kind, $user_id, $ts} | ...25512552 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`:25552556 .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}25572558 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.25612562 [[3]] | .[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end25632564 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}']25742575 - title: 'Defining Functions'2576 body: |25772578 You can give a filter a name using "def" syntax:25792580 def increment: . + 1;25812582 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:25852586 def map(f): [.[] | f];25872588 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:25942595 def foo(f): f|f;2596 5|foo(.*2)25972598 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.26032604 If you want the value-argument behaviour for defining simple2605 functions, you can just use a variable:26062607 def addvalue(f): f as $f | map(. + $f);26082609 Or use the short-hand:26102611 def addvalue($f): ...;26122613 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.26182619 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.26242625 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]]']26322633 - title: 'Scoping'2634 body: |26352636 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.26422643 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.26492650 - title: Reduce2651 body: |26522653 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:26562657 reduce .[] as $item (0; . + $item)26582659 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:26632664 0 | (3 as $item | . + $item) |2665 (2 as $item | . + $item) |2666 (1 as $item | . + $item)26672668 examples:2669 - program: 'reduce .[] as $item (0; . + $item)'2670 input: '[10,2,5,3]'2671 output: ['20']26722673 - title: "`isempty(exp)`"2674 body: |26752676 Returns true if `exp` produces no outputs, false otherwise.26772678 examples:2679 - program: 'isempty(empty)'2680 input: 'null'2681 output: ['true']26822683 - title: "`limit(n; exp)`"2684 body: |26852686 The `limit` function extracts up to `n` outputs from `exp`.26872688 examples:2689 - program: '[limit(3;.[])]'2690 input: '[0,1,2,3,4,5,6,7,8,9]'2691 output: ['[0,1,2]']26922693 - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"2694 body: |26952696 The `first(expr)` and `last(expr)` functions extract the first2697 and last values from `expr`, respectively.26982699 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`.27032704 examples:2705 - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'2706 input: '10'2707 output: ['[0,9,5]']27082709 - title: "`first`, `last`, `nth(n)`"2710 body: |27112712 The `first` and `last` functions extract the first2713 and last values from any array at `.`.27142715 The `nth(n)` function extracts the nth value of any array at `.`.27162717 examples:2718 - program: '[range(.)]|[first, last, nth(5)]'2719 input: '10'2720 output: ['[0,9,5]']27212722 - title: "`foreach`"2723 body: |27242725 The `foreach` syntax is similar to `reduce`, but intended to2726 allow the construction of `limit` and reducers that produce2727 intermediate results (see example).27282729 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`.27362737 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).27402741 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"]]']27482749 - title: Recursion2750 body: |27512752 As described above, `recurse` uses recursion, and any jq2753 function can be recursive. The `while` builtin is also2754 implemented in terms of recursion.27552756 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.27602761 For example:27622763 def recurse(f): def r: ., (f | select(. != null) | r); r;27642765 def while(cond; update):2766 def _while:2767 if cond then ., (update | _while) else empty end;2768 _while;27692770 def repeat(exp):2771 def _repeat:2772 exp, _repeat;2773 _repeat;27742775 - title: Generators and iterators2776 body: |27772778 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.27852786 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.27902791 The `empty` builtin is the generator that produces zero2792 outputs. The `empty` builtin backtracks to the preceding2793 generator expression.27942795 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.28032804 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]']28222823 - title: 'Math'2824 body: |28252826 jq currently only has IEEE754 double-precision (64-bit) floating2827 point number support.28282829 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 `.`.28372838 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.28422843 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`.28492850 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`.28532854 Three-input C math functions: `fma`.28552856 See your system's manual for more information on each of these.28572858 - title: 'I/O'2859 body: |28602861 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.28672868 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.28752876 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.28792880 entries:2881 - title: "`input`"2882 body: |28832884 Outputs one new input.28852886 - title: "`inputs`"2887 body: |28882889 Outputs all remaining inputs, one by one.28902891 This is primarily useful for reductions over a program's2892 inputs.28932894 - title: "`debug`"2895 body: |28962897 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.29012902 - title: "`stderr`"2903 body: |29042905 Prints its input in raw and compact mode to stderr with no2906 additional decoration, not even a newline.29072908 - title: "`input_filename`"2909 body: |29102911 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.29142915 - title: "`input_line_number`"2916 body: |29172918 Returns the line number of the input currently being filtered.29192920 - title: 'Streaming'2921 body: |29222923 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.29282929 However, streaming isn't easy to deal with as the jq program will2930 have `[<path>, <leaf-value>]` (and a few other forms) as inputs.29312932 Several builtins are provided to make handling streams easier.29332934 The examples below use the streamed form of `[0,[1]]`, which is2935 `[[0],0],[[1,0],1],[[1,0]],[[1]]`.29362937 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.29422943 entries:2944 - title: "`truncate_stream(stream_expression)`"2945 body: |29462947 Consumes a number as input and truncates the corresponding2948 number of path elements from the left of the outputs of the2949 given streaming expression.29502951 examples:2952 - program: '[1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]'2953 input: '1'2954 output: ['[[[0],2],[[0]]]']29552956 - title: "`fromstream(stream_expression)`"2957 body: |29582959 Outputs values corresponding to the stream expression's2960 outputs.29612962 examples:2963 - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'2964 input: 'null'2965 output: ['[2]']29662967 - title: "`tostream`"2968 body: |29692970 The `tostream` builtin outputs the streamed form of its input.29712972 examples:2973 - program: '. as $dot|fromstream($dot|tostream)|.==$dot'2974 input: '[0,[1,{"a":1},{"b":2}]]'2975 output: ['true']29762977 - 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".29842985 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).29932994 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.29982999 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.30023003 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.30113012 Most users will want to use modification assignment operators,3013 such as `|=` or `+=`, rather than `=`.30143015 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.30193020 Note too that `.a,.b=0` does not set `.a` and `.b`, but3021 `(.a,.b)=0` sets both.30223023 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.30323033 The left-hand side can be any general path expression; see `path()`.30343035 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.30393040 If the right-hand side outputs no values (i.e., `empty`), then3041 the left-hand side path will be deleted, as with `del(path)`.30423043 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).30463047 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]]']30513052 - title: "Arithmetic update-assignment: `+=`, `-=`, `*=`, `/=`, `%=`, `//=`"3053 body: |30543055 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`.30583059 examples:3060 - program: .foo += 13061 input: '{"foo": 42}'3062 output: ['{"foo": 43}']30633064 - title: "Plain assignment: `=`"3065 body: |30663067 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).30723073 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.30793080 This example should show the difference between '=' and '|=':30813082 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:30833084 .a = .b30853086 .a |= .b30873088 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}.30923093 Another example of the difference between '=' and '|=':30943095 null|(.a,.b)=range(3)30963097 outputs '{"a":0,"b":0}', '{"a":1,"b":1}', and '{"a":2,"b":2}',3098 while30993100 null|(.a,.b)|=range(3)31013102 outputs just '{"a":0,"b":0}'.31033104 - 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:31103111 .posts[0].title = "JQ Manual"31123113 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:31163117 .posts[].comments |= . + ["this is great"]31183119 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).31223123 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.31293130 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:31343135 .posts[] | select(.author == "stedolan")31363137 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:31403141 (.posts[] | select(.author == "stedolan") | .comments) |=3142 . + ["terrible."]31433144 - title: Modules3145 body: |31463147 jq has a library/module system. Modules are files whose names end3148 in `.jq`.31493150 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.31533154 Paths in the a search path are subject to various substitutions.31553156 For paths starting with "~/", the user's home directory is3157 substituted for "~".31583159 For paths starting with "$ORIGIN/", the path of the jq executable3160 is substituted for "$ORIGIN".31613162 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.31653166 Import directives can optionally specify a search path to which3167 the default is appended.31683169 The default search path is the search path given to the `-L`3170 command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",3171 "$ORIGIN/../lib"]`.31723173 Null and empty string path elements terminate search path3174 processing.31753176 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.31813182 Consecutive components with the same name are not allowed to avoid3183 ambiguities (e.g., "foo/foo").31843185 For example, with `-L$HOME/.jq` a module `foo` can be found in3186 `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.31873188 If "$HOME/.jq" is a file, it is sourced into the main program.31893190 entries:3191 - title: "`import RelativePathString as NAME [<metadata>];`"3192 body: |31933194 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::".31983199 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.32043205 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.32083209 - title: "`include RelativePathString [<metadata>];`"3210 body: |32113212 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.32173218 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.32233224 - title: "`import RelativePathString as $NAME [<metadata>];`"3225 body: |32263227 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`.32313232 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.32373238 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.32413242 - title: "`module <metadata>;`"3243 body: |32443245 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.32483249 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.32533254 - title: "`modulemeta`"3255 body: |32563257 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.32603261 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.32643265 - title: Colors3266 body: |32673268 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:32713272 - color for `null`3273 - color for `false`3274 - color for `true`3275 - color for numbers3276 - color for strings3277 - color for arrays3278 - color for objects32793280 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"`.32823283 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:32863287 - 1 (bright)3288 - 2 (dim)3289 - 4 (underscore)3290 - 5 (blink)3291 - 7 (reverse)3292 - 8 (hidden)32933294 and the second is one of these:32953296 - 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
1headline: Download jq2body:34 - text: |56 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.910 The binaries should just run, but on OS X and Linux you may need11 to make them executable first using `chmod +x jq`.1213 jq is licensed under the MIT license. For all of the gory14 details, read the file `COPYING` in the source distribution.151617 ### Linux1819 * 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`.2223 * jq 1.5 is in the official24 [Fedora](http://pkgs.fedoraproject.org/cgit/jq.git/) repository.25 Install using `sudo dnf install jq`.2627 * jq 1.4 is in the official [openSUSE](https://software.opensuse.org/package/jq)28 repository. Install using `sudo zypper install jq`.2930 * 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`.3334 * 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).3839 * 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).4344 * 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).4849 * 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).5354 ### OS X5556 * Use [Homebrew](http://brew.sh/) to install jq 1.5 with57 `brew install jq`.5859 * jq 1.6 binary for60 [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.6/jq-osx-amd64).6162 * jq 1.5 binary for63 [64-bit](https://github.com/stedolan/jq/releases/download/jq-1.5/jq-osx-amd64).6465 * 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).6970 * 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).7475 ### FreeBSD7677 * `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).7980 * `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.8485 ### Solaris8687 * `pkgutil -i jq` in [OpenCSW](https://www.opencsw.org/p/jq) for Solaris88 10+, Sparc and x86.8990 * 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).9495 ### Windows9697 * Use [Chocolatey NuGet](https://chocolatey.org/) to install jq 1.5 with98 `chocolatey install jq`.99100 * 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).104105 * 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).109110 * 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).114115 * 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).119120 ### Checksums and signatures121122 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).129130 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`.140141 ### From source on Linux, OS X, Cygwin, and other POSIX-like operating systems142143 * [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)145146 You can build it using the usual `./configure && make && sudo147 make install` rigmarole.148149 If you're interested in using the lastest development version, try:150151 git clone https://github.com/stedolan/jq.git152 cd jq153 autoreconf -i154 ./configure --disable-maintainer-mode155 make156 sudo make install157158 To build it from a git clone, you'll need to install a few159 packages first:160161 * [GCC](https://gcc.gnu.org)162 * [Make](https://www.gnu.org/software/make/)163 * [Autotools](https://www.gnu.org/software/automake/)164165 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.168169 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/).174175 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/).180181 #### Building the documentation182183 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`.188189 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
added:docs/content/manual/v1.3/manual.yml+1270 added
1---2headline: jq 1.3 Manual34history: |56 *The manual for the development version of jq can be found7 [here](/jq/manual).*89body: |1011 A jq program is a "filter": it takes an input, and produces an12 output. There are a lot of builtin filters for extracting a13 particular field of an object, or converting a number to a string,14 or various other standard tasks.1516 Filters can be combined in various ways - you can pipe the output of17 one filter into another filter, or collect the output of a filter18 into an array.1920 Some filters produce multiple results, for instance there's one that21 produces all the elements of its input array. Piping that filter22 into a second runs the second filter for each element of the23 array. Generally, things that would be done with loops and iteration24 in other languages are just done by gluing filters together in jq.2526 It's important to remember that every filter has an input and an27 output. Even literals like "hello" or 42 are filters - they take an28 input but always produce the same literal as output. Operations that29 combine two filters, like addition, generally feed the same input to30 both and combine the results. So, you can implement an averaging31 filter as `add / length` - feeding the input array both to the `add`32 filter and the `length` filter and dividing the results.3334 But that's getting ahead of ourselves. :) Let's start with something35 simpler:3637manpage_intro: |38 jq(1) -- Command-line JSON processor39 ====================================4041 ## SYNOPSIS4243 `jq` [<options>...] <filter> [<files>...]4445 `jq` can transform JSON in various ways, by selecting, iterating,46 reducing and otherwise mangling JSON documents. For instance,47 running the command `jq 'map(.price) | add'` will take an array of48 JSON objects as input and return the sum of their "price" fields.4950 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.5354 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.5859 ## FILTERS6061manpage_epilogue: |62 ## BUGS6364 Presumably. Report them or discuss them at:6566 https://github.com/stedolan/jq/issues6768 ## AUTHOR6970 Stephen Dolan `<mu@netsoc.tcd.ie>`7172sections:73 - title: Invoking jq74 body: |7576 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.8182 You can affect how jq reads and writes its input and output83 using some command-line options:8485 * `--slurp`/`-s`:8687 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.9091 * `--raw-input`/`-R`:9293 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.9798 * `--null-input`/`-n`:99100 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.103104 * `--compact-output` / `-c`:105106 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.109110 * `--color-output` / `-C` and `--monochrome-output` / `-M`:111112 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`.115116 * `--ascii-output` / `-a`:117118 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.123124 * `--raw-output` / `-r`:125126 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.130131 * `--arg name value`:132133 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"`.136137 - title: Basic filters138 entries:139 - title: "`.`"140 body: |141142 The absolute simplest (and least interesting) filter143 is `.`. This is a filter that takes its input and144 produces it unchanged as output.145146 Since jq by default pretty-prints all output, this trivial147 program can be a useful way of formatting JSON output from,148 say, `curl`.149150 examples:151 - program: '.'152 input: '"Hello, world!"'153 output: ['"Hello, world!"']154155 - title: "`.foo`"156 body: |157158 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.161162 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']169170 - title: "`.[foo]`, `.[2]`, `.[10:15]`"171 body: |172173 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.178179 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).185186 examples:187 - program: '.[0]'188 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'189 output: ['{"name":"JSON", "good":true}']190191 - program: '.[2]'192 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'193 output: ['null']194195 - program: '.[2:4]'196 input: '["a","b","c","d","e"]'197 output: ['["c", "d"]']198199 - program: '.[:3]'200 input: '["a","b","c","d","e"]'201 output: ['["a", "b", "c"]']202203 - program: '.[-2:]'204 input: '["a","b","c","d","e"]'205 output: ['["d", "e"]']206207 - title: "`.[]`"208 body: |209210 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.215216 You can also use this on an object, and it will return all217 the values of the object.218219 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}'225226 - program: '.[]'227 input: '[]'228 output: []229230 - program: '.[]'231 input: '{"a": 1, "b": 1}'232 output: ['1', '1']233234 - title: "`,`"235 body: |236237 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.243244 examples:245 - program: '.foo, .bar'246 input: '{"foo": 42, "bar": "something else", "baz": true}'247 output: ['42', '"something else"']248249 - program: ".user, .projects[]"250 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'251 output: ['"stedolan"', '"jq"', '"wikiflow"']252253 - program: '.[4,2]'254 input: '["a","b","c","d","e"]'255 output: ['"e"', '"c"']256257 - 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.263264 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.268269 examples:270 - program: '.[] | .name'271 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'272 output: ['"JSON"', '"XML"']273274 - title: Types and Values275 body: |276277 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".280281 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.286287 entries:288 - title: Array construction - `[]`289 body: |290291 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]`)298299 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).304305 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.308309 examples:310 - program: "[.user, .projects[]]"311 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'312 output: ['["stedolan", "jq", "wikiflow"]']313 - title: Objects - `{}`314 body: |315316 Like JSON, `{}` is for constructing objects (aka317 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.318319 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).325326 {foo: .bar}327328 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 write333334 {user: .user, title: .title}335336 Because that's so common, there's a shortcut syntax: `{user, title}`.337338 If one of the expressions produces multiple results,339 multiple dictionaries will be produced. If the input's340341 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}342343 then the expression344345 {user, title: .titles[]}346347 will produce two outputs:348349 {"user":"stedolan", "title": "JQ Primer"}350 {"user":"stedolan", "title": "More JQ"}351352 Putting parentheses around the key means it will be evaluated as an353 expression. With the same input as above,354355 {(.user): .titles}356357 produces358359 {"stedolan": ["JQ Primer", "More JQ"]}360361 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"]}']370371 - title: Builtin operators and functions372 body: |373374 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.379380 entries:381 - title: Addition - `+`382 body: |383384 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:387388 - **Numbers** are added by normal arithmetic.389390 - **Arrays** are added by being concatenated into a larger array.391392 - **Strings** are added by being joined into a larger string.393394 - **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.398399 `null` can be added to any value, and returns the other400 value unchanged.401402 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}']418419 - title: Subtraction - `-`420 body: |421422 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.425426 examples:427 - program: '4 - .a'428 input: '{"a":3}'429 output: ['1']430 - program: . - ["xml", "yaml"]431 input: '["xml", "yaml", "json"]'432 output: ['["json"]']433434 - title: Multiplication, division - `*` and `/`435 body: |436437 These operators only work on numbers, and do the expected.438439 examples:440 - program: '10 / . * 3'441 input: 5442 output: [6]443444 - title: '`length`'445 body: |446447 The builtin function `length` gets the length of various448 different types of value:449450 - 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).453454 - The length of an **array** is the number of elements.455456 - The length of an **object** is the number of key-value pairs.457458 - The length of **null** is zero.459460 examples:461 - program: '.[] | length'462 input: '[[1,2], "string", {"a":2}, null]'463 output: [2, 6, 1, 0]464465 - title: '`keys`'466 body: |467468 The builtin function `keys`, when given an object, returns469 its keys in an array.470471 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.476477 When `keys` is given an array, it returns the valid indices478 for that array: the integers from 0 to length-1.479480 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]']487488 - title: '`has`'489 body: |490491 The builtin function `has` returns whether the input object492 has the given key, or the input array has an element at the493 given index.494495 `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.498499 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]']506507 - title: '`to_entries`, `from_entries`, `with_entries`'508 body: |509510 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}`.514515 `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.519520 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}']530531532 - title: '`select`'533 body: |534535 The function `select(foo)` produces its input unchanged if536 `foo` returns true for that input, and produces no output537 otherwise.538539 It's useful for filtering lists: '`[1,2,3] | map(select(. >= 2))`'540 will give you `[3]`.541542 examples:543 - program: 'map(select(. >= 2))'544 input: '[1,5,3,0,7]'545 output: ['[5,3,7]']546547 - title: '`empty`'548 body: |549550 `empty` returns no results. None at all. Not even `null`.551552 It's useful on occasion. You'll know if you need it :)553554 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]']561562 - title: '`map(x)`'563 body: |564565 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.568569 `map(x)` is equivalent to `[.[] | x]`. In fact, this is how570 it's defined.571572 examples:573 - program: 'map(.+1)'574 input: '[1,2,3]'575 output: ['[2,3,4]']576577 - title: '`add`'578 body: |579580 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).585586 If the input is an empty array, `add` returns `null`.587588 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"]598599 - title: '`range`'600 body: |601602 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.606607 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]']614615 - title: '`tonumber`'616 body: |617618 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.621622 examples:623 - program: '.[] | tonumber'624 input: '[1, "1"]'625 output: [1, 1]626627 - title: '`tostring`'628 body: |629630 The `tostring` function prints its input as a631 string. Strings are left unchanged, and all other values are632 JSON-encoded.633634 examples:635 - program: '.[] | tostring'636 input: '[1, "1", [1]]'637 output: ['"1"', '"1"', '"[1]"']638639 - title: '`type`'640 body: |641642 The `type` function returns the type of its argument as a643 string, which is one of null, boolean, number, string, array644 or object.645646 examples:647 - program: 'map(type)'648 input: '[0, false, [], {}, null, "hello"]'649 output: ['["number", "boolean", "array", "object", "null", "string"]']650651 - title: '`sort, sort_by`'652 body: |653654 The `sort` functions sorts its input, which must be an655 array. Values are sorted in the following order:656657 * `null`658 * `false`659 * `true`660 * numbers661 * strings, in alphabetical order (by unicode codepoint value)662 * arrays, in lexical order663 * objects664665 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.669670 `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.674675 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}]']682683 - title: '`group_by`'684 body: |685686 `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.690691 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.694695 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}]]']699700 - title: '`min`, `max`, `min_by`, `max_by`'701 body: |702703 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.707708 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}']715716 - title: '`unique`'717 body: |718719 The `unique` function takes as input an array and produces720 an array of the same elements, in sorted order, with721 duplicates removed.722723 examples:724 - program: 'unique'725 input: '[1,2,5,3,5,3,1,3]'726 output: ['[1,2,3,5]']727728 - title: '`reverse`'729 body: |730731 This function reverses an array.732733 examples:734 - program: 'reverse'735 input: '[1,2,3,4]'736 output: ['[4,3,2,1]']737738 - title: '`contains`'739 body: |740741 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.749750 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']766767 - title: '`recurse`'768 body: |769770 The `recurse` function allows you to search through a771 recursive structure, and extract interesting data from all772 levels. Suppose your input represents a filesystem:773774 {"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": []}]}]}]}781782 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:786787 recurse(.children[]) | .name788789 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":[]}'797798799 - title: String interpolation - `\(foo)`800 body: |801802 Inside a string, you can put an expression inside parens803 after a backslash. Whatever the expression returns will be804 interpolated into the string.805806 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"']810811 - title: "Format strings and escaping"812 body: |813814 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:818819 * `@text`:820821 Calls `tostring`, see that function for details.822823 * `@json`:824825 Serialises the input as JSON.826827 * `@html`:828829 Applies HTML/XML escaping, by mapping the characters830 `<>&'"` to their entity equivalents `&lt;`, `&gt;`,831 `&amp;`, `&apos;`, `&quot;`.832833 * `@uri`:834835 Applies percent-encoding, by mapping all reserved URI836 characters to a `%xx` sequence.837838 * `@csv`:839840 The input must be an array, and it is rendered as CSV841 with double quotes for strings, and quotes escaped by842 repetition.843844 * `@sh`:845846 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.849850 * `@base64`:851852 The input is converted to base64 as specified by RFC 4648.853854 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,859860 @uri "https://www.google.com/search?q=\(.search)"861862 will produce the following output for the input863 `{"search":"jq!"}`:864865 https://www.google.com/search?q=jq%21866867 Note that the slashes, question mark, etc. in the URL are868 not escaped, as they were part of the string literal.869870 examples:871 - program: '@html'872 input: '"This works if x < y"'873 output: ['"This works if x &lt; y"']874875# - program: '@html "<span>Anonymous said: \(.)</span>"'876# input: '"<script>alert(\"lol hax\");</script>"'877# output: ["<span>Anonymous said: &lt;script&gt;alert(&quot;lol hax&quot;);&lt;/script&gt;</span>"]878879 - program: '@sh "echo \(.)"'880 input: "\"O'Hara's Ale\""881 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]882883 - title: Conditionals and Comparisons884 entries:885 - title: '`==`, `!=`'886 body: |887888 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.894895 != is "not equal", and 'a != b' returns the opposite value of 'a == b'896897 examples:898 - program: '.[] == 1'899 input: '[1, 1.0, "1", "banana"]'900 output: ['true', 'true', 'false', 'false']901 - title: if-then-else902 body: |903904 `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.907908 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.915916 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.919920 More cases can be added to an if using `elif A then B` syntax.921922 examples:923 - program: |-924 if . == 0 then925 "zero"926 elif . == 1 then927 "one"928 else929 "many"930 end931 input: 2932 output: ['"many"']933934 - title: '`>, >=, <=, <`'935 body: |936937 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).941942 The ordering is the same as that described for `sort`, above.943944 examples:945 - program: '. < 5'946 input: 2947 output: ['true']948949 - title: and/or/not950 body: |951952 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".955956 If an operand of one of these operators produces multiple957 results, the operator itself will produce a result for each input.958959 `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`.963964 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.970971 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]']987988 - title: Alternative operator - `//`989 body: |990991 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`.994995 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).10001001 examples:1002 - program: '.foo // 42'1003 input: '{"foo": 19}'1004 output: [19]1005 - program: '.foo // 42'1006 input: '{}'1007 output: [42]10081009 - title: Advanced features1010 body: |1011 Variables are an absolute necessity in most programming languages, but1012 they're relegated to an "advanced feature" in jq.10131014 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.10201021 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).10251026 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.10291030 entries:1031 - title: Variables1032 body: |10331034 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.10401041 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.10471048 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:10531054 length as $array_length | add / $array_length10551056 We'll need a more complicated problem to find a situation where using1057 variables actually makes our lives easier.105810591060 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:10631064 {"posts": [{"title": "Frist psot", "author": "anon"},1065 {"title": "A well-written article", "author": "person1"}],1066 "realnames": {"anon": "Anonymous Coward",1067 "person1": "Person McPherson"}}10681069 We want to produce the posts with the author field containing a real1070 name, as in:10711072 {"title": "Frist psot", "author": "Anonymous Coward"}1073 {"title": "A well-written article", "author": "Person McPherson"}10741075 We use a variable, $names, to store the realnames object, so that we1076 can refer to it later when looking up author usernames:10771078 .realnames as $names | .posts[] | {title, author: $names[.author]}10791080 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.10841085 Variables are scoped over the rest of the expression that defines1086 them, so10871088 .realnames as $names | (.posts[] | {title, author: $names[.author]})10891090 will work, but10911092 (.realnames as $names | .posts[]) | {title, author: $names[.author]}10931094 won't.10951096 examples:1097 - program: '.bar as $x | .foo | . + $x'1098 input: '{"foo":10, "bar":200}'1099 output: ['210']11001101 - title: 'Defining Functions'1102 body: |11031104 You can give a filter a name using "def" syntax:11051106 def increment: . + 1;11071108 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:11111112 def map(f): [.[] | f];11131114 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.11191120 If you want the value-argument behaviour for defining simple1121 functions, you can just use a variable:11221123 def addvalue(f): f as $value | map(. + $value);11241125 With that definition, `addvalue(.foo)` will add the current1126 input's `.foo` field to each element of the array.11271128 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]]']11351136 - title: Reduce1137 body: |11381139 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:11421143 reduce .[] as $item (0; . + $item)11441145 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:11491150 0 | (3 as $item | . + $item) |1151 (2 as $item | . + $item) |1152 (1 as $item | . + $item)11531154 examples:1155 - program: 'reduce .[] as $item (0; . + $item)'1156 input: '[10,2,5,3]'1157 output: ['20']115811591160 - title: Assignment1161 body: |11621163 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".11681169 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).11761177 entries:1178 - title: "`=`"1179 body: |11801181 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,11851186 .foo = .bar | .foo.baz = 111871188 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.11961197 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.12011202 - 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.12091210 This example should show the difference between '=' and '|=':12111212 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:12131214 .a = .b1215 .a |= .b12161217 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}.12201221 - title: "`+=`, `-=`, `*=`, `/=`, `//=`"1222 body: |12231224 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.12261227 examples:1228 - program: .foo += 11229 input: '{"foo": 42}'1230 output: ['{"foo": 43}']12311232 - 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:12381239 .posts[0].title = "JQ Manual"12401241 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:12441245 .posts[].comments |= . + ["this is great"]12461247 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).12501251 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.12571258 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:12621263 .posts[] | select(.author == "stedolan")12641265 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:12681269 (.posts[] | select(.author == "stedolan") | .comments) |=1270 . + ["terrible."]
added:docs/content/manual/v1.4/manual.yml+1672 added
1---2headline: jq 1.4 Manual34history: |56 *The manual for the development version of jq can be found7 [here](/jq/manual).*89body: |1011 A jq program is a "filter": it takes an input, and produces an12 output. There are a lot of builtin filters for extracting a13 particular field of an object, or converting a number to a string,14 or various other standard tasks.1516 Filters can be combined in various ways - you can pipe the output of17 one filter into another filter, or collect the output of a filter18 into an array.1920 Some filters produce multiple results, for instance there's one that21 produces all the elements of its input array. Piping that filter22 into a second runs the second filter for each element of the23 array. Generally, things that would be done with loops and iteration24 in other languages are just done by gluing filters together in jq.2526 It's important to remember that every filter has an input and an27 output. Even literals like "hello" or 42 are filters - they take an28 input but always produce the same literal as output. Operations that29 combine two filters, like addition, generally feed the same input to30 both and combine the results. So, you can implement an averaging31 filter as `add / length` - feeding the input array both to the `add`32 filter and the `length` filter and dividing the results.3334 But that's getting ahead of ourselves. :) Let's start with something35 simpler:3637manpage_intro: |38 jq(1) -- Command-line JSON processor39 ====================================4041 ## SYNOPSIS4243 `jq` [<options>...] <filter> [<files>...]4445 `jq` can transform JSON in various ways, by selecting, iterating,46 reducing and otherwise mangling JSON documents. For instance,47 running the command `jq 'map(.price) | add'` will take an array of48 JSON objects as input and return the sum of their "price" fields.4950 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.5354 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.5859 ## FILTERS6061manpage_epilogue: |62 ## BUGS6364 Presumably. Report them or discuss them at:6566 https://github.com/stedolan/jq/issues6768 ## AUTHOR6970 Stephen Dolan `<mu@netsoc.tcd.ie>`7172sections:73 - title: Invoking jq74 body: |7576 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.8182 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.9293 You can affect how jq reads and writes its input and output94 using some command-line options:9596 * `--version`:9798 Output the jq version and exit with zero.99100 * `--slurp`/`-s`:101102 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.105106 * `--online-input`/`-I`:107108 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.111112 * `--raw-input`/`-R`:113114 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.118119 * `--null-input`/`-n`:120121 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.124125 * `--compact-output` / `-c`:126127 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.130131 * `--color-output` / `-C` and `--monochrome-output` / `-M`:132133 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`.136137 * `--ascii-output` / `-a`:138139 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.144145 * `--unbuffered`146147 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).150151 * `--sort-keys` / `-S`:152153 Output the fields of each object with the keys in sorted order.154155 * `--raw-output` / `-r`:156157 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.161162 * `-f filename` / `--from-file filename`:163164 Read filter from the file rather than from a command line, like165 awk's -f option. You can also use '#' to make comments.166167 * `-e` / `--exit-status`:168169 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.175176 * `--arg name value`:177178 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"`.181182 * `--argfile name filename`:183184 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`.189190 - title: Basic filters191 entries:192 - title: "`.`"193 body: |194195 The absolute simplest (and least interesting) filter196 is `.`. This is a filter that takes its input and197 produces it unchanged as output.198199 Since jq by default pretty-prints all output, this trivial200 program can be a useful way of formatting JSON output from,201 say, `curl`.202203 examples:204 - program: '.'205 input: '"Hello, world!"'206 output: ['"Hello, world!"']207208 - title: "`.foo`, `.foo.bar`"209 body: |210211 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.214215 If the key contains special characters, you need to surround216 it with double quotes like this: `."foo$"`.217218 A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.219220 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]230231 - title: "`.foo?`"232 body: |233234 Just like `.foo`, but does not output even an error when `.`235 is not an array or an object.236237 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: ['[]']250251 - title: "`.[<string>]`, `.[2]`, `.[10:15]`"252 body: |253254 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.259260 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).267268 The `?` "operator" can also be used with the slice operator,269 as in `.[10:15]?`, which outputs values where the inputs are270 slice-able.271272 examples:273 - program: '.[0]'274 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'275 output: ['{"name":"JSON", "good":true}']276277 - program: '.[2]'278 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'279 output: ['null']280281 - program: '.[2:4]'282 input: '["a","b","c","d","e"]'283 output: ['["c", "d"]']284285 - program: '.[2:4]'286 input: '"abcdefghi"'287 output: ['"cd"']288289 - program: '.[:3]'290 input: '["a","b","c","d","e"]'291 output: ['["a", "b", "c"]']292293 - program: '.[-2:]'294 input: '["a","b","c","d","e"]'295 output: ['["d", "e"]']296297 - title: "`.[]`"298 body: |299300 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.305306 You can also use this on an object, and it will return all307 the values of the object.308309 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}'315316 - program: '.[]'317 input: '[]'318 output: []319320 - program: '.[]'321 input: '{"a": 1, "b": 1}'322 output: ['1', '1']323324 - title: "`.[]?`"325 body: |326327 Like `.[]`, but no errors will be output if . is not an array328 or object.329330 - title: "`,`"331 body: |332333 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.339340 examples:341 - program: '.foo, .bar'342 input: '{"foo": 42, "bar": "something else", "baz": true}'343 output: ['42', '"something else"']344345 - program: ".user, .projects[]"346 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'347 output: ['"stedolan"', '"jq"', '"wikiflow"']348349 - program: '.[4,2]'350 input: '["a","b","c","d","e"]'351 output: ['"e"', '"c"']352353 - 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.359360 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.364365 examples:366 - program: '.[] | .name'367 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'368 output: ['"JSON"', '"XML"']369370 - title: Types and Values371 body: |372373 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".376377 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.382383 entries:384 - title: Array construction - `[]`385 body: |386387 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]`)394395 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).400401 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.404405 examples:406 - program: "[.user, .projects[]]"407 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'408 output: ['["stedolan", "jq", "wikiflow"]']409 - title: Objects - `{}`410 body: |411412 Like JSON, `{}` is for constructing objects (aka413 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.414415 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).421422 {foo: .bar}423424 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 write429430 {user: .user, title: .title}431432 Because that's so common, there's a shortcut syntax: `{user, title}`.433434 If one of the expressions produces multiple results,435 multiple dictionaries will be produced. If the input's436437 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}438439 then the expression440441 {user, title: .titles[]}442443 will produce two outputs:444445 {"user":"stedolan", "title": "JQ Primer"}446 {"user":"stedolan", "title": "More JQ"}447448 Putting parentheses around the key means it will be evaluated as an449 expression. With the same input as above,450451 {(.user): .titles}452453 produces454455 {"stedolan": ["JQ Primer", "More JQ"]}456457 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"]}']466467 - title: Builtin operators and functions468 body: |469470 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.475476 entries:477 - title: Addition - `+`478 body: |479480 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:483484 - **Numbers** are added by normal arithmetic.485486 - **Arrays** are added by being concatenated into a larger array.487488 - **Strings** are added by being joined into a larger string.489490 - **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.)495496 `null` can be added to any value, and returns the other497 value unchanged.498499 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}']515516 - title: Subtraction - `-`517 body: |518519 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.522523 examples:524 - program: '4 - .a'525 input: '{"a":3}'526 output: ['1']527 - program: . - ["xml", "yaml"]528 input: '["xml", "yaml", "json"]'529 output: ['["json"]']530531 - title: Multiplication, division, modulo - `*`, `/`, and `%`532 body: |533534 These operators only work on numbers, and do the expected.535536 Multiplying a string by a number produces the concatenation of537 that string that many times.538539 Dividing a string by another splits the first using the second540 as separators.541542 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.546547 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}}']557558 - title: "`length`"559 body: |560561 The builtin function `length` gets the length of various562 different types of value:563564 - 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).567568 - The length of an **array** is the number of elements.569570 - The length of an **object** is the number of key-value pairs.571572 - The length of **null** is zero.573574 examples:575 - program: '.[] | length'576 input: '[[1,2], "string", {"a":2}, null]'577 output: [2, 6, 1, 0]578579 - title: "`keys`"580 body: |581582 The builtin function `keys`, when given an object, returns583 its keys in an array.584585 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.590591 When `keys` is given an array, it returns the valid indices592 for that array: the integers from 0 to length-1.593594 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]']601602 - title: "`has`"603 body: |604605 The builtin function `has` returns whether the input object606 has the given key, or the input array has an element at the607 given index.608609 `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.612613 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]']620621 - title: "`del`"622 body: |623624 The builtin function `del` removes a key and its corresponding625 value from an object.626627 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"]']634635 - title: "`to_entries`, `from_entries`, `with_entries`"636 body: |637638 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}`.642643 `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.647648 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}']658659660 - title: "`select`"661 body: |662663 The function `select(foo)` produces its input unchanged if664 `foo` returns true for that input, and produces no output665 otherwise.666667 It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`668 will give you `[2,3]`.669670 examples:671 - program: 'map(select(. >= 2))'672 input: '[1,5,3,0,7]'673 output: ['[5,3,7]']674675676 - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `strings`, `nulls`, `values`, `scalars`"677 body: |678679 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.682683 examples:684 - program: '.[]|numbers'685 input: '[[],{},1,"foo",null,true,false]'686 output: ['1']687688 - title: "`empty`"689 body: |690691 `empty` returns no results. None at all. Not even `null`.692693 It's useful on occasion. You'll know if you need it :)694695 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]']702703 - title: "`map(x)`"704 body: |705706 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.709710 `map(x)` is equivalent to `[.[] | x]`. In fact, this is how711 it's defined.712713 examples:714 - program: 'map(.+1)'715 input: '[1,2,3]'716 output: ['[2,3,4]']717718 - title: "`paths`"719 body: |720721 Outputs the paths to all the elements in its input (except it722 does not output the empty list, representing . itself).723724 `paths` is equivalent to725726 def paths: path(recurse(if (type|. == "array" or . == "object") then .[] else empty end))|select(length > 0);727728 examples:729 - program: '[paths]'730 input: '[1,[[],{"a":2}]]'731 output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']732733 - title: "`leaf_paths`"734 body: |735736 Outputs the paths to all the leaves (non-array, non-object737 elements) in its input.738739 examples:740 - program: '[leaf_paths]'741 input: '[1,[[],{"a":2}]]'742 output: ['[[0],[1,1,"a"]]']743744 - title: "`add`"745 body: |746747 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).752753 If the input is an empty array, `add` returns `null`.754755 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"]765766 - title: "`any`"767 body: |768769 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`.772773 If the input is an empty array, `any` returns `false`.774775 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"]785786 - title: "`all`"787 body: |788789 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`.792793 If the input is an empty array, `all` returns `true`.794795 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"]805806 - title: "`range`"807 body: |808809 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.813814 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]']821822 - title: "`floor`"823 body: |824825 The `floor` function returns the floor of its numeric input.826827 examples:828 - program: 'floor'829 input: '3.14159'830 output: ['3']831832 - title: "`sqrt`"833 body: |834835 The `sqrt` function returns the square root of its numeric input.836837 examples:838 - program: 'sqrt'839 input: '9'840 output: ['3']841842 - title: "`tonumber`"843 body: |844845 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.848849 examples:850 - program: '.[] | tonumber'851 input: '[1, "1"]'852 output: [1, 1]853854 - title: "`tostring`"855 body: |856857 The `tostring` function prints its input as a858 string. Strings are left unchanged, and all other values are859 JSON-encoded.860861 examples:862 - program: '.[] | tostring'863 input: '[1, "1", [1]]'864 output: ['"1"', '"1"', '"[1]"']865866 - title: "`type`"867 body: |868869 The `type` function returns the type of its argument as a870 string, which is one of null, boolean, number, string, array871 or object.872873 examples:874 - program: 'map(type)'875 input: '[0, false, [], {}, null, "hello"]'876 output: ['["number", "boolean", "array", "object", "null", "string"]']877878 - title: "`sort, sort_by`"879 body: |880881 The `sort` functions sorts its input, which must be an882 array. Values are sorted in the following order:883884 * `null`885 * `false`886 * `true`887 * numbers888 * strings, in alphabetical order (by unicode codepoint value)889 * arrays, in lexical order890 * objects891892 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.896897 `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.901902 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}]']909910 - title: "`group_by`"911 body: |912913 `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.917918 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.921922 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}]]']926927 - title: "`min`, `max`, `min_by`, `max_by`"928 body: |929930 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.934935 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}']942943 - title: "`unique`"944 body: |945946 The `unique` function takes as input an array and produces947 an array of the same elements, in sorted order, with948 duplicates removed.949950 examples:951 - program: 'unique'952 input: '[1,2,5,3,5,3,1,3]'953 output: ['[1,2,3,5]']954955 - title: "`unique_by`"956 body: |957958 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`.963964 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"]']971972973 - title: "`reverse`"974 body: |975976 This function reverses an array.977978 examples:979 - program: 'reverse'980 input: '[1,2,3,4]'981 output: ['[4,3,2,1]']982983 - title: "`contains`"984 body: |985986 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.994995 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']10111012 - title: "`indices(s)`"1013 body: |10141015 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`.10191020 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]']10301031 - title: "`index(s)`, `rindex(s)`"1032 body: |10331034 Outputs the index of the first (`index`) or last (`rindex`)1035 occurrence of `s` in the input.10361037 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']10441045 - title: "`startswith`"1046 body: |10471048 Outputs `true` if . starts with the given string argument.10491050 examples:1051 - program: '[.[]|startswith("foo")]'1052 input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1053 output: ['[false, true, false, true, false]']10541055 - title: "`endswith`"1056 body: |10571058 Outputs `true` if . ends with the given string argument.10591060 examples:1061 - program: '[.[]|endswith("foo")]'1062 input: '["foobar", "barfoo"]'1063 output: ['[false, true]']10641065 - title: "`ltrimstr`"1066 body: |10671068 Outputs its input with the given prefix string removed, if it1069 starts with it.10701071 examples:1072 - program: '[.[]|ltrimstr("foo")]'1073 input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1074 output: ['["fo","","barfoo","bar","afoo"]']10751076 - title: "`rtrimstr`"1077 body: |10781079 Outputs its input with the given suffix string removed, if it1080 starts with it.10811082 examples:1083 - program: '[.[]|rtrimstr("foo")]'1084 input: '["fo", "foo", "barfoo", "foobar", "foob"]'1085 output: ['["fo","","bar","foobar","foob"]']10861087 - title: "`explode`"1088 body: |10891090 Converts an input string into an array of the string's1091 codepoint numbers.10921093 examples:1094 - program: 'explode'1095 input: '"foobar"'1096 output: ['[102,111,111,98,97,114]']10971098 - title: "`implode`"1099 body: |11001101 The inverse of explode.11021103 examples:1104 - program: 'implode'1105 input: '[65, 66, 67]'1106 output: ['"ABC"']11071108 - title: "`split`"1109 body: |11101111 Splits an input string on the separator argument.11121113 examples:1114 - program: 'split(", ")'1115 input: '"a, b,c,d, e"'1116 output: ['["a","b,c,d","e"]']11171118 - title: "`join`"1119 body: |11201121 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.11251126 examples:1127 - program: 'join(", ")'1128 input: '["a","b,c,d","e"]'1129 output: ['"a, b,c,d, e"']113011311132 - title: "`recurse`"1133 body: |11341135 The `recurse` function allows you to search through a1136 recursive structure, and extract interesting data from all1137 levels. Suppose your input represents a filesystem:11381139 {"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": []}]}]}]}11461147 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:11511152 recurse(.children[]) | .name11531154 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":[]}'11621163 - title: "`recurse_down`"1164 body: |11651166 A quieter version of `recurse(.[])`, equivalent to:11671168 def recurse_down: recurse(.[]?);11691170 - title: "`..`"1171 body: |11721173 Short-hand for `recurse_down`. This is intended to resemble1174 the XPath `//` operator. Note that `..a` does not work; use1175 `..|a` instead.11761177 examples:1178 - program: '..|.a?'1179 input: '[[{"a":1}]]'1180 output: ['1']11811182 - title: "String interpolation - `\\(foo)`"1183 body: |11841185 Inside a string, you can put an expression inside parens1186 after a backslash. Whatever the expression returns will be1187 interpolated into the string.11881189 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"']11931194 - title: "Convert to/from JSON"1195 body: |11961197 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.12011202 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"]]']12121213 - title: "Format strings and escaping"1214 body: |12151216 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:12201221 * `@text`:12221223 Calls `tostring`, see that function for details.12241225 * `@json`:12261227 Serialises the input as JSON.12281229 * `@html`:12301231 Applies HTML/XML escaping, by mapping the characters1232 `<>&'"` to their entity equivalents `&lt;`, `&gt;`,1233 `&amp;`, `&apos;`, `&quot;`.12341235 * `@uri`:12361237 Applies percent-encoding, by mapping all reserved URI1238 characters to a `%xx` sequence.12391240 * `@csv`:12411242 The input must be an array, and it is rendered as CSV1243 with double quotes for strings, and quotes escaped by1244 repetition.12451246 * `@sh`:12471248 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.12511252 * `@base64`:12531254 The input is converted to base64 as specified by RFC 4648.12551256 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,12611262 @uri "https://www.google.com/search?q=\(.search)"12631264 will produce the following output for the input1265 `{"search":"what is jq?"}`:12661267 "https://www.google.com/search?q=what%20is%20jq%3f"12681269 Note that the slashes, question mark, etc. in the URL are1270 not escaped, as they were part of the string literal.12711272 examples:1273 - program: '@html'1274 input: '"This works if x < y"'1275 output: ['"This works if x &lt; y"']12761277# - program: '@html "<span>Anonymous said: \(.)</span>"'1278# input: '"<script>alert(\"lol hax\");</script>"'1279# output: ["<span>Anonymous said: &lt;script&gt;alert(&quot;lol hax&quot;);&lt;/script&gt;</span>"]12801281 - program: '@sh "echo \(.)"'1282 input: "\"O'Hara's Ale\""1283 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]12841285 - title: Conditionals and Comparisons1286 entries:1287 - title: "`==`, `!=`"1288 body: |12891290 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.12961297 != is "not equal", and 'a != b' returns the opposite value of 'a == b'12981299 examples:1300 - program: '.[] == 1'1301 input: '[1, 1.0, "1", "banana"]'1302 output: ['true', 'true', 'false', 'false']1303 - title: if-then-else1304 body: |13051306 `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.13091310 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.13171318 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.13211322 More cases can be added to an if using `elif A then B` syntax.13231324 examples:1325 - program: |-1326 if . == 0 then1327 "zero"1328 elif . == 1 then1329 "one"1330 else1331 "many"1332 end1333 input: 21334 output: ['"many"']13351336 - title: "`>, >=, <=, <`"1337 body: |13381339 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).13431344 The ordering is the same as that described for `sort`, above.13451346 examples:1347 - program: '. < 5'1348 input: 21349 output: ['true']13501351 - title: and/or/not1352 body: |13531354 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".13571358 If an operand of one of these operators produces multiple1359 results, the operator itself will produce a result for each input.13601361 `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`.13651366 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.13721373 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]']13891390 - title: Alternative operator - `//`1391 body: |13921393 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`.13961397 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).14021403 examples:1404 - program: '.foo // 42'1405 input: '{"foo": 19}'1406 output: [19]1407 - program: '.foo // 42'1408 input: '{}'1409 output: [42]14101411 - title: Advanced features1412 body: |1413 Variables are an absolute necessity in most programming languages, but1414 they're relegated to an "advanced feature" in jq.14151416 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.14221423 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).14271428 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.14311432 entries:1433 - title: Variables1434 body: |14351436 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.14421443 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.14491450 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:14551456 length as $array_length | add / $array_length14571458 We'll need a more complicated problem to find a situation where using1459 variables actually makes our lives easier.146014611462 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:14651466 {"posts": [{"title": "Frist psot", "author": "anon"},1467 {"title": "A well-written article", "author": "person1"}],1468 "realnames": {"anon": "Anonymous Coward",1469 "person1": "Person McPherson"}}14701471 We want to produce the posts with the author field containing a real1472 name, as in:14731474 {"title": "Frist psot", "author": "Anonymous Coward"}1475 {"title": "A well-written article", "author": "Person McPherson"}14761477 We use a variable, $names, to store the realnames object, so that we1478 can refer to it later when looking up author usernames:14791480 .realnames as $names | .posts[] | {title, author: $names[.author]}14811482 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.14861487 Variables are scoped over the rest of the expression that defines1488 them, so14891490 .realnames as $names | (.posts[] | {title, author: $names[.author]})14911492 will work, but14931494 (.realnames as $names | .posts[]) | {title, author: $names[.author]}14951496 won't.14971498 examples:1499 - program: '.bar as $x | .foo | . + $x'1500 input: '{"foo":10, "bar":200}'1501 output: ['210']15021503 - title: 'Defining Functions'1504 body: |15051506 You can give a filter a name using "def" syntax:15071508 def increment: . + 1;15091510 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:15131514 def map(f): [.[] | f];15151516 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.15211522 If you want the value-argument behaviour for defining simple1523 functions, you can just use a variable:15241525 def addvalue(f): f as $value | map(. + $value);15261527 With that definition, `addvalue(.foo)` will add the current1528 input's `.foo` field to each element of the array.15291530 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]]']15371538 - title: Reduce1539 body: |15401541 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:15441545 reduce .[] as $item (0; . + $item)15461547 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:15511552 0 | (3 as $item | . + $item) |1553 (2 as $item | . + $item) |1554 (1 as $item | . + $item)15551556 examples:1557 - program: 'reduce .[] as $item (0; . + $item)'1558 input: '[10,2,5,3]'1559 output: ['20']156015611562 - title: Assignment1563 body: |15641565 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".15701571 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).15781579 entries:1580 - title: "`=`"1581 body: |15821583 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,15871588 .foo = .bar | .foo.baz = 115891590 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.15981599 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.16031604 - 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.16111612 This example should show the difference between '=' and '|=':16131614 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:16151616 .a = .b1617 .a |= .b16181619 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}.16221623 - title: "`+=`, `-=`, `*=`, `/=`, `%=`, `//=`"1624 body: |16251626 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.16281629 examples:1630 - program: .foo += 11631 input: '{"foo": 42}'1632 output: ['{"foo": 43}']16331634 - 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:16401641 .posts[0].title = "JQ Manual"16421643 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:16461647 .posts[].comments |= . + ["this is great"]16481649 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).16521653 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.16591660 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:16641665 .posts[] | select(.author == "stedolan")16661667 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:16701671 (.posts[] | select(.author == "stedolan") | .comments) |=1672 . + ["terrible."]
added:docs/content/manual/v1.5/manual.yml+2878 added
1---2headline: jq 1.5 Manual34history: |56 *The manual for the development version of jq can be found7 [here](/jq/manual).*89body: |1011 A jq program is a "filter": it takes an input, and produces an12 output. There are a lot of builtin filters for extracting a13 particular field of an object, or converting a number to a string,14 or various other standard tasks.1516 Filters can be combined in various ways - you can pipe the output of17 one filter into another filter, or collect the output of a filter18 into an array.1920 Some filters produce multiple results, for instance there's one that21 produces all the elements of its input array. Piping that filter22 into a second runs the second filter for each element of the23 array. Generally, things that would be done with loops and iteration24 in other languages are just done by gluing filters together in jq.2526 It's important to remember that every filter has an input and an27 output. Even literals like "hello" or 42 are filters - they take an28 input but always produce the same literal as output. Operations that29 combine two filters, like addition, generally feed the same input to30 both and combine the results. So, you can implement an averaging31 filter as `add / length` - feeding the input array both to the `add`32 filter and the `length` filter and then performing the division.3334 But that's getting ahead of ourselves. :) Let's start with something35 simpler:3637manpage_intro: |38 jq(1) -- Command-line JSON processor39 ====================================4041 ## SYNOPSIS4243 `jq` [<options>...] <filter> [<files>...]4445 `jq` can transform JSON in various ways, by selecting, iterating,46 reducing and otherwise mangling JSON documents. For instance,47 running the command `jq 'map(.price) | add'` will take an array of48 JSON objects as input and return the sum of their "price" fields.4950 `jq` can accept text input as well, but by default, `jq` reads a51 stream of JSON entities (including numbers and other literals) from52 `stdin`. Whitespace is only needed to separate entities such as 153 and 2, and true and false. One or more <files> may be specified, in54 which case `jq` will read input from those instead.5556 The <options> are described in the [INVOKING JQ] section; they57 mostly concern input and output formatting. The <filter> is written58 in the jq language and specifies how to transform the input59 file or document.6061 ## FILTERS6263manpage_epilogue: |64 ## BUGS6566 Presumably. Report them or discuss them at:6768 https://github.com/stedolan/jq/issues6970 ## AUTHOR7172 Stephen Dolan `<mu@netsoc.tcd.ie>`7374sections:75 - title: Invoking jq76 body: |7778 jq filters run on a stream of JSON data. The input to jq is79 parsed as a sequence of whitespace-separated JSON values which80 are passed through the provided filter one at a time. The81 output(s) of the filter are written to standard out, again as a82 sequence of whitespace-separated JSON data.8384 Note: it is important to mind the shell's quoting rules. As a85 general rule it's best to always quote (with single-quote86 characters) the jq program, as too many characters with special87 meaning to jq are also shell meta-characters. For example, `jq88 "foo"` will fail on most Unix shells because that will be the same89 as `jq foo`, which will generally fail because `foo is not90 defined`. When using the Windows command shell (cmd.exe) it's91 best to use double quotes around your jq program when given on the92 command-line (instead of the `-f program-file` option), but then93 double-quotes in the jq program need backslash escaping.9495 You can affect how jq reads and writes its input and output96 using some command-line options:9798 * `--version`:99100 Output the jq version and exit with zero.101102 * `--seq`:103104 Use the `application/json-seq` MIME type scheme for separating105 JSON texts in jq's input and output. This means that an ASCII106 RS (record separator) character is printed before each value on107 output and an ASCII LF (line feed) is printed after every108 output. Input JSON texts that fail to parse are ignored (but109 warned about), discarding all subsequent input until the next110 RS. This more also parses the output of jq without the `--seq`111 option.112113 * `--stream`:114115 Parse the input in streaming fashion, outputing arrays of path116 and leaf values (scalars and empty arrays or empty objects).117 For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]`118 becomes `[[0],[]]`, `[[1],"a"]`, and `[[1,0],"b"]`.119120 This is useful for processing very large inputs. Use this in121 conjunction with filtering and the `reduce` and `foreach` syntax122 to reduce large inputs incrementally.123124 * `--slurp`/`-s`:125126 Instead of running the filter for each JSON object in the127 input, read the entire input stream into a large array and run128 the filter just once.129130 * `--raw-input`/`-R`:131132 Don't parse the input as JSON. Instead, each line of text is133 passed to the filter as a string. If combined with `--slurp`,134 then the entire input is passed to the filter as a single long135 string.136137 * `--null-input`/`-n`:138139 Don't read any input at all! Instead, the filter is run once140 using `null` as the input. This is useful when using jq as a141 simple calculator or to construct JSON data from scratch.142143 * `--compact-output` / `-c`:144145 By default, jq pretty-prints JSON output. Using this option146 will result in more compact output by instead putting each147 JSON object on a single line.148149 * `--tab`:150151 Use a tab for each indentation level instead of two spaces.152153 * `--indent n`:154155 Use the given number of spaces (no more than 8) for indentation.156157 * `--color-output` / `-C` and `--monochrome-output` / `-M`:158159 By default, jq outputs colored JSON if writing to a160 terminal. You can force it to produce color even if writing to161 a pipe or a file using `-C`, and disable color with `-M`.162163 * `--ascii-output` / `-a`:164165 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.170171 * `--unbuffered`172173 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).176177 * `--sort-keys` / `-S`:178179 Output the fields of each object with the keys in sorted order.180181 * `--raw-output` / `-r`:182183 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.187188 * `--join-output` / `-j`:189190 Like `-r` but jq won't print a newline after each output.191192 * `-f filename` / `--from-file filename`:193194 Read filter from the file rather than from a command line, like195 awk's -f option. You can also use '#' to make comments.196197 * `-Ldirectory` / `-L directory`:198199 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.202203 * `-e` / `--exit-status`:204205 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.211212 * `--arg name value`:213214 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"`.219220 * `--argjson name JSON-text`:221222 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`.225226 * `--slurpfile variable-name filename`:227228 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`.233234 * `--argfile variable-name filename`:235236 Do not use. Use `--slurpfile` instead.237238 (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`.)241242 * `--run-tests [filename]`:243244 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.253254 Be warned that this option can change backwards-incompatibly.255256 - title: Basic filters257 entries:258 - title: "`.`"259 body: |260261 The absolute simplest (and least interesting) filter262 is `.`. This is a filter that takes its input and263 produces it unchanged as output.264265 Since jq by default pretty-prints all output, this trivial266 program can be a useful way of formatting JSON output from,267 say, `curl`.268269 examples:270 - program: '.'271 input: '"Hello, world!"'272 output: ['"Hello, world!"']273274 - title: "`.foo`, `.foo.bar`"275 body: |276277 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.280281 If the key contains special characters, you need to surround282 it with double quotes like this: `."foo$"`.283284 A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.285286 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]296297 - title: "`.foo?`"298 body: |299300 Just like `.foo`, but does not output even an error when `.`301 is not an array or an object.302303 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: ['[]']316317 - title: "`.[<string>]`, `.[2]`, `.[10:15]`"318 body: |319320 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.325326 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).333334 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.338339 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.344345 The `?` "operator" can also be used with the slice operator,346 as in `.[10:15]?`, which outputs values where the inputs are347 slice-able.348349 examples:350 - program: '.[0]'351 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'352 output: ['{"name":"JSON", "good":true}']353354 - program: '.[2]'355 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'356 output: ['null']357358 - program: '.[2:4]'359 input: '["a","b","c","d","e"]'360 output: ['["c", "d"]']361362 - program: '.[2:4]'363 input: '"abcdefghi"'364 output: ['"cd"']365366 - program: '.[:3]'367 input: '["a","b","c","d","e"]'368 output: ['["a", "b", "c"]']369370 - program: '.[-2:]'371 input: '["a","b","c","d","e"]'372 output: ['["d", "e"]']373374 - program: '.[-2]'375 input: '[1,2,3]'376 output: ['2']377378 - title: "`.[]`"379 body: |380381 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.386387 You can also use this on an object, and it will return all388 the values of the object.389390 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}'396397 - program: '.[]'398 input: '[]'399 output: []400401 - program: '.[]'402 input: '{"a": 1, "b": 1}'403 output: ['1', '1']404405 - title: "`.[]?`"406 body: |407408 Like `.[]`, but no errors will be output if . is not an array409 or object.410411 - title: "`,`"412 body: |413414 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.420421 examples:422 - program: '.foo, .bar'423 input: '{"foo": 42, "bar": "something else", "baz": true}'424 output: ['42', '"something else"']425426 - program: ".user, .projects[]"427 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'428 output: ['"stedolan"', '"jq"', '"wikiflow"']429430 - program: '.[4,2]'431 input: '["a","b","c","d","e"]'432 output: ['"e"', '"c"']433434 - 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.440441 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.445446 examples:447 - program: '.[] | .name'448 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'449 output: ['"JSON"', '"XML"']450451 - title: Types and Values452 body: |453454 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".457458 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.463464 entries:465 - title: Array construction - `[]`466 body: |467468 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]`)475476 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).481482 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.485486 examples:487 - program: "[.user, .projects[]]"488 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'489 output: ['["stedolan", "jq", "wikiflow"]']490 - title: Objects - `{}`491 body: |492493 Like JSON, `{}` is for constructing objects (aka494 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.495496 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).502503 {foo: .bar}504505 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 write510511 {user: .user, title: .title}512513 Because that's so common, there's a shortcut syntax: `{user, title}`.514515 If one of the expressions produces multiple results,516 multiple dictionaries will be produced. If the input's517518 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}519520 then the expression521522 {user, title: .titles[]}523524 will produce two outputs:525526 {"user":"stedolan", "title": "JQ Primer"}527 {"user":"stedolan", "title": "More JQ"}528529 Putting parentheses around the key means it will be evaluated as an530 expression. With the same input as above,531532 {(.user): .titles}533534 produces535536 {"stedolan": ["JQ Primer", "More JQ"]}537538 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"]}']547548 - title: Builtin operators and functions549 body: |550551 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.556557 entries:558 - title: Addition - `+`559 body: |560561 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:564565 - **Numbers** are added by normal arithmetic.566567 - **Arrays** are added by being concatenated into a larger array.568569 - **Strings** are added by being joined into a larger string.570571 - **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.)576577 `null` can be added to any value, and returns the other578 value unchanged.579580 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}']596597 - title: Subtraction - `-`598 body: |599600 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.603604 examples:605 - program: '4 - .a'606 input: '{"a":3}'607 output: ['1']608 - program: . - ["xml", "yaml"]609 input: '["xml", "yaml", "json"]'610 output: ['["json"]']611612 - title: Multiplication, division, modulo - `*`, `/`, and `%`613 body: |614615 These infix operators behave as expected when given two numbers.616 Division by zero raises an error. `x % y` computes x modulo y.617618 Multiplying a string by a number produces the concatenation of619 that string that many times. `"x" * 0` produces **null**.620621 Dividing a string by another splits the first using the second622 as separators.623624 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.628629 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']642643644 - title: "`length`"645 body: |646647 The builtin function `length` gets the length of various648 different types of value:649650 - 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).653654 - The length of an **array** is the number of elements.655656 - The length of an **object** is the number of key-value pairs.657658 - The length of **null** is zero.659660 examples:661 - program: '.[] | length'662 input: '[[1,2], "string", {"a":2}, null]'663 output: [2, 6, 1, 0]664665 - title: "`keys`, `keys_unsorted`"666 body: |667668 The builtin function `keys`, when given an object, returns669 its keys in an array.670671 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.676677 When `keys` is given an array, it returns the valid indices678 for that array: the integers from 0 to length-1.679680 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.683684 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]']691692 - title: "`has(key)`"693 body: |694695 The builtin function `has` returns whether the input object696 has the given key, or the input array has an element at the697 given index.698699 `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.702703 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]']710711 - title: "`in`"712 body: |713714 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`.718719 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]']726727 - title: "`path(path_expression)`"728 body: |729730 Outputs array representations of the given path expression731 in `.`. The outputs are arrays of strings (object keys)732 and/or numbers (array indices).733734 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.738739 `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.742743 `path(pattern)` will produce array representations of the744 paths matching `pattern` if the paths exist in `.`.745746 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.750751 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"]]']758759 - title: "`del(path_expression)`"760 body: |761762 The builtin function `del` removes a key and its corresponding763 value from an object.764765 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"]']772773 - title: "`to_entries`, `from_entries`, `with_entries`"774 body: |775776 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}`.780781 `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.786787 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}']797798799 - title: "`select(boolean_expression)`"800 body: |801802 The function `select(foo)` produces its input unchanged if803 `foo` returns true for that input, and produces no output804 otherwise.805806 It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`807 will give you `[2,3]`.808809 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}']816817818 - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"819 body: |820821 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.825826 examples:827 - program: '.[]|numbers'828 input: '[[],{},1,"foo",null,true,false]'829 output: ['1']830831 - title: "`empty`"832 body: |833834 `empty` returns no results. None at all. Not even `null`.835836 It's useful on occasion. You'll know if you need it :)837838 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]']845846 - title: "`error(message)`"847 body: |848849 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.852853 - title: "`$__loc__`"854 body: |855856 Produces an object with a "file" key and a "line" key, with857 the filename and line number where `$__loc__` occurs, as858 values.859860 examples:861 - program: 'try error("\($__loc__)") catch .'862 input: 'null'863 output: ['"{\"file\":\"<top-level>\",\"line\":1}"']864865 - title: "`map(x)`, `map_values(x)`"866 body: |867868 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.871872 Similarly, `map_values(x)` will run that filter for each element,873 but it will return an object when an object is passed.874875 `map(x)` is equivalent to `[.[] | x]`. In fact, this is how876 it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`.877878 examples:879 - program: 'map(.+1)'880 input: '[1,2,3]'881 output: ['[2,3,4]']882883 - program: 'map_values(.+1)'884 input: '{"a": 1, "b": 2, "c": 3}'885 output: ['{"a": 2, "b": 3, "c": 4}']886887 - title: "`paths`, `paths(node_filter)`, `leaf_paths`"888 body: |889890 `paths` outputs the paths to all the elements in its input891 (except it does not output the empty list, representing .892 itself).893894 `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.897898 `leaf_paths` is an alias of `paths(scalars)`; `leaf_paths` is899 *deprecated* and will be removed in the next major release.900901 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"]]']908909 - title: "`add`"910 body: |911912 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).917918 If the input is an empty array, `add` returns `null`.919920 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"]930931 - title: "`any`, `any(condition)`, `any(generator; condition)`"932 body: |933934 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`.937938 If the input is an empty array, `any` returns `false`.939940 The `any(condition)` form applies the given condition to the941 elements of the input array.942943 The `any(generator; condition)` form applies the given944 condition to all the outputs of the given generator.945946 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"]956957 - title: "`all`, `all(condition)`, `all(generator; condition)`"958 body: |959960 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`.963964 The `all(condition)` form applies the given condition to the965 elements of the input array.966967 The `all(generator; condition)` form applies the given968 condition to all the outputs of the given generator.969970 If the input is an empty array, `all` returns `true`.971972 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"]982983 - title: "`flatten`, `flatten(depth)`"984 body: |985986 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.990991 `flatten(2)` is like `flatten`, but going only up to two992 levels deep.993994 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"}]']10071008 - title: "`range(upto)`, `range(from;upto)` `range(from;upto;by)`"1009 body: |10101011 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.10151016 The one argument form generates numbers from 0 to the given1017 number, with an increment of 1.10181019 The two argument form generates numbers from `from` to `upto`1020 with an increment of 1.10211022 The three argument form generates numbers `from` to `upto`1023 with an increment of `by`.10241025 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]']10441045 - title: "`floor`"1046 body: |10471048 The `floor` function returns the floor of its numeric input.10491050 examples:1051 - program: 'floor'1052 input: '3.14159'1053 output: ['3']10541055 - title: "`sqrt`"1056 body: |10571058 The `sqrt` function returns the square root of its numeric input.10591060 examples:1061 - program: 'sqrt'1062 input: '9'1063 output: ['3']10641065 - title: "`tonumber`"1066 body: |10671068 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.10711072 examples:1073 - program: '.[] | tonumber'1074 input: '[1, "1"]'1075 output: [1, 1]10761077 - title: "`tostring`"1078 body: |10791080 The `tostring` function prints its input as a1081 string. Strings are left unchanged, and all other values are1082 JSON-encoded.10831084 examples:1085 - program: '.[] | tostring'1086 input: '[1, "1", [1]]'1087 output: ['"1"', '"1"', '"[1]"']10881089 - title: "`type`"1090 body: |10911092 The `type` function returns the type of its argument as a1093 string, which is one of null, boolean, number, string, array1094 or object.10951096 examples:1097 - program: 'map(type)'1098 input: '[0, false, [], {}, null, "hello"]'1099 output: ['["number", "boolean", "array", "object", "null", "string"]']11001101 - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1102 body: |11031104 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.11111112 Note that division by zero raises an error.11131114 Currently most arithmetic operations operating on infinities,1115 NaNs, and sub-normals do not raise errors.11161117 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"']11241125 - title: "`sort, sort_by(path_expression)`"1126 body: |11271128 The `sort` functions sorts its input, which must be an1129 array. Values are sorted in the following order:11301131 * `null`1132 * `false`1133 * `true`1134 * numbers1135 * strings, in alphabetical order (by unicode codepoint value)1136 * arrays, in lexical order1137 * objects11381139 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.11431144 `sort` may be used to sort by a particular field of an1145 object, or by applying any jq filter.11461147 `sort_by(foo)` compares two elements by comparing the result of1148 `foo` on each element.11491150 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}]']11571158 - title: "`group_by(path_expression)`"1159 body: |11601161 `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.11651166 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.11691170 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}]]']11741175 - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1176 body: |11771178 Find the minimum or maximum element of the input array.11791180 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.11831184 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}']11911192 - title: "`unique`, `unique_by(path_exp)`"1193 body: |11941195 The `unique` function takes as input an array and produces1196 an array of the same elements, in sorted order, with1197 duplicates removed.11981199 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`.12031204 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"]']12141215 - title: "`reverse`"1216 body: |12171218 This function reverses an array.12191220 examples:1221 - program: 'reverse'1222 input: '[1,2,3,4]'1223 output: ['[4,3,2,1]']12241225 - title: "`contains(element)`"1226 body: |12271228 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.12361237 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']12531254 - title: "`indices(s)`"1255 body: |12561257 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`.12611262 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]']12721273 - title: "`index(s)`, `rindex(s)`"1274 body: |12751276 Outputs the index of the first (`index`) or last (`rindex`)1277 occurrence of `s` in the input.12781279 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']12861287 - title: "`inside`"1288 body: |12891290 The filter `inside(b)` will produce true if the input is1291 completely contained within b. It is, essentially, an1292 inversed version of `contains`.12931294 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']13101311 - title: "`startswith(str)`"1312 body: |13131314 Outputs `true` if . starts with the given string argument.13151316 examples:1317 - program: '[.[]|startswith("foo")]'1318 input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1319 output: ['[false, true, false, true, false]']13201321 - title: "`endswith(str)`"1322 body: |13231324 Outputs `true` if . ends with the given string argument.13251326 examples:1327 - program: '[.[]|endswith("foo")]'1328 input: '["foobar", "barfoo"]'1329 output: ['[false, true]']13301331 - title: "`combinations`, `combinations(n)`"1332 body: |13331334 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.13371338 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]']13451346 - title: "`ltrimstr(str)`"1347 body: |13481349 Outputs its input with the given prefix string removed, if it1350 starts with it.13511352 examples:1353 - program: '[.[]|ltrimstr("foo")]'1354 input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1355 output: ['["fo","","barfoo","bar","afoo"]']13561357 - title: "`rtrimstr(str)`"1358 body: |13591360 Outputs its input with the given suffix string removed, if it1361 ends with it.13621363 examples:1364 - program: '[.[]|rtrimstr("foo")]'1365 input: '["fo", "foo", "barfoo", "foobar", "foob"]'1366 output: ['["fo","","bar","foobar","foob"]']13671368 - title: "`explode`"1369 body: |13701371 Converts an input string into an array of the string's1372 codepoint numbers.13731374 examples:1375 - program: 'explode'1376 input: '"foobar"'1377 output: ['[102,111,111,98,97,114]']13781379 - title: "`implode`"1380 body: |13811382 The inverse of explode.13831384 examples:1385 - program: 'implode'1386 input: '[65, 66, 67]'1387 output: ['"ABC"']13881389 - title: "`split`"1390 body: |13911392 Splits an input string on the separator argument.13931394 examples:1395 - program: 'split(", ")'1396 input: '"a, b,c,d, e, "'1397 output: ['["a","b,c,d","e",""]']13981399 - title: "`join(str)`"1400 body: |14011402 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.14061407 examples:1408 - program: 'join(", ")'1409 input: '["a","b,c,d","e"]'1410 output: ['"a, b,c,d, e"']141114121413 - title: "`ascii_downcase`, `ascii_upcase`"1414 body: |14151416 Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1417 converted to the specified case.14181419 example:1420 - program: 'ascii_upcase'1421 input: '"useful but not for é"'1422 output: '"USEFUL BUT NOT FOR é"'14231424 - title: "`while(cond; update)`"1425 body: |14261427 The `while(cond; update)` function allows you to repeatedly1428 apply an update to `.` until `cond` is false.14291430 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.14341435 examples:1436 - program: '[while(.<100; .*2)]'1437 input: '1'1438 output: ['[1,2,4,8,16,32,64]']14391440 - title: "`until(cond; next)`"1441 body: |14421443 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).14471448 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.14521453 examples:1454 - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1455 input: '4'1456 output: ['24']145714581459 - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`, `recurse_down`"1460 body: |14611462 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:14651466 {"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": []}]}]}]}14731474 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:14781479 recurse(.children[]) | .name14801481 When called without an argument, `recurse` is equivalent to1482 `recurse(.[]?)`.14831484 `recurse(f)` is identical to `recurse(f; . != null)` and can be1485 used without concerns about recursion depth.14861487 `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)`.14921493 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.14961497 The recursive calls in `recurse` will not consume additional1498 memory whenever `f` produces at most a single output for each1499 input.15001501 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":[]}'15091510 - program: 'recurse'1511 input: '{"a":0,"b":[1]}'1512 output:1513 - '{"a":0,"b":[1]}'1514 - '0'1515 - '[1]'1516 - '1'15171518 - program: 'recurse(. * .; . < 20)'1519 input: 21520 output:1521 - 21522 - 41523 - 1615241525 - title: "`..`"1526 body: |15271528 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" `.`.15331534 examples:1535 - program: '..|.a?'1536 input: '[[{"a":1}]]'1537 output: ['1']15381539 - title: "`env`"1540 body: |15411542 Outputs an object representing jq's environment.15431544 examples:1545 - program: 'env.PAGER'1546 input: 'null'1547 output: ['"less"']15481549 - title: "`transpose`"1550 body: |15511552 Transpose a possibly jagged matrix (an array of arrays).1553 Rows are padded with nulls so the result is always rectangular.15541555 examples:1556 - program: 'transpose'1557 input: '[[1], [2,3]]'1558 output: ['[[1,2],[null,3]]']15591560 - title: "`bsearch(x)`"1561 body: |15621563 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.15711572 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]']15821583 - title: "String interpolation - `\\(foo)`"1584 body: |15851586 Inside a string, you can put an expression inside parens1587 after a backslash. Whatever the expression returns will be1588 interpolated into the string.15891590 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"']15941595 - title: "Convert to/from JSON"1596 body: |15971598 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.16021603 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"]]']16131614 - title: "Format strings and escaping"1615 body: |16161617 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:16211622 * `@text`:16231624 Calls `tostring`, see that function for details.16251626 * `@json`:16271628 Serializes the input as JSON.16291630 * `@html`:16311632 Applies HTML/XML escaping, by mapping the characters1633 `<>&'"` to their entity equivalents `&lt;`, `&gt;`,1634 `&amp;`, `&apos;`, `&quot;`.16351636 * `@uri`:16371638 Applies percent-encoding, by mapping all reserved URI1639 characters to a `%XX` sequence.16401641 * `@csv`:16421643 The input must be an array, and it is rendered as CSV1644 with double quotes for strings, and quotes escaped by1645 repetition.16461647 * `@tsv`:16481649 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.16561657 * `@sh`:16581659 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.16621663 * `@base64`:16641665 The input is converted to base64 as specified by RFC 4648.16661667 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,16721673 @uri "https://www.google.com/search?q=\(.search)"16741675 will produce the following output for the input1676 `{"search":"what is jq?"}`:16771678 "https://www.google.com/search?q=what%20is%20jq%3F"16791680 Note that the slashes, question mark, etc. in the URL are1681 not escaped, as they were part of the string literal.16821683 examples:1684 - program: '@html'1685 input: '"This works if x < y"'1686 output: ['"This works if x &lt; y"']16871688# - program: '@html "<span>Anonymous said: \(.)</span>"'1689# input: '"<script>alert(\"lol hax\");</script>"'1690# output: ["<span>Anonymous said: &lt;script&gt;alert(&quot;lol hax&quot;);&lt;/script&gt;</span>"]16911692 - program: '@sh "echo \(.)"'1693 input: "\"O'Hara's Ale\""1694 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]16951696 - title: "Dates"1697 body: |16981699 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.17021703 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.17071708 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.17121713 The `todate` builtin is an alias for `todateiso8601`.17141715 The `now` builtin outputs the current time, in seconds since1716 the Unix epoch.17171718 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.17241725 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.17321733 The `mktime` builtin consumes "broken down time"1734 representations of time output by `gmtime` and `strptime`.17351736 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`.17391740 The `strftime(fmt)` builtin formats a time with the given1741 format.17421743 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"`.17461747 jq may not support some or all of this date functionality on1748 some systems.17491750 examples:1751 - program: 'fromdate'1752 input: '"2015-03-05T23:51:47Z"'1753 output: ['1425599507']17541755 - 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]']17581759 - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'1760 input: '"2015-03-05T23:51:47Z"'1761 output: ['1425599507']17621763 - title: Conditionals and Comparisons1764 entries:1765 - title: "`==`, `!=`"1766 body: |17671768 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.17741775 != is "not equal", and 'a != b' returns the opposite value of 'a == b'17761777 examples:1778 - program: '.[] == 1'1779 input: '[1, 1.0, "1", "banana"]'1780 output: ['true', 'true', 'false', 'false']17811782 - title: if-then-else1783 body: |17841785 `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.17881789 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.17961797 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.18001801 More cases can be added to an if using `elif A then B` syntax.18021803 examples:1804 - program: |-1805 if . == 0 then1806 "zero"1807 elif . == 1 then1808 "one"1809 else1810 "many"1811 end1812 input: 21813 output: ['"many"']18141815 - title: "`>, >=, <=, <`"1816 body: |18171818 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).18221823 The ordering is the same as that described for `sort`, above.18241825 examples:1826 - program: '. < 5'1827 input: 21828 output: ['true']18291830 - title: and/or/not1831 body: |18321833 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".18361837 If an operand of one of these operators produces multiple1838 results, the operator itself will produce a result for each input.18391840 `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`.18441845 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.18511852 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]']18681869 - title: Alternative operator - `//`1870 body: |18711872 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`.18751876 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).18811882 examples:1883 - program: '.foo // 42'1884 input: '{"foo": 19}'1885 output: [19]1886 - program: '.foo // 42'1887 input: '{}'1888 output: [42]18891890 - title: try-catch1891 body: |18921893 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.18981899 The `try EXP` form uses `empty` as the exception handler.19001901 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"']19111912 - title: Breaking out of control structures1913 body: |19141915 A convenient use of try/catch is to break out of control1916 structures like `reduce`, `foreach`, `while`, and so on.19171918 For example:19191920 # 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;19241925 jq has a syntax for named lexical labels to "break" or "go (back) to":19261927 label $out | ... break $out ...19281929 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`.19321933 The relationship between the `break` and corresponding `label`1934 is lexical: the label has to be "visible" from the break.19351936 To break out of a `reduce`, for example:19371938 label $out | reduce .[] as $item (null; if .==false then break $out else ... end)19391940 The following jq program produces a syntax error:19411942 break $out19431944 because no label `$out` is visible.19451946 - title: "`?` operator"1947 body: |19481949 The `?` operator, used as `EXP?`, is shorthand for `try EXP`.19501951 examples:1952 - program: '[.[]|(.a)?]'1953 input: '[{}, true, {"a":1}]'1954 output: ['[null, 1]']195519561957 - title: Regular expressions (PCRE)1958 body: |19591960 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.19631964 The jq regex filters are defined so that they can be used using1965 one of these patterns:19661967 STRING | FILTER( REGEX )1968 STRING | FILTER( REGEX; FLAGS )1969 STRING | FILTER( [REGEX] )1970 STRING | FILTER( [REGEX, FLAGS] )19711972 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.19761977 FLAGS is a string consisting of one of more of the supported flags:19781979 * `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)19871988 To match whitespace in an x pattern use an escape such as \s, e.g.19891990 * test( "a\\sb", "x" ).19911992 Note that certain flags may also be specified within REGEX, e.g.19931994 * jq -n '("test", "TEst", "teST", "TEST") | test( "(?i)te(?-i)st" )'19951996 evaluates to: true, true, false, false.19971998 entries:1999 - title: "`test(val)`, `test(regex; flags)`"2000 body: |20012002 Like `match`, but does not return match objects, only `true` or `false`2003 for whether or not the regex matches the input.20042005 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']20122013 - title: "`match(val)`, `match(regex; flags)`"2014 body: |20152016 **match** outputs an object for each match it finds. Matches have2017 the following fields:20182019 * `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.20232024 Capturing group objects have the following fields:20252026 * `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)20302031 Capturing groups that did not match anything return an offset of -120322033 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"}]}'20522053 - program: '[ match("."; "g")] | length'2054 input: '"abc"'2055 output: [3]205620572058 - title: "`capture(val)`, `capture(regex; flags)`"2059 body: |20602061 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.20642065 examples:2066 - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2067 input: '"xyzzy-14"'2068 output: ['{ "a": "xyzzy", "n": "14" }']20692070 - title: "`scan(regex)`, `scan(regex; flags)`"2071 body: |20722073 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) ]`.20782079 example:2080 - program: 'scan("c")'2081 input: '"abcdefabc"'2082 output: ['"c"', '"c"']20832084 - program: 'scan("b")'2085 input: ("", "")2086 output: ['[]', '[]']20872088 - title: "`split(regex; flags)`"2089 body: |20902091 For backwards compatibility, `split` splits on a string, not a regex.20922093 example:2094 - program: 'split(", *"; null)'2095 input: '"ab,cd, ef"'2096 output: ['"ab","cd","ef"']209720982099 - title: "`splits(regex)`, `splits(regex; flags)`"2100 body: |21012102 These provide the same results as their `split` counterparts,2103 but as a stream instead of an array.21042105 example:2106 - program: 'splits(", *")'2107 input: '("ab,cd", "ef, gh")'2108 output: ['"ab"', '"cd"', '"ef"', '"gh"']21092110 - title: "`sub(regex; tostring)` `sub(regex; string; flags)`"2111 body: |21122113 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)".21192120 example:2121 - program: 'sub("^[^a-z]*(?<x>[a-z]*).*")'2122 input: '"123abc456"'2123 output: '"ZabcZabc"'212421252126 - title: "`gsub(regex; string)`, `gsub(regex; string; flags)`"2127 body: |21282129 `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2130 replaced by the string, after interpolation.21312132 example:2133 - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2134 input: '"Abcabc"'2135 output: '"+A-+a-"'213621372138 - title: Advanced features2139 body: |2140 Variables are an absolute necessity in most programming languages, but2141 they're relegated to an "advanced feature" in jq.21422143 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.21492150 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).21542155 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.21582159 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.21622163 Some minimal I/O support (besides reading JSON from standard2164 input, and writing JSON to standard output) is available.21652166 Finally, there is a module/library system.21672168 entries:2169 - title: Variables2170 body: |21712172 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.21782179 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.21852186 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:21912192 length as $array_length | add / $array_length21932194 We'll need a more complicated problem to find a situation where using2195 variables actually makes our lives easier.219621972198 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:22012202 {"posts": [{"title": "Frist psot", "author": "anon"},2203 {"title": "A well-written article", "author": "person1"}],2204 "realnames": {"anon": "Anonymous Coward",2205 "person1": "Person McPherson"}}22062207 We want to produce the posts with the author field containing a real2208 name, as in:22092210 {"title": "Frist psot", "author": "Anonymous Coward"}2211 {"title": "A well-written article", "author": "Person McPherson"}22122213 We use a variable, $names, to store the realnames object, so that we2214 can refer to it later when looking up author usernames:22152216 .realnames as $names | .posts[] | {title, author: $names[.author]}22172218 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.22222223 Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2224 `{$foo}` is a handy way of writing `{foo:$foo}`.22252226 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"):22292230 . as {realnames: $names, posts: [$first, $second]} | ...22312232 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.22372238 Variables are scoped over the rest of the expression that defines2239 them, so22402241 .realnames as $names | (.posts[] | {title, author: $names[.author]})22422243 will work, but22442245 (.realnames as $names | .posts[]) | {title, author: $names[.author]}22462247 won't.22482249 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.22542255 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}']22682269 - title: 'Defining Functions'2270 body: |22712272 You can give a filter a name using "def" syntax:22732274 def increment: . + 1;22752276 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:22792280 def map(f): [.[] | f];22812282 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:22882289 def foo(f): f|f;2290 5|foo(.*2)22912292 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.22972298 If you want the value-argument behaviour for defining simple2299 functions, you can just use a variable:23002301 def addvalue(f): f as $f | map(. + $f);23022303 Or use the short-hand:23042305 def addvalue($f): ...;23062307 With either definition, `addvalue(.foo)` will add the current2308 input's `.foo` field to each element of the array.23092310 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.23142315 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]]']23222323 - title: Reduce2324 body: |23252326 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:23292330 reduce .[] as $item (0; . + $item)23312332 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:23362337 0 | (3 as $item | . + $item) |2338 (2 as $item | . + $item) |2339 (1 as $item | . + $item)23402341 examples:2342 - program: 'reduce .[] as $item (0; . + $item)'2343 input: '[10,2,5,3]'2344 output: ['20']23452346 - title: "`limit(n; exp)`"2347 body: |23482349 The `limit` function extracts up to `n` outputs from `exp`.23502351 examples:2352 - program: '[limit(3;.[])]'2353 input: '[0,1,2,3,4,5,6,7,8,9]'2354 output: ['[0,1,2]']23552356 - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"2357 body: |23582359 The `first(expr)` and `last(expr)` functions extract the first2360 and last values from `expr`, respectively.23612362 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`.23662367 examples:2368 - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'2369 input: '10'2370 output: ['[0,9,5]']23712372 - title: "`first`, `last`, `nth(n)`"2373 body: |23742375 The `first` and `last` functions extract the first2376 and last values from any array at `.`.23772378 The `nth(n)` function extracts the nth value of any array at `.`.23792380 examples:2381 - program: '[range(.)]|[first, last, nth(5)]'2382 input: '10'2383 output: ['[0,9,5]']23842385 - title: "`foreach`"2386 body: |23872388 The `foreach` syntax is similar to `reduce`, but intended to2389 allow the construction of `limit` and reducers that produce2390 intermediate results (see example).23912392 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`.23992400 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).24032404 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"]]']24112412 - title: Recursion2413 body: |24142415 As described above, `recurse` uses recursion, and any jq2416 function can be recursive. The `while` builtin is also2417 implemented in terms of recursion.24182419 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.24232424 For example:24252426 def recurse(f): def r: ., (f | select(. != null) | r); r;24272428 def while(cond; update):2429 def _while:2430 if cond then ., (update | _while) else empty end;2431 _while;24322433 def repeat(exp):2434 def _repeat:2435 exp, _repeat;2436 _repeat;24372438 - title: Generators and iterators2439 body: |24402441 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.24482449 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.24532454 The `empty` builtin is the generator that produces zero2455 outputs. The `empty` builtin backtracks to the preceding2456 generator expression.24572458 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.24662467 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]']24852486 - title: 'Math'2487 body: |24882489 jq currently only has IEEE754 double-precision (64-bit) floating2490 point number support.24912492 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 `.`.24982499 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.25032504 - title: 'I/O'2505 body: |25062507 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.25132514 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.25192520 entries:2521 - title: "`input`"2522 body: |25232524 Outputs one new input.25252526 - title: "`inputs`"2527 body: |25282529 Outputs all remaining inputs, one by one.25302531 This is primarily useful for reductions over a program's2532 inputs.25332534 - title: "`debug`"2535 body: |25362537 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.25412542 - title: "`input_filename`"2543 body: |25442545 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.25482549 - title: "`input_line_number`"2550 body: |25512552 Returns the line number of the input currently being filtered.25532554 - title: 'Streaming'2555 body: |25562557 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.25622563 However, streaming isn't easy to deal with as the jq program will2564 have `[<path>, <leaf-value>]` (and a few other forms) as inputs.25652566 Several builtins are provided to make handling streams easier.25672568 The examples below use the streamed form of `[0,[1]]`, which2569 is `[[0],0],[[1,0],1],[[1,0]],[[1]]`.25702571 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.25762577 entries:2578 - title: "`truncate_stream(stream_expression)`"2579 body: |25802581 Consumes a number as input and truncates the corresponding2582 number of path elements from the left of the outputs of the2583 given streaming expression.25842585 examples:2586 - program: '[1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]'2587 input: '1'2588 output: ['[[[0],2],[[0]]]']25892590 - title: "`fromstream(stream_expression)`"2591 body: |25922593 Outputs values corresponding to the stream expression's2594 outputs.25952596 examples:2597 - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'2598 input: 'null'2599 output: ['[2]']26002601 - title: "`tostream`"2602 body: |26032604 The `tostream` builtin outputs the streamed form of its input.26052606 examples:2607 - program: '. as $dot|fromstream($dot|tostream)|.==$dot'2608 input: '[0,[1,{"a":1},{"b":2}]]'2609 output: ['true']26102611 - title: Assignment2612 body: |26132614 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".26192620 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).26272628 All the assignment operators in jq have path expressions on the2629 left-hand side.26302631 entries:2632 - title: "`=`"2633 body: |26342635 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,26392640 .foo = .bar | .foo.baz = 126412642 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.26502651 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.26552656 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.26602661 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.26672668 Note too that `.a,.b=0` does not set `.a` and `.b`, but2669 `(.a,.b)=0` sets both.26702671 - 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.26792680 This example should show the difference between '=' and '|=':26812682 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:26832684 .a = .b2685 .a |= .b26862687 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}.26902691 The left-hand side can be any general path expression; see `path()`.26922693 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.26972698 If the right-hand side outputs multiple values, only the last2699 one will be used.27002701 examples:27022703 - 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]]']27062707 - title: "`+=`, `-=`, `*=`, `/=`, `%=`, `//=`"2708 body: |27092710 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.27122713 examples:2714 - program: .foo += 12715 input: '{"foo": 42}'2716 output: ['{"foo": 43}']27172718 - 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:27242725 .posts[0].title = "JQ Manual"27262727 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:27302731 .posts[].comments |= . + ["this is great"]27322733 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).27362737 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.27432744 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:27482749 .posts[] | select(.author == "stedolan")27502751 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:27542755 (.posts[] | select(.author == "stedolan") | .comments) |=2756 . + ["terrible."]27572758 - title: Modules2759 body: |27602761 jq has a library/module system. Modules are files whose names end2762 in `.jq`.27632764 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.27672768 Paths in the a search path are subject to various substitutions.27692770 For paths starting with "~/", the user's home directory is2771 substituted for "~".27722773 For paths starting with "$ORIGIN/", the path of the jq executable2774 is substituted for "$ORIGIN".27752776 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.27792780 Import directives can optionally specify a search path to which2781 the default is appended.27822783 The default search path is the search path given to the `-L`2784 command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",2785 "$ORIGIN/../lib"]`.27862787 Null and empty string path elements terminate search path2788 processing.27892790 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.27952796 Consecutive components with the same name are not allowed to avoid2797 ambiguities (e.g., "foo/foo").27982799 For example, with `-L$HOME/.jq` a module `foo` can be found in2800 `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.28012802 If "$HOME/.jq" is a file, it is sourced into the main program.28032804 entries:2805 - title: "`import RelativePathString as NAME [<metadata>];`"2806 body: |28072808 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::".28122813 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.28182819 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.28222823 - title: "`include RelativePathString [<metadata>];`"2824 body: |28252826 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.28312832 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.28372838 - title: "`import RelativePathString as $NAME [<metadata>];`"2839 body: |28402841 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`.28452846 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.28512852 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.28552856 - title: "`module <metadata>;`"2857 body: |28582859 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.28622863 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.28672868 - title: "`modulemeta`"2869 body: |28702871 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.28742875 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---2headline: jq 1.6 Manual34history: |56 *The manual for the development version of jq can be found7 [here](/jq/manual).*89body: |1011 A jq program is a "filter": it takes an input, and produces an12 output. There are a lot of builtin filters for extracting a13 particular field of an object, or converting a number to a string,14 or various other standard tasks.1516 Filters can be combined in various ways - you can pipe the output of17 one filter into another filter, or collect the output of a filter18 into an array.1920 Some filters produce multiple results, for instance there's one that21 produces all the elements of its input array. Piping that filter22 into a second runs the second filter for each element of the23 array. Generally, things that would be done with loops and iteration24 in other languages are just done by gluing filters together in jq.2526 It's important to remember that every filter has an input and an27 output. Even literals like "hello" or 42 are filters - they take an28 input but always produce the same literal as output. Operations that29 combine two filters, like addition, generally feed the same input to30 both and combine the results. So, you can implement an averaging31 filter as `add / length` - feeding the input array both to the `add`32 filter and the `length` filter and then performing the division.3334 But that's getting ahead of ourselves. :) Let's start with something35 simpler:3637manpage_intro: |38 jq(1) -- Command-line JSON processor39 ====================================4041 ## SYNOPSIS4243 `jq` [<options>...] <filter> [<files>...]4445 `jq` can transform JSON in various ways, by selecting, iterating,46 reducing and otherwise mangling JSON documents. For instance,47 running the command `jq 'map(.price) | add'` will take an array of48 JSON objects as input and return the sum of their "price" fields.4950 `jq` can accept text input as well, but by default, `jq` reads a51 stream of JSON entities (including numbers and other literals) from52 `stdin`. Whitespace is only needed to separate entities such as 153 and 2, and true and false. One or more <files> may be specified, in54 which case `jq` will read input from those instead.5556 The <options> are described in the [INVOKING JQ] section; they57 mostly concern input and output formatting. The <filter> is written58 in the jq language and specifies how to transform the input59 file or document.6061 ## FILTERS6263manpage_epilogue: |64 ## BUGS6566 Presumably. Report them or discuss them at:6768 https://github.com/stedolan/jq/issues6970 ## AUTHOR7172 Stephen Dolan `<mu@netsoc.tcd.ie>`7374sections:75 - title: Invoking jq76 body: |7778 jq filters run on a stream of JSON data. The input to jq is79 parsed as a sequence of whitespace-separated JSON values which80 are passed through the provided filter one at a time. The81 output(s) of the filter are written to standard out, again as a82 sequence of whitespace-separated JSON data.8384 Note: it is important to mind the shell's quoting rules. As a85 general rule it's best to always quote (with single-quote86 characters) the jq program, as too many characters with special87 meaning to jq are also shell meta-characters. For example, `jq88 "foo"` will fail on most Unix shells because that will be the same89 as `jq foo`, which will generally fail because `foo is not90 defined`. When using the Windows command shell (cmd.exe) it's91 best to use double quotes around your jq program when given on the92 command-line (instead of the `-f program-file` option), but then93 double-quotes in the jq program need backslash escaping.9495 You can affect how jq reads and writes its input and output96 using some command-line options:9798 * `--version`:99100 Output the jq version and exit with zero.101102 * `--seq`:103104 Use the `application/json-seq` MIME type scheme for separating105 JSON texts in jq's input and output. This means that an ASCII106 RS (record separator) character is printed before each value on107 output and an ASCII LF (line feed) is printed after every108 output. Input JSON texts that fail to parse are ignored (but109 warned about), discarding all subsequent input until the next110 RS. This mode also parses the output of jq without the `--seq`111 option.112113 * `--stream`:114115 Parse the input in streaming fashion, outputing arrays of path116 and leaf values (scalars and empty arrays or empty objects).117 For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]`118 becomes `[[0],[]]`, `[[1],"a"]`, and `[[1,0],"b"]`.119120 This is useful for processing very large inputs. Use this in121 conjunction with filtering and the `reduce` and `foreach` syntax122 to reduce large inputs incrementally.123124 * `--slurp`/`-s`:125126 Instead of running the filter for each JSON object in the127 input, read the entire input stream into a large array and run128 the filter just once.129130 * `--raw-input`/`-R`:131132 Don't parse the input as JSON. Instead, each line of text is133 passed to the filter as a string. If combined with `--slurp`,134 then the entire input is passed to the filter as a single long135 string.136137 * `--null-input`/`-n`:138139 Don't read any input at all! Instead, the filter is run once140 using `null` as the input. This is useful when using jq as a141 simple calculator or to construct JSON data from scratch.142143 * `--compact-output` / `-c`:144145 By default, jq pretty-prints JSON output. Using this option146 will result in more compact output by instead putting each147 JSON object on a single line.148149 * `--tab`:150151 Use a tab for each indentation level instead of two spaces.152153 * `--indent n`:154155 Use the given number of spaces (no more than 8) for indentation.156157 * `--color-output` / `-C` and `--monochrome-output` / `-M`:158159 By default, jq outputs colored JSON if writing to a160 terminal. You can force it to produce color even if writing to161 a pipe or a file using `-C`, and disable color with `-M`.162163 Colors can be configured with the `JQ_COLORS` environment164 variable (see below).165166 * `--ascii-output` / `-a`:167168 jq usually outputs non-ASCII Unicode codepoints as UTF-8, even169 if the input specified them as escape sequences (like170 "\u03bc"). Using this option, you can force jq to produce pure171 ASCII output with every non-ASCII character replaced with the172 equivalent escape sequence.173174 * `--unbuffered`175176 Flush the output after each JSON object is printed (useful if177 you're piping a slow data source into jq and piping jq's178 output elsewhere).179180 * `--sort-keys` / `-S`:181182 Output the fields of each object with the keys in sorted order.183184 * `--raw-output` / `-r`:185186 With this option, if the filter's result is a string then it187 will be written directly to standard output rather than being188 formatted as a JSON string with quotes. This can be useful for189 making jq filters talk to non-JSON-based systems.190191 * `--join-output` / `-j`:192193 Like `-r` but jq won't print a newline after each output.194195 * `-f filename` / `--from-file filename`:196197 Read filter from the file rather than from a command line, like198 awk's -f option. You can also use '#' to make comments.199200 * `-Ldirectory` / `-L directory`:201202 Prepend `directory` to the search list for modules. If this203 option is used then no builtin search list is used. See the204 section on modules below.205206 * `-e` / `--exit-status`:207208 Sets the exit status of jq to 0 if the last output values was209 neither `false` nor `null`, 1 if the last output value was210 either `false` or `null`, or 4 if no valid result was ever211 produced. Normally jq exits with 2 if there was any usage212 problem or system error, 3 if there was a jq program compile213 error, or 0 if the jq program ran.214215 Another way to set the exit status is with the `halt_error`216 builtin function.217218 * `--arg name value`:219220 This option passes a value to the jq program as a predefined221 variable. If you run jq with `--arg foo bar`, then `$foo` is222 available in the program and has the value `"bar"`. Note that223 `value` will be treated as a string, so `--arg foo 123` will224 bind `$foo` to `"123"`.225226 Named arguments are also available to the jq program as227 `$ARGS.named`.228229 * `--argjson name JSON-text`:230231 This option passes a JSON-encoded value to the jq program as a232 predefined variable. If you run jq with `--argjson foo 123`, then233 `$foo` is available in the program and has the value `123`.234235 * `--slurpfile variable-name filename`:236237 This option reads all the JSON texts in the named file and binds238 an array of the parsed JSON values to the given global variable.239 If you run jq with `--slurpfile foo bar`, then `$foo` is available240 in the program and has an array whose elements correspond to the241 texts in the file named `bar`.242243 * `--rawfile variable-name filename`:244245 This option reads in the named file and binds its contents to the given246 global variable. If you run jq with `--rawfile foo bar`, then `$foo` is247 available in the program and has a string whose contents are to the texs248 in the file named `bar`.249250 * `--argfile variable-name filename`:251252 Do not use. Use `--slurpfile` instead.253254 (This option is like `--slurpfile`, but when the file has just255 one text, then that is used, else an array of texts is used as256 in `--slurpfile`.)257258 * `--args`:259260 Remaining arguments are positional string arguments. These are261 available to the jq program as `$ARGS.positional[]`.262263 * `--jsonargs`:264265 Remaining arguments are positional JSON text arguments. These266 are available to the jq program as `$ARGS.positional[]`.267268 * `--run-tests [filename]`:269270 Runs the tests in the given file or standard input. This must271 be the last option given and does not honor all preceding272 options. The input consists of comment lines, empty lines, and273 program lines followed by one input line, as many lines of274 output as are expected (one per output), and a terminating empty275 line. Compilation failure tests start with a line containing276 only "%%FAIL", then a line containing the program to compile,277 then a line containing an error message to compare to the278 actual.279280 Be warned that this option can change backwards-incompatibly.281282 - title: Basic filters283 entries:284 - title: "Identity: `.`"285 body: |286287 The absolute simplest filter is `.` . This is a filter that288 takes its input and produces it unchanged as output. That is,289 this is the identity operator.290291 Since jq by default pretty-prints all output, this trivial292 program can be a useful way of formatting JSON output from,293 say, `curl`.294295 examples:296 - program: '.'297 input: '"Hello, world!"'298 output: ['"Hello, world!"']299300 - title: "Object Identifier-Index: `.foo`, `.foo.bar`"301 body: |302303 The simplest *useful* filter is `.foo`. When given a304 JSON object (aka dictionary or hash) as input, it produces305 the value at the key "foo", or null if there's none present.306307 A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.308309 This syntax only works for simple, identifier-like keys, that310 is, keys that are all made of alphanumeric characters and311 underscore, and which do not start with a digit.312313 If the key contains special characters, you need to surround314 it with double quotes like this: `."foo$"`, or else `.["foo$"]`.315316 For example `.["foo::bar"]` and `.["foo.bar"]` work while317 `.foo::bar` does not, and `.foo.bar` means `.["foo"].["bar"]`.318319 examples:320 - program: '.foo'321 input: '{"foo": 42, "bar": "less interesting data"}'322 output: [42]323 - program: '.foo'324 input: '{"notfoo": true, "alsonotfoo": false}'325 output: ['null']326 - program: '.["foo"]'327 input: '{"foo": 42}'328 output: [42]329330 - title: "Optional Object Identifier-Index: `.foo?`"331 body: |332333 Just like `.foo`, but does not output even an error when `.`334 is not an array or an object.335336 examples:337 - program: '.foo?'338 input: '{"foo": 42, "bar": "less interesting data"}'339 output: [42]340 - program: '.foo?'341 input: '{"notfoo": true, "alsonotfoo": false}'342 output: ['null']343 - program: '.["foo"]?'344 input: '{"foo": 42}'345 output: [42]346 - program: '[.foo?]'347 input: '[1,2]'348 output: ['[]']349350 - title: "Generic Object Index: `.[<string>]`"351 body: |352353 You can also look up fields of an object using syntax like354 `.["foo"]` (.foo above is a shorthand version of this, but355 only for identifier-like strings).356357 - title: "Array Index: `.[2]`"358 body: |359360 When the index value is an integer, `.[<value>]` can index361 arrays. Arrays are zero-based, so `.[2]` returns the third362 element.363364 Negative indices are allowed, with -1 referring to the last365 element, -2 referring to the next to last element, and so on.366367 examples:368 - program: '.[0]'369 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'370 output: ['{"name":"JSON", "good":true}']371372 - program: '.[2]'373 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'374 output: ['null']375376 - program: '.[-2]'377 input: '[1,2,3]'378 output: ['2']379380 - title: "Array/String Slice: `.[10:15]`"381 body: |382383 The `.[10:15]` syntax can be used to return a subarray of an384 array or substring of a string. The array returned by385 `.[10:15]` will be of length 5, containing the elements from386 index 10 (inclusive) to index 15 (exclusive). Either index may387 be negative (in which case it counts backwards from the end of388 the array), or omitted (in which case it refers to the start389 or end of the array).390391 examples:392 - program: '.[2:4]'393 input: '["a","b","c","d","e"]'394 output: ['["c", "d"]']395396 - program: '.[2:4]'397 input: '"abcdefghi"'398 output: ['"cd"']399400 - program: '.[:3]'401 input: '["a","b","c","d","e"]'402 output: ['["a", "b", "c"]']403404 - program: '.[-2:]'405 input: '["a","b","c","d","e"]'406 output: ['["d", "e"]']407408 - title: "Array/Object Value Iterator: `.[]`"409 body: |410411 If you use the `.[index]` syntax, but omit the index412 entirely, it will return *all* of the elements of an413 array. Running `.[]` with the input `[1,2,3]` will produce the414 numbers as three separate results, rather than as a single415 array.416417 You can also use this on an object, and it will return all418 the values of the object.419420 examples:421 - program: '.[]'422 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'423 output:424 - '{"name":"JSON", "good":true}'425 - '{"name":"XML", "good":false}'426427 - program: '.[]'428 input: '[]'429 output: []430431 - program: '.[]'432 input: '{"a": 1, "b": 1}'433 output: ['1', '1']434435 - title: "`.[]?`"436 body: |437438 Like `.[]`, but no errors will be output if . is not an array439 or object.440441 - title: "Comma: `,`"442 body: |443444 If two filters are separated by a comma, then the445 same input will be fed into both and the two filters' output446 value streams will be concatenated in order: first, all of the447 outputs produced by the left expression, and then all of the448 outputs produced by the right. For instance, filter `.foo,449 .bar`, produces both the "foo" fields and "bar" fields as450 separate outputs.451452 examples:453 - program: '.foo, .bar'454 input: '{"foo": 42, "bar": "something else", "baz": true}'455 output: ['42', '"something else"']456457 - program: ".user, .projects[]"458 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'459 output: ['"stedolan"', '"jq"', '"wikiflow"']460461 - program: '.[4,2]'462 input: '["a","b","c","d","e"]'463 output: ['"e"', '"c"']464465 - title: "Pipe: `|`"466 body: |467468 The | operator combines two filters by feeding the output(s) of469 the one on the left into the input of the one on the right. It's470 pretty much the same as the Unix shell's pipe, if you're used to471 that.472473 If the one on the left produces multiple results, the one on474 the right will be run for each of those results. So, the475 expression `.[] | .foo` retrieves the "foo" field of each476 element of the input array.477478 Note that `.a.b.c` is the same as `.a | .b | .c`.479480 Note too that `.` is the input value at the particular stage481 in a "pipeline", specifically: where the `.` expression appears.482 Thus `.a | . | .b` is the same as `.a.b`, as the `.` in the483 middle refers to whatever value `.a` produced.484485 examples:486 - program: '.[] | .name'487 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'488 output: ['"JSON"', '"XML"']489490 - title: "Parenthesis"491 body: |492493 Parenthesis work as a grouping operator just as in any typical494 programming language.495496 examples:497 - program: '(. + 2) * 5'498 input: '1'499 output: [15]500501 - title: Types and Values502 body: |503504 jq supports the same set of datatypes as JSON - numbers,505 strings, booleans, arrays, objects (which in JSON-speak are506 hashes with only string keys), and "null".507508 Booleans, null, strings and numbers are written the same way as509 in javascript. Just like everything else in jq, these simple510 values take an input and produce an output - `42` is a valid jq511 expression that takes an input, ignores it, and returns 42512 instead.513514 entries:515 - title: "Array construction: `[]`"516 body: |517518 As in JSON, `[]` is used to construct arrays, as in519 `[1,2,3]`. The elements of the arrays can be any jq520 expression, including a pipeline. All of the results produced521 by all of the expressions are collected into one big array.522 You can use it to construct an array out of a known quantity523 of values (as in `[.foo, .bar, .baz]`) or to "collect" all the524 results of a filter into an array (as in `[.items[].name]`)525526 Once you understand the "," operator, you can look at jq's array527 syntax in a different light: the expression `[1,2,3]` is not using a528 built-in syntax for comma-separated arrays, but is instead applying529 the `[]` operator (collect results) to the expression 1,2,3 (which530 produces three different results).531532 If you have a filter `X` that produces four results,533 then the expression `[X]` will produce a single result, an534 array of four elements.535536 examples:537 - program: "[.user, .projects[]]"538 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'539 output: ['["stedolan", "jq", "wikiflow"]']540 - program: "[ .[] | . * 2]"541 input: '[1, 2, 3]'542 output: ['[2, 4, 6]']543544 - title: "Object Construction: `{}`"545 body: |546547 Like JSON, `{}` is for constructing objects (aka548 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.549550 If the keys are "identifier-like", then the quotes can be left551 off, as in `{a:42, b:17}`. Keys generated by expressions need552 to be parenthesized, e.g., `{("a"+"b"):59}`.553554 The value can be any expression (although you may need to555 wrap it in parentheses if it's a complicated one), which gets556 applied to the {} expression's input (remember, all filters557 have an input and an output).558559 {foo: .bar}560561 will produce the JSON object `{"foo": 42}` if given the JSON562 object `{"bar":42, "baz":43}` as its input. You can use this563 to select particular fields of an object: if the input is an564 object with "user", "title", "id", and "content" fields and565 you just want "user" and "title", you can write566567 {user: .user, title: .title}568569 Because that is so common, there's a shortcut syntax for it:570 `{user, title}`.571572 If one of the expressions produces multiple results,573 multiple dictionaries will be produced. If the input's574575 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}576577 then the expression578579 {user, title: .titles[]}580581 will produce two outputs:582583 {"user":"stedolan", "title": "JQ Primer"}584 {"user":"stedolan", "title": "More JQ"}585586 Putting parentheses around the key means it will be evaluated as an587 expression. With the same input as above,588589 {(.user): .titles}590591 produces592593 {"stedolan": ["JQ Primer", "More JQ"]}594595 examples:596 - program: '{user, title: .titles[]}'597 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'598 output:599 - '{"user":"stedolan", "title": "JQ Primer"}'600 - '{"user":"stedolan", "title": "More JQ"}'601 - program: '{(.user): .titles}'602 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'603 output: ['{"stedolan": ["JQ Primer", "More JQ"]}']604605 - title: "Recursive Descent: `..`"606 body: |607608 Recursively descends `.`, producing every value. This is the609 same as the zero-argument `recurse` builtin (see below). This610 is intended to resemble the XPath `//` operator. Note that611 `..a` does not work; use `..|.a` instead. In the example612 below we use `..|.a?` to find all the values of object keys613 "a" in any object found "below" `.`.614615 This is particularly useful in conjunction with `path(EXP)`616 (also see below) and the `?` operator.617618 examples:619 - program: '..|.a?'620 input: '[[{"a":1}]]'621 output: ['1']622623 - title: Builtin operators and functions624 body: |625626 Some jq 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.631632 entries:633 - title: "Addition: `+`"634 body: |635636 The operator `+` takes two filters, applies them both637 to the same input, and adds the results together. What638 "adding" means depends on the types involved:639640 - **Numbers** are added by normal arithmetic.641642 - **Arrays** are added by being concatenated into a larger array.643644 - **Strings** are added by being joined into a larger string.645646 - **Objects** are added by merging, that is, inserting all647 the key-value pairs from both objects into a single648 combined object. If both objects contain a value for the649 same key, the object on the right of the `+` wins. (For650 recursive merge use the `*` operator.)651652 `null` can be added to any value, and returns the other653 value unchanged.654655 examples:656 - program: '.a + 1'657 input: '{"a": 7}'658 output: ['8']659 - program: '.a + .b'660 input: '{"a": [1,2], "b": [3,4]}'661 output: ['[1,2,3,4]']662 - program: '.a + null'663 input: '{"a": 1}'664 output: ['1']665 - program: '.a + 1'666 input: '{}'667 output: ['1']668 - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'669 input: 'null'670 output: ['{"a": 42, "b": 2, "c": 3}']671672 - title: "Subtraction: `-`"673 body: |674675 As well as normal arithmetic subtraction on numbers, the `-`676 operator can be used on arrays to remove all occurrences of677 the second array's elements from the first array.678679 examples:680 - program: '4 - .a'681 input: '{"a":3}'682 output: ['1']683 - program: . - ["xml", "yaml"]684 input: '["xml", "yaml", "json"]'685 output: ['["json"]']686687 - title: "Multiplication, division, modulo: `*`, `/`, and `%`"688 body: |689690 These infix operators behave as expected when given two numbers.691 Division by zero raises an error. `x % y` computes x modulo y.692693 Multiplying a string by a number produces the concatenation of694 that string that many times. `"x" * 0` produces **null**.695696 Dividing a string by another splits the first using the second697 as separators.698699 Multiplying two objects will merge them recursively: this works700 like addition but if both objects contain a value for the701 same key, and the values are objects, the two are merged with702 the same strategy.703704 examples:705 - program: '10 / . * 3'706 input: 5707 output: [6]708 - program: '. / ", "'709 input: '"a, b,c,d, e"'710 output: ['["a","b,c,d","e"]']711 - program: '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'712 input: 'null'713 output: ['{"k": {"a": 0, "b": 2, "c": 3}}']714 - program: '.[] | (1 / .)?'715 input: '[1,0,-1]'716 output: ['1', '-1']717718719 - title: "`length`"720 body: |721722 The builtin function `length` gets the length of various723 different types of value:724725 - The length of a **string** is the number of Unicode726 codepoints it contains (which will be the same as its727 JSON-encoded length in bytes if it's pure ASCII).728729 - The length of an **array** is the number of elements.730731 - The length of an **object** is the number of key-value pairs.732733 - The length of **null** is zero.734735 examples:736 - program: '.[] | length'737 input: '[[1,2], "string", {"a":2}, null]'738 output: [2, 6, 1, 0]739740741 - title: "`utf8bytelength`"742 body: |743744 The builtin function `utf8bytelength` outputs the number of745 bytes used to encode a string in UTF-8.746747 examples:748 - program: 'utf8bytelength'749 input: '"\u03bc"'750 output: [2]751752 - title: "`keys`, `keys_unsorted`"753 body: |754755 The builtin function `keys`, when given an object, returns756 its keys in an array.757758 The keys are sorted "alphabetically", by unicode codepoint759 order. This is not an order that makes particular sense in760 any particular language, but you can count on it being the761 same for any two objects with the same set of keys,762 regardless of locale settings.763764 When `keys` is given an array, it returns the valid indices765 for that array: the integers from 0 to length-1.766767 The `keys_unsorted` function is just like `keys`, but if768 the input is an object then the keys will not be sorted,769 instead the keys will roughly be in insertion order.770771 examples:772 - program: 'keys'773 input: '{"abc": 1, "abcd": 2, "Foo": 3}'774 output: ['["Foo", "abc", "abcd"]']775 - program: 'keys'776 input: '[42,3,35]'777 output: ['[0,1,2]']778779 - title: "`has(key)`"780 body: |781782 The builtin function `has` returns whether the input object783 has the given key, or the input array has an element at the784 given index.785786 `has($key)` has the same effect as checking whether `$key`787 is a member of the array returned by `keys`, although `has`788 will be faster.789790 examples:791 - program: 'map(has("foo"))'792 input: '[{"foo": 42}, {}]'793 output: ['[true, false]']794 - program: 'map(has(2))'795 input: '[[0,1], ["a","b","c"]]'796 output: ['[false, true]']797798 - title: "`in`"799 body: |800801 The builtin function `in` returns whether or not the input key is in the802 given object, or the input index corresponds to an element803 in the given array. It is, essentially, an inversed version804 of `has`.805806 examples:807 - program: '.[] | in({"foo": 42})'808 input: '["foo", "bar"]'809 output: ['true', 'false']810 - program: 'map(in([0,1]))'811 input: '[2, 0]'812 output: ['[false, true]']813814 - title: "`map(x)`, `map_values(x)`"815 body: |816817 For any filter `x`, `map(x)` will run that filter for each818 element of the input array, and return the outputs in a new819 array. `map(.+1)` will increment each element of an array of numbers.820821 Similarly, `map_values(x)` will run that filter for each element,822 but it will return an object when an object is passed.823824 `map(x)` is equivalent to `[.[] | x]`. In fact, this is how825 it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`.826827 examples:828 - program: 'map(.+1)'829 input: '[1,2,3]'830 output: ['[2,3,4]']831832 - program: 'map_values(.+1)'833 input: '{"a": 1, "b": 2, "c": 3}'834 output: ['{"a": 2, "b": 3, "c": 4}']835836 - title: "`path(path_expression)`"837 body: |838839 Outputs array representations of the given path expression840 in `.`. The outputs are arrays of strings (object keys)841 and/or numbers (array indices).842843 Path expressions are jq expressions like `.a`, but also `.[]`.844 There are two types of path expressions: ones that can match845 exactly, and ones that cannot. For example, `.a.b.c` is an846 exact match path expression, while `.a[].b` is not.847848 `path(exact_path_expression)` will produce the array849 representation of the path expression even if it does not850 exist in `.`, if `.` is `null` or an array or an object.851852 `path(pattern)` will produce array representations of the853 paths matching `pattern` if the paths exist in `.`.854855 Note that the path expressions are not different from normal856 expressions. The expression857 `path(..|select(type=="boolean"))` outputs all the paths to858 boolean values in `.`, and only those paths.859860 examples:861 - program: 'path(.a[0].b)'862 input: 'null'863 output: ['["a",0,"b"]']864 - program: '[path(..)]'865 input: '{"a":[{"b":1}]}'866 output: ['[[],["a"],["a",0],["a",0,"b"]]']867868 - title: "`del(path_expression)`"869 body: |870871 The builtin function `del` removes a key and its corresponding872 value from an object.873874 examples:875 - program: 'del(.foo)'876 input: '{"foo": 42, "bar": 9001, "baz": 42}'877 output: ['{"bar": 9001, "baz": 42}']878 - program: 'del(.[1, 2])'879 input: '["foo", "bar", "baz"]'880 output: ['["foo"]']881882 - title: "`getpath(PATHS)`"883 body: |884885 The builtin function `getpath` outputs the values in `.` found886 at each path in `PATHS`.887888 examples:889 - program: 'getpath(["a","b"])'890 input: 'null'891 output: ['null']892 - program: '[getpath(["a","b"], ["a","c"])]'893 input: '{"a":{"b":0, "c":1}}'894 output: ['[0, 1]']895896 - title: "`setpath(PATHS; VALUE)`"897 body: |898899 The builtin function `setpath` sets the `PATHS` in `.` to `VALUE`.900901 examples:902 - program: 'setpath(["a","b"]; 1)'903 input: 'null'904 output: ['{"a": {"b": 1}}']905 - program: 'setpath(["a","b"]; 1)'906 input: '{"a":{"b":0}}'907 output: ['{"a": {"b": 1}}']908 - program: 'setpath([0,"a"]; 1)'909 input: 'null'910 output: ['[{"a":1}]']911912 - title: "`delpaths(PATHS)`"913 body: |914915 The builtin function `delpaths` sets the `PATHS` in `.`.916 `PATHS` must be an array of paths, where each path is an array917 of strings and numbers.918919 examples:920 - program: 'delpaths([["a","b"]])'921 input: '{"a":{"b":1},"x":{"y":2}}'922 output: ['{"a":{},"x":{"y":2}}']923924 - title: "`to_entries`, `from_entries`, `with_entries`"925 body: |926927 These functions convert between an object and an array of928 key-value pairs. If `to_entries` is passed an object, then929 for each `k: v` entry in the input, the output array930 includes `{"key": k, "value": v}`.931932 `from_entries` does the opposite conversion, and933 `with_entries(foo)` is a shorthand for `to_entries |934 map(foo) | from_entries`, useful for doing some operation to935 all keys and values of an object. `from_entries` accepts key, Key,936 name, Name, value and Value as keys.937938 examples:939 - program: 'to_entries'940 input: '{"a": 1, "b": 2}'941 output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']942 - program: 'from_entries'943 input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'944 output: ['{"a": 1, "b": 2}']945 - program: 'with_entries(.key |= "KEY_" + .)'946 input: '{"a": 1, "b": 2}'947 output: ['{"KEY_a": 1, "KEY_b": 2}']948949950 - title: "`select(boolean_expression)`"951 body: |952953 The function `select(foo)` produces its input unchanged if954 `foo` returns true for that input, and produces no output955 otherwise.956957 It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`958 will give you `[2,3]`.959960 examples:961 - program: 'map(select(. >= 2))'962 input: '[1,5,3,0,7]'963 output: ['[5,3,7]']964 - program: '.[] | select(.id == "second")'965 input: '[{"id": "first", "val": 1}, {"id": "second", "val": 2}]'966 output: ['{"id": "second", "val": 2}']967968969 - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"970 body: |971972 These built-ins select only inputs that are arrays, objects,973 iterables (arrays or objects), booleans, numbers, normal974 numbers, finite numbers, strings, null, non-null values, and975 non-iterables, respectively.976977 examples:978 - program: '.[]|numbers'979 input: '[[],{},1,"foo",null,true,false]'980 output: ['1']981982 - title: "`empty`"983 body: |984985 `empty` returns no results. None at all. Not even `null`.986987 It's useful on occasion. You'll know if you need it :)988989 examples:990 - program: '1, empty, 2'991 input: 'null'992 output: [1, 2]993 - program: '[1,2,empty,3]'994 input: 'null'995 output: ['[1,2,3]']996997 - title: "`error(message)`"998 body: |9991000 Produces an error, just like `.a` applied to values other than1001 null and objects would, but with the given message as the1002 error's value. Errors can be caught with try/catch; see below.10031004 - title: "`halt`"1005 body: |10061007 Stops the jq program with no further outputs. jq will exit1008 with exit status `0`.10091010 - title: "`halt_error`, `halt_error(exit_code)`"1011 body: |10121013 Stops the jq program with no further outputs. The input will1014 be printed on `stderr` as raw output (i.e., strings will not1015 have double quotes) with no decoration, not even a newline.10161017 The given `exit_code` (defaulting to `5`) will be jq's exit1018 status.10191020 For example, `"Error: somthing went wrong\n"|halt_error(1)`.10211022 - title: "`$__loc__`"1023 body: |10241025 Produces an object with a "file" key and a "line" key, with1026 the filename and line number where `$__loc__` occurs, as1027 values.10281029 examples:1030 - program: 'try error("\($__loc__)") catch .'1031 input: 'null'1032 output: ['"{\"file\":\"<top-level>\",\"line\":1}"']10331034 - title: "`paths`, `paths(node_filter)`, `leaf_paths`"1035 body: |10361037 `paths` outputs the paths to all the elements in its input1038 (except it does not output the empty list, representing .1039 itself).10401041 `paths(f)` outputs the paths to any values for which `f` is true.1042 That is, `paths(numbers)` outputs the paths to all numeric1043 values.10441045 `leaf_paths` is an alias of `paths(scalars)`; `leaf_paths` is1046 *deprecated* and will be removed in the next major release.10471048 examples:1049 - program: '[paths]'1050 input: '[1,[[],{"a":2}]]'1051 output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']1052 - program: '[paths(scalars)]'1053 input: '[1,[[],{"a":2}]]'1054 output: ['[[0],[1,1,"a"]]']10551056 - title: "`add`"1057 body: |10581059 The filter `add` takes as input an array, and produces as1060 output the elements of the array added together. This might1061 mean summed, concatenated or merged depending on the types1062 of the elements of the input array - the rules are the same1063 as those for the `+` operator (described above).10641065 If the input is an empty array, `add` returns `null`.10661067 examples:1068 - program: add1069 input: '["a","b","c"]'1070 output: ['"abc"']1071 - program: add1072 input: '[1, 2, 3]'1073 output: [6]1074 - program: add1075 input: '[]'1076 output: ["null"]10771078 - title: "`any`, `any(condition)`, `any(generator; condition)`"1079 body: |10801081 The filter `any` takes as input an array of boolean values,1082 and produces `true` as output if any of the elements of1083 the array are `true`.10841085 If the input is an empty array, `any` returns `false`.10861087 The `any(condition)` form applies the given condition to the1088 elements of the input array.10891090 The `any(generator; condition)` form applies the given1091 condition to all the outputs of the given generator.10921093 examples:1094 - program: any1095 input: '[true, false]'1096 output: ["true"]1097 - program: any1098 input: '[false, false]'1099 output: ["false"]1100 - program: any1101 input: '[]'1102 output: ["false"]11031104 - title: "`all`, `all(condition)`, `all(generator; condition)`"1105 body: |11061107 The filter `all` takes as input an array of boolean values,1108 and produces `true` as output if all of the elements of1109 the array are `true`.11101111 The `all(condition)` form applies the given condition to the1112 elements of the input array.11131114 The `all(generator; condition)` form applies the given1115 condition to all the outputs of the given generator.11161117 If the input is an empty array, `all` returns `true`.11181119 examples:1120 - program: all1121 input: '[true, false]'1122 output: ["false"]1123 - program: all1124 input: '[true, true]'1125 output: ["true"]1126 - program: all1127 input: '[]'1128 output: ["true"]11291130 - title: "`flatten`, `flatten(depth)`"1131 body: |11321133 The filter `flatten` takes as input an array of nested arrays,1134 and produces a flat array in which all arrays inside the original1135 array have been recursively replaced by their values. You can pass1136 an argument to it to specify how many levels of nesting to flatten.11371138 `flatten(2)` is like `flatten`, but going only up to two1139 levels deep.11401141 examples:1142 - program: flatten1143 input: '[1, [2], [[3]]]'1144 output: ["[1, 2, 3]"]1145 - program: flatten(1)1146 input: '[1, [2], [[3]]]'1147 output: ["[1, 2, [3]]"]1148 - program: flatten1149 input: '[[]]'1150 output: ["[]"]1151 - program: flatten1152 input: '[{"foo": "bar"}, [{"foo": "baz"}]]'1153 output: ['[{"foo": "bar"}, {"foo": "baz"}]']11541155 - title: "`range(upto)`, `range(from;upto)` `range(from;upto;by)`"1156 body: |11571158 The `range` function produces a range of numbers. `range(4;10)`1159 produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers1160 are produced as separate outputs. Use `[range(4;10)]` to get a range as1161 an array.11621163 The one argument form generates numbers from 0 to the given1164 number, with an increment of 1.11651166 The two argument form generates numbers from `from` to `upto`1167 with an increment of 1.11681169 The three argument form generates numbers `from` to `upto`1170 with an increment of `by`.11711172 examples:1173 - program: 'range(2;4)'1174 input: 'null'1175 output: ['2', '3']1176 - program: '[range(2;4)]'1177 input: 'null'1178 output: ['[2,3]']1179 - program: '[range(4)]'1180 input: 'null'1181 output: ['[0,1,2,3]']1182 - program: '[range(0;10;3)]'1183 input: 'null'1184 output: ['[0,3,6,9]']1185 - program: '[range(0;10;-1)]'1186 input: 'null'1187 output: ['[]']1188 - program: '[range(0;-5;-1)]'1189 input: 'null'1190 output: ['[0,-1,-2,-3,-4]']11911192 - title: "`floor`"1193 body: |11941195 The `floor` function returns the floor of its numeric input.11961197 examples:1198 - program: 'floor'1199 input: '3.14159'1200 output: ['3']12011202 - title: "`sqrt`"1203 body: |12041205 The `sqrt` function returns the square root of its numeric input.12061207 examples:1208 - program: 'sqrt'1209 input: '9'1210 output: ['3']12111212 - title: "`tonumber`"1213 body: |12141215 The `tonumber` function parses its input as a number. It1216 will convert correctly-formatted strings to their numeric1217 equivalent, leave numbers alone, and give an error on all other input.12181219 examples:1220 - program: '.[] | tonumber'1221 input: '[1, "1"]'1222 output: [1, 1]12231224 - title: "`tostring`"1225 body: |12261227 The `tostring` function prints its input as a1228 string. Strings are left unchanged, and all other values are1229 JSON-encoded.12301231 examples:1232 - program: '.[] | tostring'1233 input: '[1, "1", [1]]'1234 output: ['"1"', '"1"', '"[1]"']12351236 - title: "`type`"1237 body: |12381239 The `type` function returns the type of its argument as a1240 string, which is one of null, boolean, number, string, array1241 or object.12421243 examples:1244 - program: 'map(type)'1245 input: '[0, false, [], {}, null, "hello"]'1246 output: ['["number", "boolean", "array", "object", "null", "string"]']12471248 - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1249 body: |12501251 Some arithmetic operations can yield infinities and "not a1252 number" (NaN) values. The `isinfinite` builtin returns `true`1253 if its input is infinite. The `isnan` builtin returns `true`1254 if its input is a NaN. The `infinite` builtin returns a1255 positive infinite value. The `nan` builtin returns a NaN.1256 The `isnormal` builtin returns true if its input is a normal1257 number.12581259 Note that division by zero raises an error.12601261 Currently most arithmetic operations operating on infinities,1262 NaNs, and sub-normals do not raise errors.12631264 examples:1265 - program: '.[] | (infinite * .) < 0'1266 input: '[-1, 1]'1267 output: ['true', 'false']1268 - program: 'infinite, nan | type'1269 input: 'null'1270 output: ['"number"', '"number"']12711272 - title: "`sort, sort_by(path_expression)`"1273 body: |12741275 The `sort` functions sorts its input, which must be an1276 array. Values are sorted in the following order:12771278 * `null`1279 * `false`1280 * `true`1281 * numbers1282 * strings, in alphabetical order (by unicode codepoint value)1283 * arrays, in lexical order1284 * objects12851286 The ordering for objects is a little complex: first they're1287 compared by comparing their sets of keys (as arrays in1288 sorted order), and if their keys are equal then the values1289 are compared key by key.12901291 `sort` may be used to sort by a particular field of an1292 object, or by applying any jq filter.12931294 `sort_by(foo)` compares two elements by comparing the result of1295 `foo` on each element.12961297 examples:1298 - program: 'sort'1299 input: '[8,3,null,6]'1300 output: ['[null,3,6,8]']1301 - program: 'sort_by(.foo)'1302 input: '[{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}]'1303 output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']13041305 - title: "`group_by(path_expression)`"1306 body: |13071308 `group_by(.foo)` takes as input an array, groups the1309 elements having the same `.foo` field into separate arrays,1310 and produces all of these arrays as elements of a larger1311 array, sorted by the value of the `.foo` field.13121313 Any jq expression, not just a field access, may be used in1314 place of `.foo`. The sorting order is the same as described1315 in the `sort` function above.13161317 examples:1318 - program: 'group_by(.foo)'1319 input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'1320 output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']13211322 - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1323 body: |13241325 Find the minimum or maximum element of the input array.13261327 The `min_by(path_exp)` and `max_by(path_exp)` functions allow1328 you to specify a particular field or property to examine, e.g.1329 `min_by(.foo)` finds the object with the smallest `foo` field.13301331 examples:1332 - program: 'min'1333 input: '[5,4,2,7]'1334 output: ['2']1335 - program: 'max_by(.foo)'1336 input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'1337 output: ['{"foo":2, "bar":3}']13381339 - title: "`unique`, `unique_by(path_exp)`"1340 body: |13411342 The `unique` function takes as input an array and produces1343 an array of the same elements, in sorted order, with1344 duplicates removed.13451346 The `unique_by(path_exp)` function will keep only one element1347 for each value obtained by applying the argument. Think of it1348 as making an array by taking one element out of every group1349 produced by `group`.13501351 examples:1352 - program: 'unique'1353 input: '[1,2,5,3,5,3,1,3]'1354 output: ['[1,2,3,5]']1355 - program: 'unique_by(.foo)'1356 input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'1357 output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']1358 - program: 'unique_by(length)'1359 input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'1360 output: ['["bacon", "chunky", "asparagus"]']13611362 - title: "`reverse`"1363 body: |13641365 This function reverses an array.13661367 examples:1368 - program: 'reverse'1369 input: '[1,2,3,4]'1370 output: ['[4,3,2,1]']13711372 - title: "`contains(element)`"1373 body: |13741375 The filter `contains(b)` will produce true if b is1376 completely contained within the input. A string B is1377 contained in a string A if B is a substring of A. An array B1378 is contained in an array A if all elements in B are1379 contained in any element in A. An object B is contained in1380 object A if all of the values in B are contained in the1381 value in A with the same key. All other types are assumed to1382 be contained in each other if they are equal.13831384 examples:1385 - program: 'contains("bar")'1386 input: '"foobar"'1387 output: ['true']1388 - program: 'contains(["baz", "bar"])'1389 input: '["foobar", "foobaz", "blarp"]'1390 output: ['true']1391 - program: 'contains(["bazzzzz", "bar"])'1392 input: '["foobar", "foobaz", "blarp"]'1393 output: ['false']1394 - program: 'contains({foo: 12, bar: [{barp: 12}]})'1395 input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1396 output: ['true']1397 - program: 'contains({foo: 12, bar: [{barp: 15}]})'1398 input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'1399 output: ['false']14001401 - title: "`indices(s)`"1402 body: |14031404 Outputs an array containing the indices in `.` where `s`1405 occurs. The input may be an array, in which case if `s` is an1406 array then the indices output will be those where all elements1407 in `.` match those of `s`.14081409 examples:1410 - program: 'indices(", ")'1411 input: '"a,b, cd, efg, hijk"'1412 output: ['[3,7,12]']1413 - program: 'indices(1)'1414 input: '[0,1,2,1,3,1,4]'1415 output: ['[1,3,5]']1416 - program: 'indices([1,2])'1417 input: '[0,1,2,3,1,4,2,5,1,2,6,7]'1418 output: ['[1,8]']14191420 - title: "`index(s)`, `rindex(s)`"1421 body: |14221423 Outputs the index of the first (`index`) or last (`rindex`)1424 occurrence of `s` in the input.14251426 examples:1427 - program: 'index(", ")'1428 input: '"a,b, cd, efg, hijk"'1429 output: ['3']1430 - program: 'rindex(", ")'1431 input: '"a,b, cd, efg, hijk"'1432 output: ['12']14331434 - title: "`inside`"1435 body: |14361437 The filter `inside(b)` will produce true if the input is1438 completely contained within b. It is, essentially, an1439 inversed version of `contains`.14401441 examples:1442 - program: 'inside("foobar")'1443 input: '"bar"'1444 output: ['true']1445 - program: 'inside(["foobar", "foobaz", "blarp"])'1446 input: '["baz", "bar"]'1447 output: ['true']1448 - program: 'inside(["foobar", "foobaz", "blarp"])'1449 input: '["bazzzzz", "bar"]'1450 output: ['false']1451 - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1452 input: '{"foo": 12, "bar": [{"barp": 12}]}'1453 output: ['true']1454 - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'1455 input: '{"foo": 12, "bar": [{"barp": 15}]}'1456 output: ['false']14571458 - title: "`startswith(str)`"1459 body: |14601461 Outputs `true` if . starts with the given string argument.14621463 examples:1464 - program: '[.[]|startswith("foo")]'1465 input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1466 output: ['[false, true, false, true, false]']14671468 - title: "`endswith(str)`"1469 body: |14701471 Outputs `true` if . ends with the given string argument.14721473 examples:1474 - program: '[.[]|endswith("foo")]'1475 input: '["foobar", "barfoo"]'1476 output: ['[false, true]']14771478 - title: "`combinations`, `combinations(n)`"1479 body: |14801481 Outputs all combinations of the elements of the arrays in the1482 input array. If given an argument `n`, it outputs all combinations1483 of `n` repetitions of the input array.14841485 examples:1486 - program: 'combinations'1487 input: '[[1,2], [3, 4]]'1488 output: ['[1, 3]', '[1, 4]', '[2, 3]', '[2, 4]']1489 - program: 'combinations(2)'1490 input: '[0, 1]'1491 output: ['[0, 0]', '[0, 1]', '[1, 0]', '[1, 1]']14921493 - title: "`ltrimstr(str)`"1494 body: |14951496 Outputs its input with the given prefix string removed, if it1497 starts with it.14981499 examples:1500 - program: '[.[]|ltrimstr("foo")]'1501 input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1502 output: ['["fo","","barfoo","bar","afoo"]']15031504 - title: "`rtrimstr(str)`"1505 body: |15061507 Outputs its input with the given suffix string removed, if it1508 ends with it.15091510 examples:1511 - program: '[.[]|rtrimstr("foo")]'1512 input: '["fo", "foo", "barfoo", "foobar", "foob"]'1513 output: ['["fo","","bar","foobar","foob"]']15141515 - title: "`explode`"1516 body: |15171518 Converts an input string into an array of the string's1519 codepoint numbers.15201521 examples:1522 - program: 'explode'1523 input: '"foobar"'1524 output: ['[102,111,111,98,97,114]']15251526 - title: "`implode`"1527 body: |15281529 The inverse of explode.15301531 examples:1532 - program: 'implode'1533 input: '[65, 66, 67]'1534 output: ['"ABC"']15351536 - title: "`split(str)`"1537 body: |15381539 Splits an input string on the separator argument.15401541 examples:1542 - program: 'split(", ")'1543 input: '"a, b,c,d, e, "'1544 output: ['["a","b,c,d","e",""]']15451546 - title: "`join(str)`"1547 body: |15481549 Joins the array of elements given as input, using the1550 argument as separator. It is the inverse of `split`: that is,1551 running `split("foo") | join("foo")` over any input string1552 returns said input string.15531554 Numbers and booleans in the input are converted to strings.1555 Null values are treated as empty strings. Arrays and objects1556 in the input are not supported.15571558 examples:1559 - program: 'join(", ")'1560 input: '["a","b,c,d","e"]'1561 output: ['"a, b,c,d, e"']1562 - program: 'join(" ")'1563 input: '["a",1,2.3,true,null,false]'1564 output: ['"a 1 2.3 true false"']15651566 - title: "`ascii_downcase`, `ascii_upcase`"1567 body: |15681569 Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1570 converted to the specified case.15711572 example:1573 - program: 'ascii_upcase'1574 input: '"useful but not for é"'1575 output: '"USEFUL BUT NOT FOR é"'15761577 - title: "`while(cond; update)`"1578 body: |15791580 The `while(cond; update)` function allows you to repeatedly1581 apply an update to `.` until `cond` is false.15821583 Note that `while(cond; update)` is internally defined as a1584 recursive jq function. Recursive calls within `while` will1585 not consume additional memory if `update` produces at most one1586 output for each input. See advanced topics below.15871588 examples:1589 - program: '[while(.<100; .*2)]'1590 input: '1'1591 output: ['[1,2,4,8,16,32,64]']15921593 - title: "`until(cond; next)`"1594 body: |15951596 The `until(cond; next)` function allows you to repeatedly1597 apply the expression `next`, initially to `.` then to its own1598 output, until `cond` is true. For example, this can be used1599 to implement a factorial function (see below).16001601 Note that `until(cond; next)` is internally defined as a1602 recursive jq function. Recursive calls within `until()` will1603 not consume additional memory if `next` produces at most one1604 output for each input. See advanced topics below.16051606 examples:1607 - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1608 input: '4'1609 output: ['24']161016111612 - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`, `recurse_down`"1613 body: |16141615 The `recurse(f)` function allows you to search through a1616 recursive structure, and extract interesting data from all1617 levels. Suppose your input represents a filesystem:16181619 {"name": "/", "children": [1620 {"name": "/bin", "children": [1621 {"name": "/bin/ls", "children": []},1622 {"name": "/bin/sh", "children": []}]},1623 {"name": "/home", "children": [1624 {"name": "/home/stephen", "children": [1625 {"name": "/home/stephen/jq", "children": []}]}]}]}16261627 Now suppose you want to extract all of the filenames1628 present. You need to retrieve `.name`, `.children[].name`,1629 `.children[].children[].name`, and so on. You can do this1630 with:16311632 recurse(.children[]) | .name16331634 When called without an argument, `recurse` is equivalent to1635 `recurse(.[]?)`.16361637 `recurse(f)` is identical to `recurse(f; . != null)` and can be1638 used without concerns about recursion depth.16391640 `recurse(f; condition)` is a generator which begins by1641 emitting . and then emits in turn .|f, .|f|f, .|f|f|f, ... so long1642 as the computed value satisfies the condition. For example,1643 to generate all the integers, at least in principle, one1644 could write `recurse(.+1; true)`.16451646 For legacy reasons, `recurse_down` exists as an alias to1647 calling `recurse` without arguments. This alias is considered1648 *deprecated* and will be removed in the next major release.16491650 The recursive calls in `recurse` will not consume additional1651 memory whenever `f` produces at most a single output for each1652 input.16531654 examples:1655 - program: 'recurse(.foo[])'1656 input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'1657 output:1658 - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'1659 - '{"foo":[]}'1660 - '{"foo":[{"foo":[]}]}'1661 - '{"foo":[]}'16621663 - program: 'recurse'1664 input: '{"a":0,"b":[1]}'1665 output:1666 - '{"a":0,"b":[1]}'1667 - '0'1668 - '[1]'1669 - '1'16701671 - program: 'recurse(. * .; . < 20)'1672 input: 21673 output:1674 - 21675 - 41676 - 1616771678 - title: "`walk(f)`"1679 body: |16801681 The `walk(f)` function applies f recursively to every1682 component of the input entity. When an array is1683 encountered, f is first applied to its elements and then to1684 the array itself; when an object is encountered, f is first1685 applied to all the values and then to the object. In1686 practice, f will usually test the type of its input, as1687 illustrated in the following examples. The first example1688 highlights the usefulness of processing the elements of an1689 array of arrays before processing the array itself. The second1690 example shows how all the keys of all the objects within the1691 input can be considered for alteration.16921693 examples:1694 - program: 'walk(if type == "array" then sort else . end)'1695 input: '[[4, 1, 7], [8, 5, 2], [3, 6, 9]]'1696 output:1697 - '[[1,4,7],[2,5,8],[3,6,9]]'16981699 - program: 'walk( if type == "object" then with_entries( .key |= sub( "^_+"; "") ) else . end )'1700 input: '[ { "_a": { "__b": 2 } } ]'1701 output:1702 - '[{"a":{"b":2}}]'17031704 - title: "`$ENV`, `env`"1705 body: |17061707 `$ENV` is an object representing the environment variables as1708 set when the jq program started.17091710 `env` outputs an object representing jq's current environment.17111712 At the moment there is no builtin for setting environment1713 variables.17141715 examples:1716 - program: '$ENV.PAGER'1717 input: 'null'1718 output: ['"less"']17191720 - program: 'env.PAGER'1721 input: 'null'1722 output: ['"less"']17231724 - title: "`transpose`"1725 body: |17261727 Transpose a possibly jagged matrix (an array of arrays).1728 Rows are padded with nulls so the result is always rectangular.17291730 examples:1731 - program: 'transpose'1732 input: '[[1], [2,3]]'1733 output: ['[[1,2],[null,3]]']17341735 - title: "`bsearch(x)`"1736 body: |17371738 bsearch(x) conducts a binary search for x in the input1739 array. If the input is sorted and contains x, then1740 bsearch(x) will return its index in the array; otherwise, if1741 the array is sorted, it will return (-1 - ix) where ix is an1742 insertion point such that the array would still be sorted1743 after the insertion of x at ix. If the array is not sorted,1744 bsearch(x) will return an integer that is probably of no1745 interest.17461747 examples:1748 - program: 'bsearch(0)'1749 input: '[0,1]'1750 output: ['0']1751 - program: 'bsearch(0)'1752 input: '[1,2,3]'1753 output: ['-1']1754 - program: 'bsearch(4) as $ix | if $ix < 0 then .[-(1+$ix)] = 4 else . end'1755 input: '[1,2,3]'1756 output: ['[1,2,3,4]']17571758 - title: "String interpolation - `\\(foo)`"1759 body: |17601761 Inside a string, you can put an expression inside parens1762 after a backslash. Whatever the expression returns will be1763 interpolated into the string.17641765 examples:1766 - program: '"The input was \(.), which is one less than \(.+1)"'1767 input: '42'1768 output: ['"The input was 42, which is one less than 43"']17691770 - title: "Convert to/from JSON"1771 body: |17721773 The `tojson` and `fromjson` builtins dump values as JSON texts1774 or parse JSON texts into values, respectively. The tojson1775 builtin differs from tostring in that tostring returns strings1776 unmodified, while tojson encodes strings as JSON strings.17771778 examples:1779 - program: '[.[]|tostring]'1780 input: '[1, "foo", ["foo"]]'1781 output: ['["1","foo","[\"foo\"]"]']1782 - program: '[.[]|tojson]'1783 input: '[1, "foo", ["foo"]]'1784 output: ['["1","\"foo\"","[\"foo\"]"]']1785 - program: '[.[]|tojson|fromjson]'1786 input: '[1, "foo", ["foo"]]'1787 output: ['[1,"foo",["foo"]]']17881789 - title: "Format strings and escaping"1790 body: |17911792 The `@foo` syntax is used to format and escape strings,1793 which is useful for building URLs, documents in a language1794 like HTML or XML, and so forth. `@foo` can be used as a1795 filter on its own, the possible escapings are:17961797 * `@text`:17981799 Calls `tostring`, see that function for details.18001801 * `@json`:18021803 Serializes the input as JSON.18041805 * `@html`:18061807 Applies HTML/XML escaping, by mapping the characters1808 `<>&'"` to their entity equivalents `&lt;`, `&gt;`,1809 `&amp;`, `&apos;`, `&quot;`.18101811 * `@uri`:18121813 Applies percent-encoding, by mapping all reserved URI1814 characters to a `%XX` sequence.18151816 * `@csv`:18171818 The input must be an array, and it is rendered as CSV1819 with double quotes for strings, and quotes escaped by1820 repetition.18211822 * `@tsv`:18231824 The input must be an array, and it is rendered as TSV1825 (tab-separated values). Each input array will be printed as1826 a single line. Fields are separated by a single1827 tab (ascii `0x09`). Input characters line-feed (ascii `0x0a`),1828 carriage-return (ascii `0x0d`), tab (ascii `0x09`) and1829 backslash (ascii `0x5c`) will be output as escape sequences1830 `\n`, `\r`, `\t`, `\\` respectively.18311832 * `@sh`:18331834 The input is escaped suitable for use in a command-line1835 for a POSIX shell. If the input is an array, the output1836 will be a series of space-separated strings.18371838 * `@base64`:18391840 The input is converted to base64 as specified by RFC 4648.18411842 * `@base64d`:18431844 The inverse of `@base64`, input is decoded as specified by RFC 4648.1845 Note\: If the decoded string is not UTF-8, the results are undefined.18461847 This syntax can be combined with string interpolation in a1848 useful way. You can follow a `@foo` token with a string1849 literal. The contents of the string literal will *not* be1850 escaped. However, all interpolations made inside that string1851 literal will be escaped. For instance,18521853 @uri "https://www.google.com/search?q=\(.search)"18541855 will produce the following output for the input1856 `{"search":"what is jq?"}`:18571858 "https://www.google.com/search?q=what%20is%20jq%3F"18591860 Note that the slashes, question mark, etc. in the URL are1861 not escaped, as they were part of the string literal.18621863 examples:1864 - program: '@html'1865 input: '"This works if x < y"'1866 output: ['"This works if x &lt; y"']18671868# - program: '@html "<span>Anonymous said: \(.)</span>"'1869# input: '"<script>alert(\"lol hax\");</script>"'1870# output: ["<span>Anonymous said: &lt;script&gt;alert(&quot;lol hax&quot;);&lt;/script&gt;</span>"]18711872 - program: '@sh "echo \(.)"'1873 input: "\"O'Hara's Ale\""1874 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]18751876 - program: '@base64'1877 input: '"This is a message"'1878 output: ['"VGhpcyBpcyBhIG1lc3NhZ2U="']18791880 - program: '@base64d'1881 input: '"VGhpcyBpcyBhIG1lc3NhZ2U="'1882 output: ['"This is a message"']18831884 - title: "Dates"1885 body: |18861887 jq provides some basic date handling functionality, with some1888 high-level and low-level builtins. In all cases these1889 builtins deal exclusively with time in UTC.18901891 The `fromdateiso8601` builtin parses datetimes in the ISO 86011892 format to a number of seconds since the Unix epoch1893 (1970-01-01T00:00:00Z). The `todateiso8601` builtin does the1894 inverse.18951896 The `fromdate` builtin parses datetime strings. Currently1897 `fromdate` only supports ISO 8601 datetime strings, but in the1898 future it will attempt to parse datetime strings in more1899 formats.19001901 The `todate` builtin is an alias for `todateiso8601`.19021903 The `now` builtin outputs the current time, in seconds since1904 the Unix epoch.19051906 Low-level jq interfaces to the C-library time functions are1907 also provided: `strptime`, `strftime`, `strflocaltime`,1908 `mktime`, `gmtime`, and `localtime`. Refer to your host1909 operating system's documentation for the format strings used1910 by `strptime` and `strftime`. Note: these are not necessarily1911 stable interfaces in jq, particularly as to their localization1912 functionality.19131914 The `gmtime` builtin consumes a number of seconds since the1915 Unix epoch and outputs a "broken down time" representation of1916 Greenwhich Meridian time as an array of numbers representing1917 (in this order): the year, the month (zero-based), the day of1918 the month (one-based), the hour of the day, the minute of the1919 hour, the second of the minute, the day of the week, and the1920 day of the year -- all one-based unless otherwise stated. The1921 day of the week number may be wrong on some systems for dates1922 before March 1st 1900, or after December 31 2099.19231924 The `localtime` builtin works like the `gmtime` builtin, but1925 using the local timezone setting.19261927 The `mktime` builtin consumes "broken down time"1928 representations of time output by `gmtime` and `strptime`.19291930 The `strptime(fmt)` builtin parses input strings matching the1931 `fmt` argument. The output is in the "broken down time"1932 representation consumed by `gmtime` and output by `mktime`.19331934 The `strftime(fmt)` builtin formats a time (GMT) with the1935 given format. The `strflocaltime` does the same, but using1936 the local timezone setting.19371938 The format strings for `strptime` and `strftime` are described1939 in typical C library documentation. The format string for ISO1940 8601 datetime is `"%Y-%m-%dT%H:%M:%SZ"`.19411942 jq may not support some or all of this date functionality on1943 some systems. In particular, the `%u` and `%j` specifiers for1944 `strptime(fmt)` are not supported on macOS.19451946 examples:1947 - program: 'fromdate'1948 input: '"2015-03-05T23:51:47Z"'1949 output: ['1425599507']19501951 - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")'1952 input: '"2015-03-05T23:51:47Z"'1953 output: ['[2015,2,5,23,51,47,4,63]']19541955 - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'1956 input: '"2015-03-05T23:51:47Z"'1957 output: ['1425599507']19581959 - title: "SQL-Style Operators"1960 body: |19611962 jq provides a few SQL-style operators.19631964 * INDEX(stream; index_expression):19651966 This builtin produces an object whose keys are computed by1967 the given index expression applied to each value from the1968 given stream.19691970 * JOIN($idx; stream; idx_expr; join_expr):19711972 This builtin joins the values from the given stream to the1973 given index. The index's keys are computed by applying the1974 given index expression to each value from the given stream.1975 An array of the value in the stream and the corresponding1976 value from the index is fed to the given join expression to1977 produce each result.19781979 * JOIN($idx; stream; idx_expr):19801981 Same as `JOIN($idx; stream; idx_expr; .)`.19821983 * JOIN($idx; idx_expr):19841985 This builtin joins the input `.` to the given index, applying1986 the given index expression to `.` to compute the index key.1987 The join operation is as described above.19881989 * IN(s):19901991 This builtin outputs `true` if `.` appears in the given1992 stream, otherwise it outputs `false`.19931994 * IN(source; s):19951996 This builtin outputs `true` if any value in the source stream1997 appears in the second stream, otherwise it outputs `false`.19981999 - title: "`builtins`"2000 body: |20012002 Returns a list of all builtin functions in the format `name/arity`.2003 Since functions with the same name but different arities are considered2004 separate functions, `all/0`, `all/1`, and `all/2` would all be present2005 in the list.20062007 - title: Conditionals and Comparisons2008 entries:2009 - title: "`==`, `!=`"2010 body: |20112012 The expression 'a == b' will produce 'true' if the result of a and b2013 are equal (that is, if they represent equivalent JSON documents) and2014 'false' otherwise. In particular, strings are never considered equal2015 to numbers. If you're coming from Javascript, jq's == is like2016 Javascript's === - considering values equal only when they have the2017 same type as well as the same value.20182019 != is "not equal", and 'a != b' returns the opposite value of 'a == b'20202021 examples:2022 - program: '.[] == 1'2023 input: '[1, 1.0, "1", "banana"]'2024 output: ['true', 'true', 'false', 'false']20252026 - title: if-then-else2027 body: |20282029 `if A then B else C end` will act the same as `B` if `A`2030 produces a value other than false or null, but act the same2031 as `C` otherwise.20322033 Checking for false or null is a simpler notion of2034 "truthiness" than is found in Javascript or Python, but it2035 means that you'll sometimes have to be more explicit about2036 the condition you want: you can't test whether, e.g. a2037 string is empty using `if .name then A else B end`, you'll2038 need something more like `if (.name | length) > 0 then A else2039 B end` instead.20402041 If the condition `A` produces multiple results, then `B` is evaluated2042 once for each result that is not false or null, and `C` is evaluated2043 once for each false or null.20442045 More cases can be added to an if using `elif A then B` syntax.20462047 examples:2048 - program: |-2049 if . == 0 then2050 "zero"2051 elif . == 1 then2052 "one"2053 else2054 "many"2055 end2056 input: 22057 output: ['"many"']20582059 - title: "`>, >=, <=, <`"2060 body: |20612062 The comparison operators `>`, `>=`, `<=`, `<` return whether2063 their left argument is greater than, greater than or equal2064 to, less than or equal to or less than their right argument2065 (respectively).20662067 The ordering is the same as that described for `sort`, above.20682069 examples:2070 - program: '. < 5'2071 input: 22072 output: ['true']20732074 - title: and/or/not2075 body: |20762077 jq supports the normal Boolean operators and/or/not. They have the2078 same standard of truth as if expressions - false and null are2079 considered "false values", and anything else is a "true value".20802081 If an operand of one of these operators produces multiple2082 results, the operator itself will produce a result for each input.20832084 `not` is in fact a builtin function rather than an operator,2085 so it is called as a filter to which things can be piped2086 rather than with special syntax, as in `.foo and .bar |2087 not`.20882089 These three only produce the values "true" and "false", and2090 so are only useful for genuine Boolean operations, rather2091 than the common Perl/Python/Ruby idiom of2092 "value_that_may_be_null or default". If you want to use this2093 form of "or", picking between two values rather than2094 evaluating a condition, see the "//" operator below.20952096 examples:2097 - program: '42 and "a string"'2098 input: 'null'2099 output: ['true']2100 - program: '(true, false) or false'2101 input: 'null'2102 output: ['true', 'false']2103# - program: '(true, false) and (true, false)'2104# input: 'null'2105# output: ['true', 'false', 'false', 'false']2106 - program: '(true, true) and (true, false)'2107 input: 'null'2108 output: ['true', 'false', 'true', 'false']2109 - program: '[true, false | not]'2110 input: 'null'2111 output: ['[false, true]']21122113 - title: "Alternative operator: `//`"2114 body: |21152116 A filter of the form `a // b` produces the same2117 results as `a`, if `a` produces results other than `false`2118 and `null`. Otherwise, `a // b` produces the same results as `b`.21192120 This is useful for providing defaults: `.foo // 1` will2121 evaluate to `1` if there's no `.foo` element in the2122 input. It's similar to how `or` is sometimes used in Python2123 (jq's `or` operator is reserved for strictly Boolean2124 operations).21252126 examples:2127 - program: '.foo // 42'2128 input: '{"foo": 19}'2129 output: [19]2130 - program: '.foo // 42'2131 input: '{}'2132 output: [42]21332134 - title: try-catch2135 body: |21362137 Errors can be caught by using `try EXP catch EXP`. The first2138 expression is executed, and if it fails then the second is2139 executed with the error message. The output of the handler,2140 if any, is output as if it had been the output of the2141 expression to try.21422143 The `try EXP` form uses `empty` as the exception handler.21442145 examples:2146 - program: 'try .a catch ". is not an object"'2147 input: 'true'2148 output: ['". is not an object"']2149 - program: '[.[]|try .a]'2150 input: '[{}, true, {"a":1}]'2151 output: ['[null, 1]']2152 - program: 'try error("some exception") catch .'2153 input: 'true'2154 output: ['"some exception"']21552156 - title: Breaking out of control structures2157 body: |21582159 A convenient use of try/catch is to break out of control2160 structures like `reduce`, `foreach`, `while`, and so on.21612162 For example:21632164 # Repeat an expression until it raises "break" as an2165 # error, then stop repeating without re-raising the error.2166 # But if the error caught is not "break" then re-raise it.2167 try repeat(exp) catch .=="break" then empty else error;21682169 jq has a syntax for named lexical labels to "break" or "go (back) to":21702171 label $out | ... break $out ...21722173 The `break $label_name` expression will cause the program to2174 to act as though the nearest (to the left) `label $label_name`2175 produced `empty`.21762177 The relationship between the `break` and corresponding `label`2178 is lexical: the label has to be "visible" from the break.21792180 To break out of a `reduce`, for example:21812182 label $out | reduce .[] as $item (null; if .==false then break $out else ... end)21832184 The following jq program produces a syntax error:21852186 break $out21872188 because no label `$out` is visible.21892190 - title: "Error Suppression / Optional Operator: `?`"2191 body: |21922193 The `?` operator, used as `EXP?`, is shorthand for `try EXP`.21942195 examples:2196 - program: '[.[]|(.a)?]'2197 input: '[{}, true, {"a":1}]'2198 output: ['[null, 1]']219922002201 - title: Regular expressions (PCRE)2202 body: |22032204 jq uses the Oniguruma regular expression library, as do php,2205 ruby, TextMate, Sublime Text, etc, so the description here2206 will focus on jq specifics.22072208 The jq regex filters are defined so that they can be used using2209 one of these patterns:22102211 STRING | FILTER( REGEX )2212 STRING | FILTER( REGEX; FLAGS )2213 STRING | FILTER( [REGEX] )2214 STRING | FILTER( [REGEX, FLAGS] )22152216 where:2217 * STRING, REGEX and FLAGS are jq strings and subject to jq string interpolation;2218 * REGEX, after string interpolation, should be a valid PCRE regex;2219 * FILTER is one of `test`, `match`, or `capture`, as described below.22202221 FLAGS is a string consisting of one of more of the supported flags:22222223 * `g` - Global search (find all matches, not just the first)2224 * `i` - Case insensitive search2225 * `m` - Multi line mode ('.' will match newlines)2226 * `n` - Ignore empty matches2227 * `p` - Both s and m modes are enabled2228 * `s` - Single line mode ('^' -> '\A', '$' -> '\Z')2229 * `l` - Find longest possible matches2230 * `x` - Extended regex format (ignore whitespace and comments)22312232 To match whitespace in an x pattern use an escape such as \s, e.g.22332234 * test( "a\\sb", "x" ).22352236 Note that certain flags may also be specified within REGEX, e.g.22372238 * jq -n '("test", "TEst", "teST", "TEST") | test( "(?i)te(?-i)st" )'22392240 evaluates to: true, true, false, false.22412242 entries:2243 - title: "`test(val)`, `test(regex; flags)`"2244 body: |22452246 Like `match`, but does not return match objects, only `true` or `false`2247 for whether or not the regex matches the input.22482249 examples:2250 - program: 'test("foo")'2251 input: '"foo"'2252 output: ['true']2253 - program: '.[] | test("a b c # spaces are ignored"; "ix")'2254 input: '["xabcd", "ABC"]'2255 output: ['true', 'true']22562257 - title: "`match(val)`, `match(regex; flags)`"2258 body: |22592260 **match** outputs an object for each match it finds. Matches have2261 the following fields:22622263 * `offset` - offset in UTF-8 codepoints from the beginning of the input2264 * `length` - length in UTF-8 codepoints of the match2265 * `string` - the string that it matched2266 * `captures` - an array of objects representing capturing groups.22672268 Capturing group objects have the following fields:22692270 * `offset` - offset in UTF-8 codepoints from the beginning of the input2271 * `length` - length in UTF-8 codepoints of this capturing group2272 * `string` - the string that was captured2273 * `name` - the name of the capturing group (or `null` if it was unnamed)22742275 Capturing groups that did not match anything return an offset of -122762277 examples:2278 - program: 'match("(abc)+"; "g")'2279 input: '"abc abc"'2280 output:2281 - '{"offset": 0, "length": 3, "string": "abc", "captures": [{"offset": 0, "length": 3, "string": "abc", "name": null}]}'2282 - '{"offset": 4, "length": 3, "string": "abc", "captures": [{"offset": 4, "length": 3, "string": "abc", "name": null}]}'2283 - program: 'match("foo")'2284 input: '"foo bar foo"'2285 output: ['{"offset": 0, "length": 3, "string": "foo", "captures": []}']2286 - program: 'match(["foo", "ig"])'2287 input: '"foo bar FOO"'2288 output:2289 - '{"offset": 0, "length": 3, "string": "foo", "captures": []}'2290 - '{"offset": 8, "length": 3, "string": "FOO", "captures": []}'2291 - program: 'match("foo (?<bar123>bar)? foo"; "ig")'2292 input: '"foo bar foo foo foo"'2293 output:2294 - '{"offset": 0, "length": 11, "string": "foo bar foo", "captures": [{"offset": 4, "length": 3, "string": "bar", "name": "bar123"}]}'2295 - '{"offset": 12, "length": 8, "string": "foo foo", "captures": [{"offset": -1, "length": 0, "string": null, "name": "bar123"}]}'22962297 - program: '[ match("."; "g")] | length'2298 input: '"abc"'2299 output: [3]230023012302 - title: "`capture(val)`, `capture(regex; flags)`"2303 body: |23042305 Collects the named captures in a JSON object, with the name2306 of each capture as the key, and the matched string as the2307 corresponding value.23082309 examples:2310 - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2311 input: '"xyzzy-14"'2312 output: ['{ "a": "xyzzy", "n": "14" }']23132314 - title: "`scan(regex)`, `scan(regex; flags)`"2315 body: |23162317 Emit a stream of the non-overlapping substrings of the input2318 that match the regex in accordance with the flags, if any2319 have been specified. If there is no match, the stream is empty.2320 To capture all the matches for each input string, use the idiom2321 `[ expr ]`, e.g. `[ scan(regex) ]`.23222323 example:2324 - program: 'scan("c")'2325 input: '"abcdefabc"'2326 output: ['"c"', '"c"']23272328 - program: 'scan("b")'2329 input: ("", "")2330 output: ['[]', '[]']23312332 - title: "`split(regex; flags)`"2333 body: |23342335 For backwards compatibility, `split` splits on a string, not a regex.23362337 example:2338 - program: 'split(", *"; null)'2339 input: '"ab,cd, ef"'2340 output: ['"ab","cd","ef"']234123422343 - title: "`splits(regex)`, `splits(regex; flags)`"2344 body: |23452346 These provide the same results as their `split` counterparts,2347 but as a stream instead of an array.23482349 example:2350 - program: 'splits(", *")'2351 input: '("ab,cd", "ef, gh")'2352 output: ['"ab"', '"cd"', '"ef"', '"gh"']23532354 - title: "`sub(regex; tostring)` `sub(regex; string; flags)`"2355 body: |23562357 Emit the string obtained by replacing the first match of regex in the2358 input string with `tostring`, after interpolation. `tostring` should2359 be a jq string, and may contain references to named captures. The2360 named captures are, in effect, presented as a JSON object (as2361 constructed by `capture`) to `tostring`, so a reference to a captured2362 variable named "x" would take the form: "\(.x)".23632364 example:2365 - program: 'sub("^[^a-z]*(?<x>[a-z]*).*")'2366 input: '"123abc456"'2367 output: '"ZabcZabc"'236823692370 - title: "`gsub(regex; string)`, `gsub(regex; string; flags)`"2371 body: |23722373 `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2374 replaced by the string, after interpolation.23752376 example:2377 - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2378 input: '"Abcabc"'2379 output: '"+A-+a-"'238023812382 - title: Advanced features2383 body: |2384 Variables are an absolute necessity in most programming languages, but2385 they're relegated to an "advanced feature" in jq.23862387 In most languages, variables are the only means of passing around2388 data. If you calculate a value, and you want to use it more than once,2389 you'll need to store it in a variable. To pass a value to another part2390 of the program, you'll need that part of the program to define a2391 variable (as a function parameter, object member, or whatever) in2392 which to place the data.23932394 It is also possible to define functions in jq, although this is2395 is a feature whose biggest use is defining jq's standard library2396 (many jq functions such as `map` and `find` are in fact written2397 in jq).23982399 jq has reduction operators, which are very powerful but a bit2400 tricky. Again, these are mostly used internally, to define some2401 useful bits of jq's standard library.24022403 It may not be obvious at first, but jq is all about generators2404 (yes, as often found in other languages). Some utilities are2405 provided to help deal with generators.24062407 Some minimal I/O support (besides reading JSON from standard2408 input, and writing JSON to standard output) is available.24092410 Finally, there is a module/library system.24112412 entries:2413 - title: "Variable / Symbolic Binding Operator: `... as $identifier | ...`"2414 body: |24152416 In jq, all filters have an input and an output, so manual2417 plumbing is not necessary to pass a value from one part of a program2418 to the next. Many expressions, for instance `a + b`, pass their input2419 to two distinct subexpressions (here `a` and `b` are both passed the2420 same input), so variables aren't usually necessary in order to use a2421 value twice.24222423 For instance, calculating the average value of an array of numbers2424 requires a few variables in most languages - at least one to hold the2425 array, perhaps one for each element or for a loop counter. In jq, it's2426 simply `add / length` - the `add` expression is given the array and2427 produces its sum, and the `length` expression is given the array and2428 produces its length.24292430 So, there's generally a cleaner way to solve most problems in jq than2431 defining variables. Still, sometimes they do make things easier, so jq2432 lets you define variables using `expression as $variable`. All2433 variable names start with `$`. Here's a slightly uglier version of the2434 array-averaging example:24352436 length as $array_length | add / $array_length24372438 We'll need a more complicated problem to find a situation where using2439 variables actually makes our lives easier.244024412442 Suppose we have an array of blog posts, with "author" and "title"2443 fields, and another object which is used to map author usernames to2444 real names. Our input looks like:24452446 {"posts": [{"title": "Frist psot", "author": "anon"},2447 {"title": "A well-written article", "author": "person1"}],2448 "realnames": {"anon": "Anonymous Coward",2449 "person1": "Person McPherson"}}24502451 We want to produce the posts with the author field containing a real2452 name, as in:24532454 {"title": "Frist psot", "author": "Anonymous Coward"}2455 {"title": "A well-written article", "author": "Person McPherson"}24562457 We use a variable, $names, to store the realnames object, so that we2458 can refer to it later when looking up author usernames:24592460 .realnames as $names | .posts[] | {title, author: $names[.author]}24612462 The expression `exp as $x | ...` means: for each value of expression2463 `exp`, run the rest of the pipeline with the entire original input, and2464 with `$x` set to that value. Thus `as` functions as something of a2465 foreach loop.24662467 Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2468 `{$foo}` is a handy way of writing `{foo:$foo}`.24692470 Multiple variables may be declared using a single `as` expression by2471 providing a pattern that matches the structure of the input2472 (this is known as "destructuring"):24732474 . as {realnames: $names, posts: [$first, $second]} | ...24752476 The variable declarations in array patterns (e.g., `. as2477 [$first, $second]`) bind to the elements of the array in from2478 the element at index zero on up, in order. When there is no2479 value at the index for an array pattern element, `null` is2480 bound to that variable.24812482 Variables are scoped over the rest of the expression that defines2483 them, so24842485 .realnames as $names | (.posts[] | {title, author: $names[.author]})24862487 will work, but24882489 (.realnames as $names | .posts[]) | {title, author: $names[.author]}24902491 won't.24922493 For programming language theorists, it's more accurate to2494 say that jq variables are lexically-scoped bindings. In2495 particular there's no way to change the value of a binding;2496 one can only setup a new binding with the same name, but which2497 will not be visible where the old one was.24982499 examples:2500 - program: '.bar as $x | .foo | . + $x'2501 input: '{"foo":10, "bar":200}'2502 output: ['210']2503 - program: '. as $i|[(.*2|. as $i| $i), $i]'2504 input: '5'2505 output: ['[10,5]']2506 - program: '. as [$a, $b, {c: $c}] | $a + $b + $c'2507 input: '[2, 3, {"c": 4, "d": 5}]'2508 output: ['9']2509 - program: '.[] as [$a, $b] | {a: $a, b: $b}'2510 input: '[[0], [0, 1], [2, 1, 0]]'2511 output: ['{"a":0,"b":null}', '{"a":0,"b":1}', '{"a":2,"b":1}']25122513 - title: 'Destructuring Alternative Operator: `?//`'2514 body: |2515 2516 The destructuring alternative operator provides a concise mechanism2517 for destructuring an input that can take one of several forms.25182519 Suppose we have an API that returns a list of resources and events2520 associated with them, and we want to get the user_id and timestamp of2521 the first event for each resource. The API (having been clumsily2522 converted from XML) will only wrap the events in an array if the resource2523 has multiple events:2524 2525 {"resources": [{"id": 1, "kind": "widget", "events": {"action": "create", "user_id": 1, "ts": 13}},2526 {"id": 2, "kind": "widget", "events": [{"action": "create", "user_id": 1, "ts": 14}, {"action": "destroy", "user_id": 1, "ts": 15}]}]}2527 2528 We can use the destructuring alternative operator to handle this structural change simply:25292530 .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$user_id, $ts}]} | {$user_id, $kind, $id, $ts}25312532 Or, if we aren't sure if the input is an array of values or an object:25332534 .[] as [$id, $kind, $user_id, $ts] ?// {$id, $kind, $user_id, $ts} | ...25352536 Each alternative need not define all of the same variables, but all named2537 variables will be available to the subsequent expression. Variables not2538 matched in the alternative that succeeded will be `null`:25392540 .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$first_user_id, $first_ts}]} | {$user_id, $first_user_id, $kind, $id, $ts, $first_ts}25412542 Additionally, if the subsequent expression returns an error, the2543 alternative operator will attempt to try the next binding. Errors2544 that occur during the final alternative are passed through.25452546 [[3]] | .[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end25472548 examples:2549 - program: '.[] as {$a, $b, c: {$d, $e}} ?// {$a, $b, c: [{$d, $e}]} | {$a, $b, $d, $e}'2550 input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2551 output: ['{"a":1,"b":2,"d":3,"e":4}', '{"a":1,"b":2,"d":3,"e":4}']2552 - program: '.[] as {$a, $b, c: {$d}} ?// {$a, $b, c: [{$e}]} | {$a, $b, $d, $e}'2553 input: '[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]'2554 output: ['{"a":1,"b":2,"d":3,"e":null}', '{"a":1,"b":2,"d":null,"e":4}']2555 - program: '.[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end'2556 input: '[[3]]'2557 output: ['{"a":null,"b":3}']25582559 - title: 'Defining Functions'2560 body: |25612562 You can give a filter a name using "def" syntax:25632564 def increment: . + 1;25652566 From then on, `increment` is usable as a filter just like a2567 builtin function (in fact, this is how many of the builtins2568 are defined). A function may take arguments:25692570 def map(f): [.[] | f];25712572 Arguments are passed as _filters_ (functions with no2573 arguments), _not_ as values. The same argument may be2574 referenced multiple times with different inputs (here `f` is2575 run for each element of the input array). Arguments to a2576 function work more like callbacks than like value arguments.2577 This is important to understand. Consider:25782579 def foo(f): f|f;2580 5|foo(.*2)25812582 The result will be 20 because `f` is `.*2`, and during the2583 first invocation of `f` `.` will be 5, and the second time it2584 will be 10 (5 * 2), so the result will be 20. Function2585 arguments are filters, and filters expect an input when2586 invoked.25872588 If you want the value-argument behaviour for defining simple2589 functions, you can just use a variable:25902591 def addvalue(f): f as $f | map(. + $f);25922593 Or use the short-hand:25942595 def addvalue($f): ...;25962597 With either definition, `addvalue(.foo)` will add the current2598 input's `.foo` field to each element of the array. Do note2599 that calling `addvalue(.[])` will cause the `map(. + $f)` part2600 to be evaluated once per value in the value of `.` at the call2601 site.26022603 Multiple definitions using the same function name are allowed.2604 Each re-definition replaces the previous one for the same2605 number of function arguments, but only for references from2606 functions (or main program) subsequent to the re-definition.2607 See also the section below on scoping.26082609 examples:2610 - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'2611 input: '[[1,2],[10,20]]'2612 output: ['[[1,2,1], [10,20,10]]']2613 - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'2614 input: '[[1,2],[10,20]]'2615 output: ['[[1,2,1,2], [10,20,1,2]]']26162617 - title: 'Scoping'2618 body: |26192620 There are two types of symbols in jq: value bindings (a.k.a.,2621 "variables"), and functions. Both are scoped lexically,2622 with expressions being able to refer only to symbols that2623 have been defined "to the left" of them. The only exception2624 to this rule is that functions can refer to themselves so as2625 to be able to create recursive functions.26262627 For example, in the following expression there is a binding2628 which is visible "to the right" of it, `... | .*3 as2629 $times_three | [. + $times_three] | ...`, but not "to the2630 left". Consider this expression now, `... | (.*3 as2631 $times_three | [.+ $times_three]) | ...`: here the binding2632 `$times_three` is _not_ visible past the closing parenthesis.26332634 - title: Reduce2635 body: |26362637 The `reduce` syntax in jq allows you to combine all of the2638 results of an expression by accumulating them into a single2639 answer. As an example, we'll pass `[3,2,1]` to this expression:26402641 reduce .[] as $item (0; . + $item)26422643 For each result that `.[]` produces, `. + $item` is run to2644 accumulate a running total, starting from 0. In this2645 example, `.[]` produces the results 3, 2, and 1, so the2646 effect is similar to running something like this:26472648 0 | (3 as $item | . + $item) |2649 (2 as $item | . + $item) |2650 (1 as $item | . + $item)26512652 examples:2653 - program: 'reduce .[] as $item (0; . + $item)'2654 input: '[10,2,5,3]'2655 output: ['20']26562657 - title: "`isempty(exp)`"2658 body: |26592660 Returns true if `exp` produces no outputs, false otherwise.26612662 examples:2663 - program: 'isempty(empty)'2664 input: 'null'2665 output: ['true']26662667 - title: "`limit(n; exp)`"2668 body: |26692670 The `limit` function extracts up to `n` outputs from `exp`.26712672 examples:2673 - program: '[limit(3;.[])]'2674 input: '[0,1,2,3,4,5,6,7,8,9]'2675 output: ['[0,1,2]']26762677 - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"2678 body: |26792680 The `first(expr)` and `last(expr)` functions extract the first2681 and last values from `expr`, respectively.26822683 The `nth(n; expr)` function extracts the nth value output by2684 `expr`. This can be defined as `def nth(n; expr):2685 last(limit(n + 1; expr));`. Note that `nth(n; expr)` doesn't2686 support negative values of `n`.26872688 examples:2689 - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'2690 input: '10'2691 output: ['[0,9,5]']26922693 - title: "`first`, `last`, `nth(n)`"2694 body: |26952696 The `first` and `last` functions extract the first2697 and last values from any array at `.`.26982699 The `nth(n)` function extracts the nth value of any array at `.`.27002701 examples:2702 - program: '[range(.)]|[first, last, nth(5)]'2703 input: '10'2704 output: ['[0,9,5]']27052706 - title: "`foreach`"2707 body: |27082709 The `foreach` syntax is similar to `reduce`, but intended to2710 allow the construction of `limit` and reducers that produce2711 intermediate results (see example).27122713 The form is `foreach EXP as $var (INIT; UPDATE; EXTRACT)`.2714 Like `reduce`, `INIT` is evaluated once to produce a state2715 value, then each output of `EXP` is bound to `$var`, `UPDATE`2716 is evaluated for each output of `EXP` with the current state2717 and with `$var` visible. Each value output by `UPDATE`2718 replaces the previous state. Finally, `EXTRACT` is evaluated2719 for each new state to extract an output of `foreach`.27202721 This is mostly useful only for constructing `reduce`- and2722 `limit`-like functions. But it is much more general, as it2723 allows for partial reductions (see the example below).27242725 examples:2726 - program: '[foreach .[] as $item2727 ([[],[]];2728 if $item == null then [[],.[0]] else [(.[0] + [$item]),[]] end;2729 if $item == null then .[1] else empty end)]'2730 input: '[1,2,3,4,null,"a","b",null]'2731 output: ['[[1,2,3,4],["a","b"]]']27322733 - title: Recursion2734 body: |27352736 As described above, `recurse` uses recursion, and any jq2737 function can be recursive. The `while` builtin is also2738 implemented in terms of recursion.27392740 Tail calls are optimized whenever the expression to the left of2741 the recursive call outputs its last value. In practice this2742 means that the expression to the left of the recursive call2743 should not produce more than one output for each input.27442745 For example:27462747 def recurse(f): def r: ., (f | select(. != null) | r); r;27482749 def while(cond; update):2750 def _while:2751 if cond then ., (update | _while) else empty end;2752 _while;27532754 def repeat(exp):2755 def _repeat:2756 exp, _repeat;2757 _repeat;27582759 - title: Generators and iterators2760 body: |27612762 Some jq operators and functions are actually generators in2763 that they can produce zero, one, or more values for each2764 input, just as one might expect in other programming2765 languages that have generators. For example, `.[]`2766 generates all the values in its input (which must be an2767 array or an object), `range(0; 10)` generates the integers2768 between 0 and 10, and so on.27692770 Even the comma operator is a generator, generating first the2771 values generated by the expression to the left of the comma,2772 then for each of those, the values generate by the2773 expression on the right of the comma.27742775 The `empty` builtin is the generator that produces zero2776 outputs. The `empty` builtin backtracks to the preceding2777 generator expression.27782779 All jq functions can be generators just by using builtin2780 generators. It is also possible to define new generators2781 using only recursion and the comma operator. If the2782 recursive call(s) is(are) "in tail position" then the2783 generator will be efficient. In the example below the2784 recursive call by `_range` to itself is in tail position.2785 The example shows off three advanced topics: tail recursion,2786 generator construction, and sub-functions.27872788 examples:2789 - program: 'def range(init; upto; by):2790 def _range:2791 if (by > 0 and . < upto) or (by < 0 and . > upto)2792 then ., ((.+by)|_range)2793 else . end;2794 if by == 0 then init else init|_range end |2795 select((by > 0 and . < upto) or (by < 0 and . > upto));2796 range(0; 10; 3)'2797 input: 'null'2798 output: ['0', '3', '6', '9']2799 - program: 'def while(cond; update):2800 def _while:2801 if cond then ., (update | _while) else empty end;2802 _while;2803 [while(.<100; .*2)]'2804 input: '1'2805 output: ['[1,2,4,8,16,32,64]']28062807 - title: 'Math'2808 body: |28092810 jq currently only has IEEE754 double-precision (64-bit) floating2811 point number support.28122813 Besides simple arithmetic operators such as `+`, jq also has most2814 standard math functions from the C math library. C math functions2815 that take a single input argument (e.g., `sin()`) are available as2816 zero-argument jq functions. C math functions that take two input2817 arguments (e.g., `pow()`) are available as two-argument jq2818 functions that ignore `.`. C math functions that take three input2819 arguments are available as three-argument jq functions that ignore2820 `.`.28212822 Availability of standard math functions depends on the2823 availability of the corresponding math functions in your operating2824 system and C math library. Unavailable math functions will be2825 defined but will raise an error.28262827 One-input C math functions: `acos` `acosh` `asin` `asinh` `atan`2828 `atanh` `cbrt` `ceil` `cos` `cosh` `erf` `erfc` `exp` `exp10`2829 `exp2` `expm1` `fabs` `floor` `gamma` `j0` `j1` `lgamma` `log`2830 `log10` `log1p` `log2` `logb` `nearbyint` `pow10` `rint` `round`2831 `significand` `sin` `sinh` `sqrt` `tan` `tanh` `tgamma` `trunc`2832 `y0` `y1`.28332834 Two-input C math functions: `atan2` `copysign` `drem` `fdim`2835 `fmax` `fmin` `fmod` `frexp` `hypot` `jn` `ldexp` `modf`2836 `nextafter` `nexttoward` `pow` `remainder` `scalb` `scalbln` `yn`.28372838 Three-input C math functions: `fma`.28392840 See your system's manual for more information on each of these.28412842 - title: 'I/O'2843 body: |28442845 At this time jq has minimal support for I/O, mostly in the2846 form of control over when inputs are read. Two builtins functions2847 are provided for this, `input` and `inputs`, that read from the2848 same sources (e.g., `stdin`, files named on the command-line) as2849 jq itself. These two builtins, and jq's own reading actions, can2850 be interleaved with each other.28512852 Two builtins provide minimal output capabilities, `debug`, and2853 `stderr`. (Recall that a jq program's output values are always2854 output as JSON texts on `stdout`.) The `debug` builtin can have2855 application-specific behavior, such as for executables that use2856 the libjq C API but aren't the jq executable itself. The `stderr`2857 builtin outputs its input in raw mode to stder with no additional2858 decoration, not even a newline.28592860 Most jq builtins are referentially transparent, and yield constant2861 and repeatable value streams when applied to constant inputs.2862 This is not true of I/O builtins.28632864 entries:2865 - title: "`input`"2866 body: |28672868 Outputs one new input.28692870 - title: "`inputs`"2871 body: |28722873 Outputs all remaining inputs, one by one.28742875 This is primarily useful for reductions over a program's2876 inputs.28772878 - title: "`debug`"2879 body: |28802881 Causes a debug message based on the input value to be2882 produced. The jq executable wraps the input value with2883 `["DEBUG:", <input-value>]` and prints that and a newline on2884 stderr, compactly. This may change in the future.28852886 - title: "`stderr`"2887 body: |28882889 Prints its input in raw and compact mode to stderr with no2890 additional decoration, not even a newline.28912892 - title: "`input_filename`"2893 body: |28942895 Returns the name of the file whose input is currently being2896 filtered. Note that this will not work well unless jq is2897 running in a UTF-8 locale.28982899 - title: "`input_line_number`"2900 body: |29012902 Returns the line number of the input currently being filtered.29032904 - title: 'Streaming'2905 body: |29062907 With the `--stream` option jq can parse input texts in a streaming2908 fashion, allowing jq programs to start processing large JSON texts2909 immediately rather than after the parse completes. If you have a2910 single JSON text that is 1GB in size, streaming it will allow you2911 to process it much more quickly.29122913 However, streaming isn't easy to deal with as the jq program will2914 have `[<path>, <leaf-value>]` (and a few other forms) as inputs.29152916 Several builtins are provided to make handling streams easier.29172918 The examples below use the streamed form of `[0,[1]]`, which is2919 `[[0],0],[[1,0],1],[[1,0]],[[1]]`.29202921 Streaming forms include `[<path>, <leaf-value>]` (to indicate any2922 scalar value, empty array, or empty object), and `[<path>]` (to2923 indicate the end of an array or object). Future versions of jq2924 run with `--stream` and `-seq` may output additional forms such as2925 `["error message"]` when an input text fails to parse.29262927 entries:2928 - title: "`truncate_stream(stream_expression)`"2929 body: |29302931 Consumes a number as input and truncates the corresponding2932 number of path elements from the left of the outputs of the2933 given streaming expression.29342935 examples:2936 - program: '[1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]'2937 input: '1'2938 output: ['[[[0],2],[[0]]]']29392940 - title: "`fromstream(stream_expression)`"2941 body: |29422943 Outputs values corresponding to the stream expression's2944 outputs.29452946 examples:2947 - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'2948 input: 'null'2949 output: ['[2]']29502951 - title: "`tostream`"2952 body: |29532954 The `tostream` builtin outputs the streamed form of its input.29552956 examples:2957 - program: '. as $dot|fromstream($dot|tostream)|.==$dot'2958 input: '[0,[1,{"a":1},{"b":2}]]'2959 output: ['true']29602961 - title: Assignment2962 body: |2963 Assignment works a little differently in jq than in most2964 programming languages. jq doesn't distinguish between references2965 to and copies of something - two objects or arrays are either2966 equal or not equal, without any further notion of being "the2967 same object" or "not the same object".29682969 If an object has two fields which are arrays, `.foo` and `.bar`,2970 and you append something to `.foo`, then `.bar` will not get2971 bigger, even if you've previously set `.bar = .foo`. If you're2972 used to programming in languages like Python, Java, Ruby,2973 Javascript, etc. then you can think of it as though jq does a full2974 deep copy of every object before it does the assignment (for2975 performance it doesn't actually do that, but that's the general2976 idea).29772978 This means that it's impossible to build circular values in jq2979 (such as an array whose first element is itself). This is quite2980 intentional, and ensures that anything a jq program can produce2981 can be represented in JSON.29822983 All the assignment operators in jq have path expressions on the2984 left-hand side (LHS). The right-hand side (RHS) provides values2985 to set to the paths named by the LHS path expressions.29862987 Values in jq are always immutable. Internally, assignment works2988 by using a reduction to compute new, replacement values for `.` that2989 have had all the desired assignments applied to `.`, then2990 outputting the modified value. This might be made clear by this2991 example: `{a:{b:{c:1}}} | (.a.b|=3), .`. This will output2992 `{"a":{"b":3}}` and `{"a":{"b":{"c":1}}}` because the last2993 sub-expression, `.`, sees the original value, not the modified2994 value.29952996 Most users will want to use modification assignment operators,2997 such as `|=` or `+=`, rather than `=`.29982999 Note that the LHS of assignment operators refers to a value in3000 `.`. Thus `$var.foo = 1` won't work as expected (`$var.foo` is3001 not a valid or useful path expression in `.`); use `$var | .foo =3002 1` instead.30033004 Note too that `.a,.b=0` does not set `.a` and `.b`, but3005 `(.a,.b)=0` sets both.30063007 entries:3008 - title: "Update-assignment: `|=`"3009 body: |3010 This is the "update" operator '|='. It takes a filter on the3011 right-hand side and works out the new value for the property3012 of `.` being assigned to by running the old value through this3013 expression. For instance, (.foo, .bar) |= .+1 will build an3014 object with the "foo" field set to the input's "foo" plus 1,3015 and the "bar" field set to the input's "bar" plus 1.30163017 The left-hand side can be any general path expression; see `path()`.30183019 Note that the left-hand side of '|=' refers to a value in `.`.3020 Thus `$var.foo |= . + 1` won't work as expected (`$var.foo` is3021 not a valid or useful path expression in `.`); use `$var |3022 .foo |= . + 1` instead.30233024 If the right-hand side outputs no values (i.e., `empty`), then3025 the left-hand side path will be deleted, as with `del(path)`.30263027 If the right-hand side outputs multiple values, only the first3028 one will be used (COMPATIBILITY NOTE: in jq 1.5 and earlier3029 releases, it used to be that only the last one was used).30303031 examples:3032 - program: '(..|select(type=="boolean")) |= if . then 1 else 0 end'3033 input: '[true,false,[5,true,[true,[false]],false]]'3034 output: ['[1,0,[5,1,[1,[0]],0]]']30353036 - title: "Arithmetic update-assignment: `+=`, `-=`, `*=`, `/=`, `%=`, `//=`"3037 body: |30383039 jq has a few operators of the form `a op= b`, which are all3040 equivalent to `a |= . op b`. So, `+= 1` can be used to3041 increment values, being the same as `|= . + 1`.30423043 examples:3044 - program: .foo += 13045 input: '{"foo": 42}'3046 output: ['{"foo": 43}']30473048 - title: "Plain assignment: `=`"3049 body: |30503051 This is the plain assignment operator. Unlike the others, the3052 input to the right-hand-side (RHS) is the same as the input to3053 the left-hand-side (LHS) rather than the value at the LHS3054 path, and all values output by the RHS will be used (as shown3055 below).30563057 If the RHS of '=' produces multiple values, then for each such3058 value jq will set the paths on the left-hand side to the value3059 and then it will output the modified `.`. For example,3060 `(.a,.b)=range(2)` outputs `{"a":0,"b":0}`, then3061 `{"a":1,"b":1}`. The "update" assignment forms (see above) do3062 not do this.30633064 This example should show the difference between '=' and '|=':30653066 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:30673068 .a = .b30693070 .a |= .b30713072 The former will set the "a" field of the input to the "b"3073 field of the input, and produce the output {"a": 20, "b": 20}.3074 The latter will set the "a" field of the input to the "a"3075 field's "b" field, producing {"a": 10, "b": 20}.30763077 Another example of the difference between '=' and '|=':30783079 null|(.a,.b)=range(3)30803081 outputs '{"a":0,"b":0}', '{"a":1,"b":1}', and '{"a":2,"b":2}',3082 while30833084 null|(.a,.b)|=range(3)30853086 outputs just '{"a":0,"b":0}'.30873088 - title: Complex assignments3089 body: |3090 Lots more things are allowed on the left-hand side of a jq assignment3091 than in most languages. We've already seen simple field accesses on3092 the left hand side, and it's no surprise that array accesses work just3093 as well:30943095 .posts[0].title = "JQ Manual"30963097 What may come as a surprise is that the expression on the left may3098 produce multiple results, referring to different points in the input3099 document:31003101 .posts[].comments |= . + ["this is great"]31023103 That example appends the string "this is great" to the "comments"3104 array of each post in the input (where the input is an object with a3105 field "posts" which is an array of posts).31063107 When jq encounters an assignment like 'a = b', it records the "path"3108 taken to select a part of the input document while executing a. This3109 path is then used to find which part of the input to change while3110 executing the assignment. Any filter may be used on the3111 left-hand side of an equals - whichever paths it selects from the3112 input will be where the assignment is performed.31133114 This is a very powerful operation. Suppose we wanted to add a comment3115 to blog posts, using the same "blog" input above. This time, we only3116 want to comment on the posts written by "stedolan". We can find those3117 posts using the "select" function described earlier:31183119 .posts[] | select(.author == "stedolan")31203121 The paths provided by this operation point to each of the posts that3122 "stedolan" wrote, and we can comment on each of them in the same way3123 that we did before:31243125 (.posts[] | select(.author == "stedolan") | .comments) |=3126 . + ["terrible."]31273128 - title: Modules3129 body: |31303131 jq has a library/module system. Modules are files whose names end3132 in `.jq`.31333134 Modules imported by a program are searched for in a default search3135 path (see below). The `import` and `include` directives allow the3136 importer to alter this path.31373138 Paths in the a search path are subject to various substitutions.31393140 For paths starting with "~/", the user's home directory is3141 substituted for "~".31423143 For paths starting with "$ORIGIN/", the path of the jq executable3144 is substituted for "$ORIGIN".31453146 For paths starting with "./" or paths that are ".", the path of3147 the including file is substituted for ".". For top-level programs3148 given on the command-line, the current directory is used.31493150 Import directives can optionally specify a search path to which3151 the default is appended.31523153 The default search path is the search path given to the `-L`3154 command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",3155 "$ORIGIN/../lib"]`.31563157 Null and empty string path elements terminate search path3158 processing.31593160 A dependency with relative path "foo/bar" would be searched for in3161 "foo/bar.jq" and "foo/bar/bar.jq" in the given search path. This3162 is intended to allow modules to be placed in a directory along3163 with, for example, version control files, README files, and so on,3164 but also to allow for single-file modules.31653166 Consecutive components with the same name are not allowed to avoid3167 ambiguities (e.g., "foo/foo").31683169 For example, with `-L$HOME/.jq` a module `foo` can be found in3170 `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.31713172 If "$HOME/.jq" is a file, it is sourced into the main program.31733174 entries:3175 - title: "`import RelativePathString as NAME [<metadata>];`"3176 body: |31773178 Imports a module found at the given path relative to a3179 directory in a search path. A ".jq" suffix will be added to3180 the relative path string. The module's symbols are prefixed3181 with "NAME::".31823183 The optional metadata must be a constant jq expression. It3184 should be an object with keys like "homepage" and so on. At3185 this time jq only uses the "search" key/value of the metadata.3186 The metadata is also made available to users via the3187 `modulemeta` builtin.31883189 The "search" key in the metadata, if present, should have a3190 string or array value (array of strings); this is the search3191 path to be prefixed to the top-level search path.31923193 - title: "`include RelativePathString [<metadata>];`"3194 body: |31953196 Imports a module found at the given path relative to a3197 directory in a search path as if it were included in place. A3198 ".jq" suffix will be added to the relative path string. The3199 module's symbols are imported into the caller's namespace as3200 if the module's content had been included directly.32013202 The optional metadata must be a constant jq expression. It3203 should be an object with keys like "homepage" and so on. At3204 this time jq only uses the "search" key/value of the metadata.3205 The metadata is also made available to users via the3206 `modulemeta` builtin.32073208 - title: "`import RelativePathString as $NAME [<metadata>];`"3209 body: |32103211 Imports a JSON file found at the given path relative to a3212 directory in a search path. A ".json" suffix will be added to3213 the relative path string. The file's data will be available3214 as `$NAME::NAME`.32153216 The optional metadata must be a constant jq expression. It3217 should be an object with keys like "homepage" and so on. At3218 this time jq only uses the "search" key/value of the metadata.3219 The metadata is also made available to users via the3220 `modulemeta` builtin.32213222 The "search" key in the metadata, if present, should have a3223 string or array value (array of strings); this is the search3224 path to be prefixed to the top-level search path.32253226 - title: "`module <metadata>;`"3227 body: |32283229 This directive is entirely optional. It's not required for3230 proper operation. It serves only the purpose of providing3231 metadata that can be read with the `modulemeta` builtin.32323233 The metadata must be a constant jq expression. It should be3234 an object with keys like "homepage". At this time jq doesn't3235 use this metadata, but it is made available to users via the3236 `modulemeta` builtin.32373238 - title: "`modulemeta`"3239 body: |32403241 Takes a module name as input and outputs the module's metadata3242 as an object, with the module's imports (including metadata)3243 as an array value for the "deps" key.32443245 Programs can use this to query a module's metadata, which they3246 could then use to, for example, search for, download, and3247 install missing dependencies.32483249 - title: Colors3250 body: |32513252 To configure alternative colors just set the `JQ_COLORS`3253 environment variable to colon-delimited list of partial terminal3254 escape sequences like `"1;31"`, in this order:32553256 - color for `null`3257 - color for `false`3258 - color for `true`3259 - color for numbers3260 - color for strings3261 - color for arrays3262 - color for objects32633264 The default color scheme is the same as setting3265 `"JQ_COLORS=1;30:0;39:0;39:0;39:0;32:1;39:1;39"`.32663267 This is not a manual for VT100/ANSI escapes. However, each of3268 these color specifications should consist of two numbers separated3269 by a semi-colon, where the first number is one of these:32703271 - 1 (bright)3272 - 2 (dim)3273 - 4 (underscore)3274 - 5 (blink)3275 - 7 (reverse)3276 - 8 (hidden)32773278 and the second is one of these:32793280 - 30 (black)3281 - 31 (red)3282 - 32 (green)3283 - 33 (yellow)3284 - 34 (blue)3285 - 35 (magenta)3286 - 36 (cyan)3287 - 37 (white)
added:docs/content/manual/manual.yml+3304 added
1---2headline: jq Manual (development version)34history: |56 *For released versions, see [jq 1.6](/jq/manual/v1.6),7 [jq 1.5](/jq/manual/v1.5), [jq 1.4](/jq/manual/v1.4)8 or [jq 1.3](/jq/manual/v1.3).*910body: |1112 A jq program is a "filter": it takes an input, and produces 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.1617 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.2021 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.2627 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.3435 But that's getting ahead of ourselves. :) Let's start with something36 simpler:3738manpage_intro: |39 jq(1) -- Command-line JSON processor40 ====================================4142 ## SYNOPSIS4344 `jq` [<options>...] <filter> [<files>...]4546 `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.5051 `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.5657 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.6162 ## FILTERS6364manpage_epilogue: |65 ## BUGS6667 Presumably. Report them or discuss them at:6869 https://github.com/stedolan/jq/issues7071 ## AUTHOR7273 Stephen Dolan `<mu@netsoc.tcd.ie>`7475sections:76 - title: Invoking jq77 body: |7879 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.8485 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.9596 You can affect how jq reads and writes its input and output97 using some command-line options:9899 * `--version`:100101 Output the jq version and exit with zero.102103 * `--seq`:104105 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.113114 * `--stream`:115116 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"]`.120121 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.124125 * `--slurp`/`-s`:126127 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.130131 * `--raw-input`/`-R`:132133 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.137138 * `--null-input`/`-n`:139140 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.143144 * `--compact-output` / `-c`:145146 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.149150 * `--tab`:151152 Use a tab for each indentation level instead of two spaces.153154 * `--indent n`:155156 Use the given number of spaces (no more than 8) for indentation.157158 * `--color-output` / `-C` and `--monochrome-output` / `-M`:159160 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`.163164 Colors can be configured with the `JQ_COLORS` environment165 variable (see below).166167 * `--ascii-output` / `-a`:168169 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.174175 * `--unbuffered`176177 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).180181 * `--sort-keys` / `-S`:182183 Output the fields of each object with the keys in sorted order.184185 * `--raw-output` / `-r`:186187 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.191192 * `--join-output` / `-j`:193194 Like `-r` but jq won't print a newline after each output.195196 * `-f filename` / `--from-file filename`:197198 Read filter from the file rather than from a command line, like199 awk's -f option. You can also use '#' to make comments.200201 * `-Ldirectory` / `-L directory`:202203 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.206207 * `-e` / `--exit-status`:208209 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.215216 Another way to set the exit status is with the `halt_error`217 builtin function.218219 * `--arg name value`:220221 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"`.226227 Named arguments are also available to the jq program as228 `$ARGS.named`.229230 * `--argjson name JSON-text`:231232 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`.235236 * `--slurpfile variable-name filename`:237238 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`.243244 * `--rawfile variable-name filename`:245246 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`.250251 * `--argfile variable-name filename`:252253 Do not use. Use `--slurpfile` instead.254255 (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`.)258259 * `--args`:260261 Remaining arguments are positional string arguments. These are262 available to the jq program as `$ARGS.positional[]`.263264 * `--jsonargs`:265266 Remaining arguments are positional JSON text arguments. These267 are available to the jq program as `$ARGS.positional[]`.268269 * `--run-tests [filename]`:270271 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.280281 Be warned that this option can change backwards-incompatibly.282283 - title: Basic filters284 entries:285 - title: "Identity: `.`"286 body: |287288 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.291292 Since jq by default pretty-prints all output, this trivial293 program can be a useful way of formatting JSON output from,294 say, `curl`.295296 examples:297 - program: '.'298 input: '"Hello, world!"'299 output: ['"Hello, world!"']300301 - title: "Object Identifier-Index: `.foo`, `.foo.bar`"302 body: |303304 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.307308 A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.309310 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.313314 If the key contains special characters, you need to surround315 it with double quotes like this: `."foo$"`, or else `.["foo$"]`.316317 For example `.["foo::bar"]` and `.["foo.bar"]` work while318 `.foo::bar` does not, and `.foo.bar` means `.["foo"].["bar"]`.319320 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]330331 - title: "Optional Object Identifier-Index: `.foo?`"332 body: |333334 Just like `.foo`, but does not output even an error when `.`335 is not an array or an object.336337 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: ['[]']350351 - title: "Generic Object Index: `.[<string>]`"352 body: |353354 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).357358 - title: "Array Index: `.[2]`"359 body: |360361 When the index value is an integer, `.[<value>]` can index362 arrays. Arrays are zero-based, so `.[2]` returns the third363 element.364365 Negative indices are allowed, with -1 referring to the last366 element, -2 referring to the next to last element, and so on.367368 examples:369 - program: '.[0]'370 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'371 output: ['{"name":"JSON", "good":true}']372373 - program: '.[2]'374 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'375 output: ['null']376377 - program: '.[-2]'378 input: '[1,2,3]'379 output: ['2']380381 - title: "Array/String Slice: `.[10:15]`"382 body: |383384 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).391392 examples:393 - program: '.[2:4]'394 input: '["a","b","c","d","e"]'395 output: ['["c", "d"]']396397 - program: '.[2:4]'398 input: '"abcdefghi"'399 output: ['"cd"']400401 - program: '.[:3]'402 input: '["a","b","c","d","e"]'403 output: ['["a", "b", "c"]']404405 - program: '.[-2:]'406 input: '["a","b","c","d","e"]'407 output: ['["d", "e"]']408409 - title: "Array/Object Value Iterator: `.[]`"410 body: |411412 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.417418 You can also use this on an object, and it will return all419 the values of the object.420421 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}'427428 - program: '.[]'429 input: '[]'430 output: []431432 - program: '.[]'433 input: '{"a": 1, "b": 1}'434 output: ['1', '1']435436 - title: "`.[]?`"437 body: |438439 Like `.[]`, but no errors will be output if . is not an array440 or object.441442 - title: "Comma: `,`"443 body: |444445 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.452453 examples:454 - program: '.foo, .bar'455 input: '{"foo": 42, "bar": "something else", "baz": true}'456 output: ['42', '"something else"']457458 - program: ".user, .projects[]"459 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'460 output: ['"stedolan"', '"jq"', '"wikiflow"']461462 - program: '.[4,2]'463 input: '["a","b","c","d","e"]'464 output: ['"e"', '"c"']465466 - title: "Pipe: `|`"467 body: |468469 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.473474 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.478479 Note that `.a.b.c` is the same as `.a | .b | .c`.480481 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.485486 examples:487 - program: '.[] | .name'488 input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'489 output: ['"JSON"', '"XML"']490491 - title: "Parenthesis"492 body: |493494 Parenthesis work as a grouping operator just as in any typical495 programming language.496497 examples:498 - program: '(. + 2) * 5'499 input: '1'500 output: [15]501502 - title: Types and Values503 body: |504505 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".508509 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.514515 entries:516 - title: "Array construction: `[]`"517 body: |518519 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]`)526527 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).532533 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.536537 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]']544545 - title: "Object Construction: `{}`"546 body: |547548 Like JSON, `{}` is for constructing objects (aka549 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.550551 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}`.557558 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).562563 {foo: .bar}564565 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 write570571 {user: .user, title: .title}572573 Because that is so common, there's a shortcut syntax for it:574 `{user, title}`.575576 If one of the expressions produces multiple results,577 multiple dictionaries will be produced. If the input's578579 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}580581 then the expression582583 {user, title: .titles[]}584585 will produce two outputs:586587 {"user":"stedolan", "title": "JQ Primer"}588 {"user":"stedolan", "title": "More JQ"}589590 Putting parentheses around the key means it will be evaluated as an591 expression. With the same input as above,592593 {(.user): .titles}594595 produces596597 {"stedolan": ["JQ Primer", "More JQ"]}598599 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,602603 "f o o" as $foo | "b a r" as $bar | {$foo, $bar:$foo}604605 produces606607 {"f o o":"f o o","b a r":"f o o"}608609 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"]}']618619 - title: "Recursive Descent: `..`"620 body: |621622 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" `.`.628629 This is particularly useful in conjunction with `path(EXP)`630 (also see below) and the `?` operator.631632 examples:633 - program: '..|.a?'634 input: '[[{"a":1}]]'635 output: ['1']636637 - title: Builtin operators and functions638 body: |639640 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.645646 entries:647 - title: "Addition: `+`"648 body: |649650 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:653654 - **Numbers** are added by normal arithmetic.655656 - **Arrays** are added by being concatenated into a larger array.657658 - **Strings** are added by being joined into a larger string.659660 - **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.)665666 `null` can be added to any value, and returns the other667 value unchanged.668669 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}']685686 - title: "Subtraction: `-`"687 body: |688689 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.692693 examples:694 - program: '4 - .a'695 input: '{"a":3}'696 output: ['1']697 - program: . - ["xml", "yaml"]698 input: '["xml", "yaml", "json"]'699 output: ['["json"]']700701 - title: "Multiplication, division, modulo: `*`, `/`, and `%`"702 body: |703704 These infix operators behave as expected when given two numbers.705 Division by zero raises an error. `x % y` computes x modulo y.706707 Multiplying a string by a number produces the concatenation of708 that string that many times. `"x" * 0` produces **null**.709710 Dividing a string by another splits the first using the second711 as separators.712713 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.717718 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']731732733 - title: "`length`"734 body: |735736 The builtin function `length` gets the length of various737 different types of value:738739 - 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).742743 - The length of an **array** is the number of elements.744745 - The length of an **object** is the number of key-value pairs.746747 - The length of **null** is zero.748749 examples:750 - program: '.[] | length'751 input: '[[1,2], "string", {"a":2}, null]'752 output: [2, 6, 1, 0]753754755 - title: "`utf8bytelength`"756 body: |757758 The builtin function `utf8bytelength` outputs the number of759 bytes used to encode a string in UTF-8.760761 examples:762 - program: 'utf8bytelength'763 input: '"\u03bc"'764 output: [2]765766 - title: "`keys`, `keys_unsorted`"767 body: |768769 The builtin function `keys`, when given an object, returns770 its keys in an array.771772 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.777778 When `keys` is given an array, it returns the valid indices779 for that array: the integers from 0 to length-1.780781 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.784785 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]']792793 - title: "`has(key)`"794 body: |795796 The builtin function `has` returns whether the input object797 has the given key, or the input array has an element at the798 given index.799800 `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.803804 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]']811812 - title: "`in`"813 body: |814815 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`.819820 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]']827828 - title: "`map(x)`, `map_values(x)`"829 body: |830831 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.834835 Similarly, `map_values(x)` will run that filter for each element,836 but it will return an object when an object is passed.837838 `map(x)` is equivalent to `[.[] | x]`. In fact, this is how839 it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`.840841 examples:842 - program: 'map(.+1)'843 input: '[1,2,3]'844 output: ['[2,3,4]']845846 - program: 'map_values(.+1)'847 input: '{"a": 1, "b": 2, "c": 3}'848 output: ['{"a": 2, "b": 3, "c": 4}']849850 - title: "`path(path_expression)`"851 body: |852853 Outputs array representations of the given path expression854 in `.`. The outputs are arrays of strings (object keys)855 and/or numbers (array indices).856857 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.861862 `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.865866 `path(pattern)` will produce array representations of the867 paths matching `pattern` if the paths exist in `.`.868869 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.873874 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"]]']881882 - title: "`del(path_expression)`"883 body: |884885 The builtin function `del` removes a key and its corresponding886 value from an object.887888 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"]']895896 - title: "`getpath(PATHS)`"897 body: |898899 The builtin function `getpath` outputs the values in `.` found900 at each path in `PATHS`.901902 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]']909910 - title: "`setpath(PATHS; VALUE)`"911 body: |912913 The builtin function `setpath` sets the `PATHS` in `.` to `VALUE`.914915 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}]']925926 - title: "`delpaths(PATHS)`"927 body: |928929 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.932933 examples:934 - program: 'delpaths([["a","b"]])'935 input: '{"a":{"b":1},"x":{"y":2}}'936 output: ['{"a":{},"x":{"y":2}}']937938 - title: "`to_entries`, `from_entries`, `with_entries`"939 body: |940941 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}`.945946 `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.951952 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}']962963964 - title: "`select(boolean_expression)`"965 body: |966967 The function `select(foo)` produces its input unchanged if968 `foo` returns true for that input, and produces no output969 otherwise.970971 It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`972 will give you `[2,3]`.973974 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}']981982983 - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"984 body: |985986 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.990991 examples:992 - program: '.[]|numbers'993 input: '[[],{},1,"foo",null,true,false]'994 output: ['1']995996 - title: "`empty`"997 body: |998999 `empty` returns no results. None at all. Not even `null`.10001001 It's useful on occasion. You'll know if you need it :)10021003 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]']10101011 - title: "`error(message)`"1012 body: |10131014 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.10171018 - title: "`halt`"1019 body: |10201021 Stops the jq program with no further outputs. jq will exit1022 with exit status `0`.10231024 - title: "`halt_error`, `halt_error(exit_code)`"1025 body: |10261027 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.10301031 The given `exit_code` (defaulting to `5`) will be jq's exit1032 status.10331034 For example, `"Error: somthing went wrong\n"|halt_error(1)`.10351036 - title: "`$__loc__`"1037 body: |10381039 Produces an object with a "file" key and a "line" key, with1040 the filename and line number where `$__loc__` occurs, as1041 values.10421043 examples:1044 - program: 'try error("\($__loc__)") catch .'1045 input: 'null'1046 output: ['"{\"file\":\"<top-level>\",\"line\":1}"']10471048 - title: "`paths`, `paths(node_filter)`, `leaf_paths`"1049 body: |10501051 `paths` outputs the paths to all the elements in its input1052 (except it does not output the empty list, representing .1053 itself).10541055 `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.10581059 `leaf_paths` is an alias of `paths(scalars)`; `leaf_paths` is1060 *deprecated* and will be removed in the next major release.10611062 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"]]']10691070 - title: "`add`"1071 body: |10721073 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).10781079 If the input is an empty array, `add` returns `null`.10801081 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"]10911092 - title: "`any`, `any(condition)`, `any(generator; condition)`"1093 body: |10941095 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`.10981099 If the input is an empty array, `any` returns `false`.11001101 The `any(condition)` form applies the given condition to the1102 elements of the input array.11031104 The `any(generator; condition)` form applies the given1105 condition to all the outputs of the given generator.11061107 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"]11171118 - title: "`all`, `all(condition)`, `all(generator; condition)`"1119 body: |11201121 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`.11241125 The `all(condition)` form applies the given condition to the1126 elements of the input array.11271128 The `all(generator; condition)` form applies the given1129 condition to all the outputs of the given generator.11301131 If the input is an empty array, `all` returns `true`.11321133 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"]11431144 - title: "`flatten`, `flatten(depth)`"1145 body: |11461147 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.11511152 `flatten(2)` is like `flatten`, but going only up to two1153 levels deep.11541155 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"}]']11681169 - title: "`range(upto)`, `range(from;upto)` `range(from;upto;by)`"1170 body: |11711172 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.11761177 The one argument form generates numbers from 0 to the given1178 number, with an increment of 1.11791180 The two argument form generates numbers from `from` to `upto`1181 with an increment of 1.11821183 The three argument form generates numbers `from` to `upto`1184 with an increment of `by`.11851186 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]']12051206 - title: "`floor`"1207 body: |12081209 The `floor` function returns the floor of its numeric input.12101211 examples:1212 - program: 'floor'1213 input: '3.14159'1214 output: ['3']12151216 - title: "`sqrt`"1217 body: |12181219 The `sqrt` function returns the square root of its numeric input.12201221 examples:1222 - program: 'sqrt'1223 input: '9'1224 output: ['3']12251226 - title: "`tonumber`"1227 body: |12281229 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.12321233 examples:1234 - program: '.[] | tonumber'1235 input: '[1, "1"]'1236 output: [1, 1]12371238 - title: "`tostring`"1239 body: |12401241 The `tostring` function prints its input as a1242 string. Strings are left unchanged, and all other values are1243 JSON-encoded.12441245 examples:1246 - program: '.[] | tostring'1247 input: '[1, "1", [1]]'1248 output: ['"1"', '"1"', '"[1]"']12491250 - title: "`type`"1251 body: |12521253 The `type` function returns the type of its argument as a1254 string, which is one of null, boolean, number, string, array1255 or object.12561257 examples:1258 - program: 'map(type)'1259 input: '[0, false, [], {}, null, "hello"]'1260 output: ['["number", "boolean", "array", "object", "null", "string"]']12611262 - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"1263 body: |12641265 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.12721273 Note that division by zero raises an error.12741275 Currently most arithmetic operations operating on infinities,1276 NaNs, and sub-normals do not raise errors.12771278 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"']12851286 - title: "`sort, sort_by(path_expression)`"1287 body: |12881289 The `sort` functions sorts its input, which must be an1290 array. Values are sorted in the following order:12911292 * `null`1293 * `false`1294 * `true`1295 * numbers1296 * strings, in alphabetical order (by unicode codepoint value)1297 * arrays, in lexical order1298 * objects12991300 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.13041305 `sort` may be used to sort by a particular field of an1306 object, or by applying any jq filter.13071308 `sort_by(foo)` compares two elements by comparing the result of1309 `foo` on each element.13101311 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}]']13181319 - title: "`group_by(path_expression)`"1320 body: |13211322 `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.13261327 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.13301331 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}]]']13351336 - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"1337 body: |13381339 Find the minimum or maximum element of the input array.13401341 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.13441345 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}']13521353 - title: "`unique`, `unique_by(path_exp)`"1354 body: |13551356 The `unique` function takes as input an array and produces1357 an array of the same elements, in sorted order, with1358 duplicates removed.13591360 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`.13641365 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"]']13751376 - title: "`reverse`"1377 body: |13781379 This function reverses an array.13801381 examples:1382 - program: 'reverse'1383 input: '[1,2,3,4]'1384 output: ['[4,3,2,1]']13851386 - title: "`contains(element)`"1387 body: |13881389 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.13971398 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']14141415 - title: "`indices(s)`"1416 body: |14171418 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`.14221423 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]']14331434 - title: "`index(s)`, `rindex(s)`"1435 body: |14361437 Outputs the index of the first (`index`) or last (`rindex`)1438 occurrence of `s` in the input.14391440 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']14471448 - title: "`inside`"1449 body: |14501451 The filter `inside(b)` will produce true if the input is1452 completely contained within b. It is, essentially, an1453 inversed version of `contains`.14541455 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']14711472 - title: "`startswith(str)`"1473 body: |14741475 Outputs `true` if . starts with the given string argument.14761477 examples:1478 - program: '[.[]|startswith("foo")]'1479 input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'1480 output: ['[false, true, false, true, false]']14811482 - title: "`endswith(str)`"1483 body: |14841485 Outputs `true` if . ends with the given string argument.14861487 examples:1488 - program: '[.[]|endswith("foo")]'1489 input: '["foobar", "barfoo"]'1490 output: ['[false, true]']14911492 - title: "`combinations`, `combinations(n)`"1493 body: |14941495 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.14981499 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]']15061507 - title: "`ltrimstr(str)`"1508 body: |15091510 Outputs its input with the given prefix string removed, if it1511 starts with it.15121513 examples:1514 - program: '[.[]|ltrimstr("foo")]'1515 input: '["fo", "foo", "barfoo", "foobar", "afoo"]'1516 output: ['["fo","","barfoo","bar","afoo"]']15171518 - title: "`rtrimstr(str)`"1519 body: |15201521 Outputs its input with the given suffix string removed, if it1522 ends with it.15231524 examples:1525 - program: '[.[]|rtrimstr("foo")]'1526 input: '["fo", "foo", "barfoo", "foobar", "foob"]'1527 output: ['["fo","","bar","foobar","foob"]']15281529 - title: "`explode`"1530 body: |15311532 Converts an input string into an array of the string's1533 codepoint numbers.15341535 examples:1536 - program: 'explode'1537 input: '"foobar"'1538 output: ['[102,111,111,98,97,114]']15391540 - title: "`implode`"1541 body: |15421543 The inverse of explode.15441545 examples:1546 - program: 'implode'1547 input: '[65, 66, 67]'1548 output: ['"ABC"']15491550 - title: "`split(str)`"1551 body: |15521553 Splits an input string on the separator argument.15541555 examples:1556 - program: 'split(", ")'1557 input: '"a, b,c,d, e, "'1558 output: ['["a","b,c,d","e",""]']15591560 - title: "`join(str)`"1561 body: |15621563 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.15671568 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.15711572 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"']15791580 - title: "`ascii_downcase`, `ascii_upcase`"1581 body: |15821583 Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1584 converted to the specified case.15851586 example:1587 - program: 'ascii_upcase'1588 input: '"useful but not for é"'1589 output: '"USEFUL BUT NOT FOR é"'15901591 - title: "`while(cond; update)`"1592 body: |15931594 The `while(cond; update)` function allows you to repeatedly1595 apply an update to `.` until `cond` is false.15961597 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.16011602 examples:1603 - program: '[while(.<100; .*2)]'1604 input: '1'1605 output: ['[1,2,4,8,16,32,64]']16061607 - title: "`until(cond; next)`"1608 body: |16091610 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).16141615 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.16191620 examples:1621 - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'1622 input: '4'1623 output: ['24']162416251626 - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`, `recurse_down`"1627 body: |16281629 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:16321633 {"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": []}]}]}]}16401641 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:16451646 recurse(.children[]) | .name16471648 When called without an argument, `recurse` is equivalent to1649 `recurse(.[]?)`.16501651 `recurse(f)` is identical to `recurse(f; . != null)` and can be1652 used without concerns about recursion depth.16531654 `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)`.16591660 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.16631664 The recursive calls in `recurse` will not consume additional1665 memory whenever `f` produces at most a single output for each1666 input.16671668 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":[]}'16761677 - program: 'recurse'1678 input: '{"a":0,"b":[1]}'1679 output:1680 - '{"a":0,"b":[1]}'1681 - '0'1682 - '[1]'1683 - '1'16841685 - program: 'recurse(. * .; . < 20)'1686 input: 21687 output:1688 - 21689 - 41690 - 1616911692 - title: "`walk(f)`"1693 body: |16941695 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.17061707 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]]'17121713 - program: 'walk( if type == "object" then with_entries( .key |= sub( "^_+"; "") ) else . end )'1714 input: '[ { "_a": { "__b": 2 } } ]'1715 output:1716 - '[{"a":{"b":2}}]'17171718 - title: "`$ENV`, `env`"1719 body: |17201721 `$ENV` is an object representing the environment variables as1722 set when the jq program started.17231724 `env` outputs an object representing jq's current environment.17251726 At the moment there is no builtin for setting environment1727 variables.17281729 examples:1730 - program: '$ENV.PAGER'1731 input: 'null'1732 output: ['"less"']17331734 - program: 'env.PAGER'1735 input: 'null'1736 output: ['"less"']17371738 - title: "`transpose`"1739 body: |17401741 Transpose a possibly jagged matrix (an array of arrays).1742 Rows are padded with nulls so the result is always rectangular.17431744 examples:1745 - program: 'transpose'1746 input: '[[1], [2,3]]'1747 output: ['[[1,2],[null,3]]']17481749 - title: "`bsearch(x)`"1750 body: |17511752 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.17601761 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]']17711772 - title: "String interpolation - `\\(foo)`"1773 body: |17741775 Inside a string, you can put an expression inside parens1776 after a backslash. Whatever the expression returns will be1777 interpolated into the string.17781779 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"']17831784 - title: "Convert to/from JSON"1785 body: |17861787 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.17911792 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"]]']18021803 - title: "Format strings and escaping"1804 body: |18051806 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:18101811 * `@text`:18121813 Calls `tostring`, see that function for details.18141815 * `@json`:18161817 Serializes the input as JSON.18181819 * `@html`:18201821 Applies HTML/XML escaping, by mapping the characters1822 `<>&'"` to their entity equivalents `&lt;`, `&gt;`,1823 `&amp;`, `&apos;`, `&quot;`.18241825 * `@uri`:18261827 Applies percent-encoding, by mapping all reserved URI1828 characters to a `%XX` sequence.18291830 * `@csv`:18311832 The input must be an array, and it is rendered as CSV1833 with double quotes for strings, and quotes escaped by1834 repetition.18351836 * `@tsv`:18371838 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.18451846 * `@sh`:18471848 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.18511852 * `@base64`:18531854 The input is converted to base64 as specified by RFC 4648.18551856 * `@base64d`:18571858 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.18601861 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,18661867 @uri "https://www.google.com/search?q=\(.search)"18681869 will produce the following output for the input1870 `{"search":"what is jq?"}`:18711872 "https://www.google.com/search?q=what%20is%20jq%3F"18731874 Note that the slashes, question mark, etc. in the URL are1875 not escaped, as they were part of the string literal.18761877 examples:1878 - program: '@html'1879 input: '"This works if x < y"'1880 output: ['"This works if x &lt; y"']18811882# - program: '@html "<span>Anonymous said: \(.)</span>"'1883# input: '"<script>alert(\"lol hax\");</script>"'1884# output: ["<span>Anonymous said: &lt;script&gt;alert(&quot;lol hax&quot;);&lt;/script&gt;</span>"]18851886 - program: '@sh "echo \(.)"'1887 input: "\"O'Hara's Ale\""1888 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]18891890 - program: '@base64'1891 input: '"This is a message"'1892 output: ['"VGhpcyBpcyBhIG1lc3NhZ2U="']18931894 - program: '@base64d'1895 input: '"VGhpcyBpcyBhIG1lc3NhZ2U="'1896 output: ['"This is a message"']18971898 - title: "Dates"1899 body: |19001901 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.19041905 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.19091910 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.19141915 The `todate` builtin is an alias for `todateiso8601`.19161917 The `now` builtin outputs the current time, in seconds since1918 the Unix epoch.19191920 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.19271928 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.19371938 The `localtime` builtin works like the `gmtime` builtin, but1939 using the local timezone setting.19401941 The `mktime` builtin consumes "broken down time"1942 representations of time output by `gmtime` and `strptime`.19431944 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`.19471948 The `strftime(fmt)` builtin formats a time (GMT) with the1949 given format. The `strflocaltime` does the same, but using1950 the local timezone setting.19511952 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"`.19551956 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.19591960 examples:1961 - program: 'fromdate'1962 input: '"2015-03-05T23:51:47Z"'1963 output: ['1425599507']19641965 - 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]']19681969 - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'1970 input: '"2015-03-05T23:51:47Z"'1971 output: ['1425599507']19721973 - title: "SQL-Style Operators"1974 body: |19751976 jq provides a few SQL-style operators.19771978 * INDEX(stream; index_expression):19791980 This builtin produces an object whose keys are computed by1981 the given index expression applied to each value from the1982 given stream.19831984 * JOIN($idx; stream; idx_expr; join_expr):19851986 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.19921993 * JOIN($idx; stream; idx_expr):19941995 Same as `JOIN($idx; stream; idx_expr; .)`.19961997 * JOIN($idx; idx_expr):19981999 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.20022003 * IN(s):20042005 This builtin outputs `true` if `.` appears in the given2006 stream, otherwise it outputs `false`.20072008 * IN(source; s):20092010 This builtin outputs `true` if any value in the source stream2011 appears in the second stream, otherwise it outputs `false`.20122013 - title: "`builtins`"2014 body: |20152016 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.20202021 - title: Conditionals and Comparisons2022 entries:2023 - title: "`==`, `!=`"2024 body: |20252026 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.20322033 != is "not equal", and 'a != b' returns the opposite value of 'a == b'20342035 examples:2036 - program: '.[] == 1'2037 input: '[1, 1.0, "1", "banana"]'2038 output: ['true', 'true', 'false', 'false']20392040 - title: if-then-else2041 body: |20422043 `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.20462047 `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 `.`.20502051 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.20572058 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.20612062 More cases can be added to an if using `elif A then B` syntax.20632064 examples:2065 - program: 'if . == 0 then2066 "zero"2067 elif . == 1 then2068 "one"2069 else2070 "many"2071 end'2072 input: 22073 output: ['"many"']20742075 - title: "`>, >=, <=, <`"2076 body: |20772078 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).20822083 The ordering is the same as that described for `sort`, above.20842085 examples:2086 - program: '. < 5'2087 input: 22088 output: ['true']20892090 - title: and/or/not2091 body: |20922093 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".20962097 If an operand of one of these operators produces multiple2098 results, the operator itself will produce a result for each input.20992100 `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`.21042105 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.21112112 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]']21282129 - title: "Alternative operator: `//`"2130 body: |21312132 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`.21352136 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).21412142 examples:2143 - program: '.foo // 42'2144 input: '{"foo": 19}'2145 output: [19]2146 - program: '.foo // 42'2147 input: '{}'2148 output: [42]21492150 - title: try-catch2151 body: |21522153 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.21582159 The `try EXP` form uses `empty` as the exception handler.21602161 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"']21712172 - title: Breaking out of control structures2173 body: |21742175 A convenient use of try/catch is to break out of control2176 structures like `reduce`, `foreach`, `while`, and so on.21772178 For example:21792180 # 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;21842185 jq has a syntax for named lexical labels to "break" or "go (back) to":21862187 label $out | ... break $out ...21882189 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`.21922193 The relationship between the `break` and corresponding `label`2194 is lexical: the label has to be "visible" from the break.21952196 To break out of a `reduce`, for example:21972198 label $out | reduce .[] as $item (null; if .==false then break $out else ... end)21992200 The following jq program produces a syntax error:22012202 break $out22032204 because no label `$out` is visible.22052206 - title: "Error Suppression / Optional Operator: `?`"2207 body: |22082209 The `?` operator, used as `EXP?`, is shorthand for `try EXP`.22102211 examples:2212 - program: '[.[]|(.a)?]'2213 input: '[{}, true, {"a":1}]'2214 output: ['[null, 1]']221522162217 - title: Regular expressions (PCRE)2218 body: |22192220 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.22232224 The jq regex filters are defined so that they can be used using2225 one of these patterns:22262227 STRING | FILTER( REGEX )2228 STRING | FILTER( REGEX; FLAGS )2229 STRING | FILTER( [REGEX] )2230 STRING | FILTER( [REGEX, FLAGS] )22312232 where:22332234 * 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.22372238 FLAGS is a string consisting of one of more of the supported flags:22392240 * `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)22482249 To match whitespace in an x pattern use an escape such as \s, e.g.22502251 * test( "a\\sb", "x" ).22522253 Note that certain flags may also be specified within REGEX, e.g.22542255 * jq -n '("test", "TEst", "teST", "TEST") | test( "(?i)te(?-i)st" )'22562257 evaluates to: true, true, false, false.22582259 entries:2260 - title: "`test(val)`, `test(regex; flags)`"2261 body: |22622263 Like `match`, but does not return match objects, only `true` or `false`2264 for whether or not the regex matches the input.22652266 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']22732274 - title: "`match(val)`, `match(regex; flags)`"2275 body: |22762277 **match** outputs an object for each match it finds. Matches have2278 the following fields:22792280 * `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.22842285 Capturing group objects have the following fields:22862287 * `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)22912292 Capturing groups that did not match anything return an offset of -122932294 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"}]}'23132314 - program: '[ match("."; "g")] | length'2315 input: '"abc"'2316 output: [3]231723182319 - title: "`capture(val)`, `capture(regex; flags)`"2320 body: |23212322 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.23252326 examples:2327 - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'2328 input: '"xyzzy-14"'2329 output: ['{ "a": "xyzzy", "n": "14" }']23302331 - title: "`scan(regex)`, `scan(regex; flags)`"2332 body: |23332334 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) ]`.23392340 example:2341 - program: 'scan("c")'2342 input: '"abcdefabc"'2343 output: ['"c"', '"c"']23442345 - program: 'scan("b")'2346 input: ("", "")2347 output: ['[]', '[]']23482349 - title: "`split(regex; flags)`"2350 body: |23512352 For backwards compatibility, `split` splits on a string, not a regex.23532354 example:2355 - program: 'split(", *"; null)'2356 input: '"ab,cd, ef"'2357 output: ['"ab","cd","ef"']235823592360 - title: "`splits(regex)`, `splits(regex; flags)`"2361 body: |23622363 These provide the same results as their `split` counterparts,2364 but as a stream instead of an array.23652366 example:2367 - program: 'splits(", *")'2368 input: '("ab,cd", "ef, gh")'2369 output: ['"ab"', '"cd"', '"ef"', '"gh"']23702371 - title: "`sub(regex; tostring)` `sub(regex; string; flags)`"2372 body: |23732374 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)".23802381 example:2382 - program: 'sub("^[^a-z]*(?<x>[a-z]*).*")'2383 input: '"123abc456"'2384 output: '"ZabcZabc"'238523862387 - title: "`gsub(regex; string)`, `gsub(regex; string; flags)`"2388 body: |23892390 `gsub` is like `sub` but all the non-overlapping occurrences of the regex are2391 replaced by the string, after interpolation.23922393 example:2394 - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'2395 input: '"Abcabc"'2396 output: '"+A-+a-"'239723982399 - title: Advanced features2400 body: |2401 Variables are an absolute necessity in most programming languages, but2402 they're relegated to an "advanced feature" in jq.24032404 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.24102411 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).24152416 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.24192420 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.24232424 Some minimal I/O support (besides reading JSON from standard2425 input, and writing JSON to standard output) is available.24262427 Finally, there is a module/library system.24282429 entries:2430 - title: "Variable / Symbolic Binding Operator: `... as $identifier | ...`"2431 body: |24322433 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.24392440 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.24462447 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:24522453 length as $array_length | add / $array_length24542455 We'll need a more complicated problem to find a situation where using2456 variables actually makes our lives easier.245724582459 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:24622463 {"posts": [{"title": "Frist psot", "author": "anon"},2464 {"title": "A well-written article", "author": "person1"}],2465 "realnames": {"anon": "Anonymous Coward",2466 "person1": "Person McPherson"}}24672468 We want to produce the posts with the author field containing a real2469 name, as in:24702471 {"title": "Frist psot", "author": "Anonymous Coward"}2472 {"title": "A well-written article", "author": "Person McPherson"}24732474 We use a variable, $names, to store the realnames object, so that we2475 can refer to it later when looking up author usernames:24762477 .realnames as $names | .posts[] | {title, author: $names[.author]}24782479 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.24832484 Just as `{foo}` is a handy way of writing `{foo: .foo}`, so2485 `{$foo}` is a handy way of writing `{foo:$foo}`.24862487 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"):24902491 . as {realnames: $names, posts: [$first, $second]} | ...24922493 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.24982499 Variables are scoped over the rest of the expression that defines2500 them, so25012502 .realnames as $names | (.posts[] | {title, author: $names[.author]})25032504 will work, but25052506 (.realnames as $names | .posts[]) | {title, author: $names[.author]}25072508 won't.25092510 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.25152516 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}']25292530 - 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.25352536 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:25462547 .resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$user_id, $ts}]} | {$user_id, $kind, $id, $ts}25482549 Or, if we aren't sure if the input is an array of values or an object:25502551 .[] as [$id, $kind, $user_id, $ts] ?// {$id, $kind, $user_id, $ts} | ...25522553 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`:25562557 .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}25582559 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.25622563 [[3]] | .[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end25642565 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}']25752576 - title: 'Defining Functions'2577 body: |25782579 You can give a filter a name using "def" syntax:25802581 def increment: . + 1;25822583 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:25862587 def map(f): [.[] | f];25882589 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:25952596 def foo(f): f|f;2597 5|foo(.*2)25982599 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.26042605 If you want the value-argument behaviour for defining simple2606 functions, you can just use a variable:26072608 def addvalue(f): f as $f | map(. + $f);26092610 Or use the short-hand:26112612 def addvalue($f): ...;26132614 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.26192620 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.26252626 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]]']26332634 - title: 'Scoping'2635 body: |26362637 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.26432644 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.26502651 - title: Reduce2652 body: |26532654 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:26572658 reduce .[] as $item (0; . + $item)26592660 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:26642665 0 | (3 as $item | . + $item) |2666 (2 as $item | . + $item) |2667 (1 as $item | . + $item)26682669 examples:2670 - program: 'reduce .[] as $item (0; . + $item)'2671 input: '[10,2,5,3]'2672 output: ['20']26732674 - title: "`isempty(exp)`"2675 body: |26762677 Returns true if `exp` produces no outputs, false otherwise.26782679 examples:2680 - program: 'isempty(empty)'2681 input: 'null'2682 output: ['true']26832684 - title: "`limit(n; exp)`"2685 body: |26862687 The `limit` function extracts up to `n` outputs from `exp`.26882689 examples:2690 - program: '[limit(3;.[])]'2691 input: '[0,1,2,3,4,5,6,7,8,9]'2692 output: ['[0,1,2]']26932694 - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"2695 body: |26962697 The `first(expr)` and `last(expr)` functions extract the first2698 and last values from `expr`, respectively.26992700 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`.27042705 examples:2706 - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'2707 input: '10'2708 output: ['[0,9,5]']27092710 - title: "`first`, `last`, `nth(n)`"2711 body: |27122713 The `first` and `last` functions extract the first2714 and last values from any array at `.`.27152716 The `nth(n)` function extracts the nth value of any array at `.`.27172718 examples:2719 - program: '[range(.)]|[first, last, nth(5)]'2720 input: '10'2721 output: ['[0,9,5]']27222723 - title: "`foreach`"2724 body: |27252726 The `foreach` syntax is similar to `reduce`, but intended to2727 allow the construction of `limit` and reducers that produce2728 intermediate results (see example).27292730 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`.27372738 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).27412742 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"]]']27492750 - title: Recursion2751 body: |27522753 As described above, `recurse` uses recursion, and any jq2754 function can be recursive. The `while` builtin is also2755 implemented in terms of recursion.27562757 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.27612762 For example:27632764 def recurse(f): def r: ., (f | select(. != null) | r); r;27652766 def while(cond; update):2767 def _while:2768 if cond then ., (update | _while) else empty end;2769 _while;27702771 def repeat(exp):2772 def _repeat:2773 exp, _repeat;2774 _repeat;27752776 - title: Generators and iterators2777 body: |27782779 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.27862787 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.27912792 The `empty` builtin is the generator that produces zero2793 outputs. The `empty` builtin backtracks to the preceding2794 generator expression.27952796 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.28042805 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]']28232824 - title: 'Math'2825 body: |28262827 jq currently only has IEEE754 double-precision (64-bit) floating2828 point number support.28292830 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 `.`.28382839 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.28432844 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`.28502851 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`.28542855 Three-input C math functions: `fma`.28562857 See your system's manual for more information on each of these.28582859 - title: 'I/O'2860 body: |28612862 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.28682869 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.28762877 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.28802881 entries:2882 - title: "`input`"2883 body: |28842885 Outputs one new input.28862887 - title: "`inputs`"2888 body: |28892890 Outputs all remaining inputs, one by one.28912892 This is primarily useful for reductions over a program's2893 inputs.28942895 - title: "`debug`"2896 body: |28972898 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.29022903 - title: "`stderr`"2904 body: |29052906 Prints its input in raw and compact mode to stderr with no2907 additional decoration, not even a newline.29082909 - title: "`input_filename`"2910 body: |29112912 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.29152916 - title: "`input_line_number`"2917 body: |29182919 Returns the line number of the input currently being filtered.29202921 - title: 'Streaming'2922 body: |29232924 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.29292930 However, streaming isn't easy to deal with as the jq program will2931 have `[<path>, <leaf-value>]` (and a few other forms) as inputs.29322933 Several builtins are provided to make handling streams easier.29342935 The examples below use the streamed form of `[0,[1]]`, which is2936 `[[0],0],[[1,0],1],[[1,0]],[[1]]`.29372938 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.29432944 entries:2945 - title: "`truncate_stream(stream_expression)`"2946 body: |29472948 Consumes a number as input and truncates the corresponding2949 number of path elements from the left of the outputs of the2950 given streaming expression.29512952 examples:2953 - program: '[1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]'2954 input: '1'2955 output: ['[[[0],2],[[0]]]']29562957 - title: "`fromstream(stream_expression)`"2958 body: |29592960 Outputs values corresponding to the stream expression's2961 outputs.29622963 examples:2964 - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'2965 input: 'null'2966 output: ['[2]']29672968 - title: "`tostream`"2969 body: |29702971 The `tostream` builtin outputs the streamed form of its input.29722973 examples:2974 - program: '. as $dot|fromstream($dot|tostream)|.==$dot'2975 input: '[0,[1,{"a":1},{"b":2}]]'2976 output: ['true']29772978 - 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".29852986 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).29942995 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.29993000 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.30033004 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.30123013 Most users will want to use modification assignment operators,3014 such as `|=` or `+=`, rather than `=`.30153016 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.30203021 Note too that `.a,.b=0` does not set `.a` and `.b`, but3022 `(.a,.b)=0` sets both.30233024 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.30333034 The left-hand side can be any general path expression; see `path()`.30353036 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.30403041 If the right-hand side outputs no values (i.e., `empty`), then3042 the left-hand side path will be deleted, as with `del(path)`.30433044 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).30473048 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]]']30523053 - title: "Arithmetic update-assignment: `+=`, `-=`, `*=`, `/=`, `%=`, `//=`"3054 body: |30553056 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`.30593060 examples:3061 - program: .foo += 13062 input: '{"foo": 42}'3063 output: ['{"foo": 43}']30643065 - title: "Plain assignment: `=`"3066 body: |30673068 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).30733074 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.30803081 This example should show the difference between '=' and '|=':30823083 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:30843085 .a = .b30863087 .a |= .b30883089 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}.30933094 Another example of the difference between '=' and '|=':30953096 null|(.a,.b)=range(3)30973098 outputs '{"a":0,"b":0}', '{"a":1,"b":1}', and '{"a":2,"b":2}',3099 while31003101 null|(.a,.b)|=range(3)31023103 outputs just '{"a":0,"b":0}'.31043105 - 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:31113112 .posts[0].title = "JQ Manual"31133114 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:31173118 .posts[].comments |= . + ["this is great"]31193120 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).31233124 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.31303131 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:31353136 .posts[] | select(.author == "stedolan")31373138 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:31413142 (.posts[] | select(.author == "stedolan") | .comments) |=3143 . + ["terrible."]31443145 - title: Modules3146 body: |31473148 jq has a library/module system. Modules are files whose names end3149 in `.jq`.31503151 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.31543155 Paths in the a search path are subject to various substitutions.31563157 For paths starting with "~/", the user's home directory is3158 substituted for "~".31593160 For paths starting with "$ORIGIN/", the path of the jq executable3161 is substituted for "$ORIGIN".31623163 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.31663167 Import directives can optionally specify a search path to which3168 the default is appended.31693170 The default search path is the search path given to the `-L`3171 command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",3172 "$ORIGIN/../lib"]`.31733174 Null and empty string path elements terminate search path3175 processing.31763177 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.31823183 Consecutive components with the same name are not allowed to avoid3184 ambiguities (e.g., "foo/foo").31853186 For example, with `-L$HOME/.jq` a module `foo` can be found in3187 `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.31883189 If "$HOME/.jq" is a file, it is sourced into the main program.31903191 entries:3192 - title: "`import RelativePathString as NAME [<metadata>];`"3193 body: |31943195 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::".31993200 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.32053206 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.32093210 - title: "`include RelativePathString [<metadata>];`"3211 body: |32123213 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.32183219 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.32243225 - title: "`import RelativePathString as $NAME [<metadata>];`"3226 body: |32273228 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`.32323233 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.32383239 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.32423243 - title: "`module <metadata>;`"3244 body: |32453246 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.32493250 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.32543255 - title: "`modulemeta`"3256 body: |32573258 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.32613262 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.32653266 - title: Colors3267 body: |32683269 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:32723273 - color for `null`3274 - color for `false`3275 - color for `true`3276 - color for numbers3277 - color for strings3278 - color for arrays3279 - color for objects32803281 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"`.32833284 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:32873288 - 1 (bright)3289 - 2 (dim)3290 - 4 (underscore)3291 - 5 (blink)3292 - 7 (reverse)3293 - 8 (hidden)32943295 and the second is one of these:32963297 - 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
1headline: Tutorial2body:3 - text: |45 GitHub has a JSON API, so let's play with that. This URL gets us the last6 5 commits from the jq repo.78 - 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 ...3839 - text: |4041 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.4546 - 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 ...7677 - text: |7879 We can use jq to extract just the first commit.8081 - 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 }158159 - text: |160161 For the rest of the examples, I'll leave out the `curl` command - it's not162 going to change.163164 There's a lot of info we don't care about there, so we'll restrict it down165 to the most interesting fields.166167 - 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 }173174 - text: |175176 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`.180181 Now let's get the rest of the commits.182183 - 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 }205206 - text: |207208 `.[]` 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}`.211212 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.215216 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.219220 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:223224 - 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 ]248249 - text: |250251 - - -252253 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.256257 "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 ]269270 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.273274 - 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 ]314315 - text: |316317 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.320321 - text: |322323 - - -324325 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
added:docs/public/css/base.css+173 added
1body {2 padding-top: 80px;3}45.container {6 max-width: 970px;7}89/* 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}1920#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}2930#news {31 font-size: 12pt;32}33#news .date {34 font-style: italic;35}3637/* 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}6364@media print {65 .tutorial-example a {66 display: none;67 }68}69/* manual.liquid ******************************************/70section {71 padding-top: 24px;72}7374h3 code {75 border: 0;76 font-size: 20px;77}7879@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}9899.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}113114@media print {115 #navcolumn {116 display: none !important;117 }118119 .manual-example {120 display: block !important;121 height: auto !important;122 }123124 .jqplay-btn {125 display: none !important;126 }127}128/* shared/_footer.liquid **********************************/129footer {130 background-color: #F5F5F5;131 padding: 20px 0;132 margin-top: 40px;133 color: #999999;134 text-align: center;135}136footer p {137 margin: 8px 0;138}139140/* typeahead **********************************************/141.twitter-typeahead {142 width: 100%;143}144145.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}158159.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>78 <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>78 <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>1213 <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>1213 <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" %}45 <body id="{{slug}}">6{% include "shared/_navbar.html.j2" %}78 <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 %}1516 {% 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>3132{% 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" %}45 <body id="{{slug}}">6{% include "shared/navbar" %}78 <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 %}1516 {% 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>3132{% 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" %}45 <body id="{{ slug }}">6{% include "shared/_navbar.html.j2" %}78 <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}}1920 <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>3334 <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>4546 <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>5152 <div class="row" style="text-align:center; margin-top: 30px">53 {{tail | markdownify}}54 </div>5556 <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>7071{% 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" %}45 <body id="{{slug}}">6{% include "shared/navbar" %}78 <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}}1920 <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>3334 <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>4546 <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>5152 <div class="row" style="text-align:center; margin-top: 30px">53 {{tail | markdownify}}54 </div>5556 <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>7071{% 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" %}45 <body id="{{slug}}" data-spy="scroll" data-target="#navcolumn" data-offset="100">6{% include "shared/_navbar.html.j2" %}78 <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>2728 <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}}4344 {% 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>8485{% 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" %}45 <body id="{{slug}}" data-spy="scroll" data-target="#navcolumn" data-offset="100">6{% include "shared/navbar" %}78 <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>2728 <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}}4344 {% 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>8485{% 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-cache3output/*45# Autogenerated from public/css/base.scss6public/css/base.css
added:docs/build_manpage.py+2 added
1#!/usr/bin/env python32print("Manpage build not yet supported")
added:docs/build_website.py+62 added
1#!/usr/bin/env python32import glob3import itertools4from jinja2 import Environment, FileSystemLoader, Markup, select_autoescape, contextfunction5from markdown import markdown6import os7import os.path8import re9import shutil10import yaml1112env = Environment(13 loader=FileSystemLoader('templates'),14 autoescape=select_autoescape(['html.j2']),15)1617def load_yml_file(fn):18 with open(fn) as f:19 return yaml.load(f)2021env.filters['search_id'] = lambda input: input.replace(r'`', '')22env.filters['section_id'] = lambda input: re.sub(r"[^a-zA-Z0-9_]", '', input)23env.filters['entry_id'] = lambda input: re.sub(r"[ `]", '', input)24env.filters['markdownify'] = lambda input: Markup(markdown(input))25env.filters['no_paragraph'] = lambda input: Markup(re.sub(r"</?p>", '', input))2627env.globals['unique_id'] = contextfunction(lambda ctx: str(next(ctx['unique_ctr'])))282930env.globals.update(load_yml_file('site.yml'))313233env.globals['navigation'] = ['tutorial', 'download', 'manual']3435def 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')4041 template_name = re.sub(r".yml$", '.html.j2', base)4243 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')474849def 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)5859copy_public_files()6061for fn in glob.glob('content/**/*.yml', recursive=True):62 generate_file(env, fn)
added:docs/Pipfile+11 added
1[[source]]2name = "pypi"3url = "https://pypi.org/simple"4verify_ssl = true56[dev-packages]78[packages]9jinja2 = "*"10pyyaml = "*"11markdown = "*"
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
1Documentation2=============34The jq website, manpages and some of the tests are generated from this5directory. The directory holds a [Bonsai](http://tinytree.info)6website, and the manual is a YAML file in `content/3.manual`.5directory. The manual is a YAML file in `content/manual`.67To build the documentation (including building the jq manpage), you'll9need a working Ruby setup. The easiest way to get one is to install10RVM and Ruby 1.9.3 like so:8need python3 and pipenv. You can install pipenv like so:912 \curl -L https://get.rvm.io | bash -s stable --ruby=1.9.310 pip install pipenv1114After that finishes installing, you'll need to make sure RVM is on15your path by doing `source $HOME/.rvm/scripts/rvm`, or just opening a16new shell. See <https://rvm.io> for more info on RVM.12Though, you may need to say pip3 instead, depending on your system. Once13you have pipenv installed, you can install the dependencies by running14`pipenv install` from the `docs` directory.1518Once RVM is installed, you can install all the dependencies for jq's19documentation build by running this from the `docs` directory:16Once this is done, rerun `./configure` in the jq root directory and then17the Makefile will be able to generate the jq manpage.1821 bundle install2223When bundle manages to install the dependencies, rerun `./configure`24in the jq root directory and then the Makefile will be able to25generate the jq manpage.19To build the website, run `pipenv run ./build_website.py` from inside20the `docs` directory.
modified:scripts/update-website+1 added-1 removed
9 unmodified lines
10# build website11scriptdir=`dirname "$0"`12cd "$scriptdir"/../docs13rm -rf output14rake build14pipenv run python3 build_website.py15cd ..1617# copy to /tmp18tmpdir=$(mktemp -d -t jq.website.XXXXXXXXXX)
11 unmodified lines
modified:configure.ac+10 added-10 removed
72 unmodified lines
73dnl Code coverage74AC_ARG_ENABLE([gcov],75 AC_HELP_STRING([--enable-gcov], [enable gcov code coverage tool]))7677dnl Don't attempt to build docs if there's no Ruby lying around77dnl Don't attempt to build docs if python deps aren't installed78AC_ARG_ENABLE([docs],79 AC_HELP_STRING([--disable-docs], [don't build docs]))8081dnl Don't attempt to build the error injection object (if there is no LD_PRELOAD support)
4 unmodified lines
86AC_ARG_ENABLE([all-static],87 AC_HELP_STRING([--enable-all-static], [link jq with static libraries only]))8889AS_IF([test "x$enable_docs" != "xno"],[90 AC_CHECK_PROGS(bundle_cmd, bundle)90 AC_CHECK_PROGS(pipenv_cmd, pipenv)9192 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*****************************************************************104EOF105 jq_cv_ruby_deps=no105 jq_cv_python_deps=no106 ])])107108 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 lines
modified:Makefile.am+9 added-9 removed
134 unmodified lines
135### Building the manpage136137man_MANS = jq.1138if ENABLE_DOCS139jq.1: $(srcdir)/docs/content/3.manual/manual.yml140 $(AM_V_GEN) ( cd ${abs_srcdir}/docs; '$(BUNDLER)' exec rake manpage ) > $@ || { rm -f $@; false; }139jq.1: $(srcdir)/docs/content/manual/manual.yml140 $(AM_V_GEN) ( cd ${abs_srcdir}/docs; pipenv run python build_manpage.py ) > $@ || { rm -f $@; false; }141jq.1.prebuilt: jq.1142 $(AM_V_GEN) cp jq.1 $@ || { rm -f $@; false; }143else144jq.1: $(srcdir)/jq.1.prebuilt
19 unmodified lines
164install-binaries: $(BUILT_SOURCES)165 $(MAKE) $(AM_MAKEFLAGS) install-exec166167DOC_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.prebuilt170171EXTRA_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 lines
179 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/shtest188189190191# README.md is expected in Github projects, good stuff in it, so we'll
31 unmodified lines