Skip to content
Myr

Add 1.4 and 1.3 manuals to website (fix #866)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Tolnay · committed by David Tolnay · parent 616f365 · Browse files · 4 files+2950 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+2950 added−1 removed

  • other:+2950 added−1 removed

4 files+2950 added−1 removed

added:docs/content/3.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.19 20 Some filters produce multiple results, for instance there's one that21 produces all the elements of its input array. Piping that filter22 into a second runs the second filter for each element of the23 array. Generally, things that would be done with loops and iteration24 in other languages are just done by gluing filters together in jq.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.53 54 The <options> are described in the [INVOKING JQ] section, they55 mostly concern input and output formatting. The <filter> is written56 in the jq language and specifies how to transform the input57 document.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>`71 72sections:73 - title: Invoking jq74 body: |75 76 jq filters run on a stream of JSON data. The input to jq is77 parsed as a sequence of whitespace-separated JSON values which78 are passed through the provided filter one at a time. The79 output(s) of the filter are written to standard out, again as a80 sequence of whitespace-separated JSON data.8182 You can affect how jq reads and writes its input and output83 using some command-line options:8485 * `--slurp`/`-s`:86 87 Instead of running the filter for each JSON object in the88 input, read the entire input stream into a large array and run89 the filter just once.90 91 * `--raw-input`/`-R`:92 93 Don't parse the input as JSON. Instead, each line of text is94 passed to the filter as a string. If combined with `--slurp`,95 then the entire input is passed to the filter as a single long96 string.97 98 * `--null-input`/`-n`:99 100 Don't read any input at all! Instead, the filter is run once101 using `null` as the input. This is useful when using jq as a102 simple calculator or to construct JSON data from scratch.103 104 * `--compact-output` / `-c`:105 106 By default, jq pretty-prints JSON output. Using this option107 will result in more compact output by instead putting each108 JSON object on a single line.109 110 * `--colour-output` / `-C` and `--monochrome-output` / `-M`:111 112 By default, jq outputs colored JSON if writing to a113 terminal. You can force it to produce color even if writing to114 a pipe or a file using `-C`, and disable color with `-M`.115 116 * `--ascii-output` / `-a`:117 118 jq usually outputs non-ASCII Unicode codepoints as UTF-8, even119 if the input specified them as escape sequences (like120 "\u03bc"). Using this option, you can force jq to produce pure121 ASCII output with every non-ASCII character replaced with the122 equivalent escape sequence.123 124 * `--raw-output` / `-r`:125 126 With this option, if the filter's result is a string then it127 will be written directly to standard output rather than being128 formatted as a JSON string with quotes. This can be useful for129 making jq filters talk to non-JSON-based systems.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: |141 142 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: |157 158 The simplest *useful* filter is .foo. When given a159 JSON object (aka dictionary or hash) as input, it produces160 the value at the key "foo", or null if there's none present.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: |172 173 You can also look up fields of an object using syntax like174 `.["foo"]` (.foo above is a shorthand version of this). This175 one works for arrays as well, if the key is an176 integer. Arrays are zero-based (like javascript), so `.[2]`177 returns the third element of the array.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"]']198 199 - 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: |209 210 If you use the `.[foo]` syntax, but omit the index211 entirely, it will return *all* of the elements of an212 array. Running `.[]` with the input `[1,2,3]` will produce the213 numbers as three separate results, rather than as a single214 array.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: |236 237 If two filters are separated by a comma, then the238 input will be fed into both and there will be multiple239 outputs: first, all of the outputs produced by the left240 expression, and then all of the outputs produced by the241 right. For instance, filter `.foo, .bar`, produces242 both the "foo" fields and "bar" fields as separate outputs.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"'] 252 253 - program: '.[4,2]'254 input: '["a","b","c","d","e"]'255 output: ['"e"', '"c"']256 257 - title: "`|`"258 body: |259 The | operator combines two filters by feeding the output(s) of260 the one on the left into the input of the one on the right. It's261 pretty much the same as the Unix shell's pipe, if you're used to262 that. 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: |276 277 jq supports the same set of datatypes as JSON - numbers,278 strings, booleans, arrays, objects (which in JSON-speak are279 hashes with only string keys), and "null".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: |290 291 As in JSON, `[]` is used to construct arrays, as in292 `[1,2,3]`. The elements of the arrays can be any jq293 expression. All of the results produced by all of the294 expressions are collected into one big array. You can use it295 to construct an array out of a known quantity of values (as296 in `[.foo, .bar, .baz]`) or to "collect" all the results of a297 filter into an array (as in `[.items[].name]`)298 299 Once you understand the "," operator, you can look at jq's array300 syntax in a different light: the expression `[1,2,3]` is not using a301 built-in syntax for comma-separated arrays, but is instead applying302 the `[]` operator (collect results) to the expression 1,2,3 (which303 produces three different results).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}`.318 319 If the keys are "sensible" (all alphabetic characters), then320 the quotes can be left off. The value can be any expression321 (although you may need to wrap it in parentheses if it's a322 complicated one), which gets applied to the {} expression's323 input (remember, all filters have an input and an324 output).325 326 {foo: .bar}327 328 will produce the JSON object `{"foo": 42}` if given the JSON329 object `{"bar":42, "baz":43}`. You can use this to select330 particular fields of an object: if the input is an object331 with "user", "title", "id", and "content" fields and you332 just want "user" and "title", you can write333 334 {user: .user, title: .title}335 336 Because that's so common, there's a shortcut syntax: `{user, title}`.337 338 If one of the expressions produces multiple results,339 multiple dictionaries will be produced. If the input's340 341 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}342 343 then the expression344 345 {user, title: .titles[]}346 347 will produce two outputs: 348 349 {"user":"stedolan", "title": "JQ Primer"}350 {"user":"stedolan", "title": "More JQ"}351 352 Putting parentheses around the key means it will be evaluated as an353 expression. With the same input as above,354 355 {(.user): .titles}356 357 produces358 359 {"stedolan": ["JQ Primer", "More JQ"]}360 361 examples:362 - program: '{user, title: .titles[]}'363 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'364 output:365 - '{"user":"stedolan", "title": "JQ Primer"}'366 - '{"user":"stedolan", "title": "More JQ"}'367 - program: '{(.user): .titles}'368 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'369 output: ['{"stedolan": ["JQ Primer", "More JQ"]}']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.379 380 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.393 394 - **Objects** are added by merging, that is, inserting all395 the key-value pairs from both objects into a single396 combined object. If both objects contain a value for the397 same key, the object on the right of the `+` wins.398 399 `null` can be added to any value, and returns the other400 value unchanged.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: |467 468 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: |490 491 The builtin function `has` returns whether the input object492 has the given key, or the input array has an element at the493 given index.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: |509 510 These functions convert between an object and an array of511 key-value pairs. If `to_entries` is passed an object, then512 for each `k: v` entry in the input, the output array513 includes `{"key": k, "value": v}`. 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: |534 535 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: |549 550 `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: |601 602 The `range` function produces a range of numbers. `range(4;10)`603 produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers604 are produced as separate outputs. Use `[range(4;10)]` to get a range as 605 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]']614 615 - 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: |641 642 The `type` function returns the type of its argument as a643 string, which is one of null, boolean, number, string, array644 or object.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: |653 654 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: |685 686 `group_by(.foo)` takes as input an array, groups the687 elements having the same `.foo` field into separate arrays,688 and produces all of these arrays as elements of a larger689 array, sorted by the value of the `.foo` field.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: |702 703 Find the minimum or maximum element of the input array. The704 `_by` versions allow you to specify a particular field or705 property to examine, e.g. `min_by(.foo)` finds the object706 with the smallest `foo` field.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: |718 719 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: |730 731 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: |769 770 The `recurse` function allows you to search through a771 recursive structure, and extract interesting data from all772 levels. Suppose your input represents a filesystem: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": []}]}]}]}781 782 Now suppose you want to extract all of the filenames783 present. You need to retrieve `.name`, `.children[].name`,784 `.children[].children[].name`, and so on. You can do this785 with: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"']810 811 - 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`:839 840 The input must be an array, and it is rendered as CSV841 with double quotes for strings, and quotes escaped by842 repetition.843844 * `@sh`:845 846 The input is escaped suitable for use in a command-line847 for a POSIX shell. If the input is an array, the output848 will be a series of space-separated strings.849 850 * `@base64`: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 "http://www.google.com/search?q=\(.search)"861862 will produce the following output for the input863 `{"search":"jq!"}`:864865 http://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'\""]882 883 - 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.894 895 != 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.907 908 Checking for false or null is a simpler notion of909 "truthiness" than is found in Javascript or Python, but it910 means that you'll sometimes have to be more explicit about911 the condition you want: you can't test whether, e.g. a912 string is empty using `if .name then A else B end`, you'll913 need something more like `if (.name | count) > 0 then A else914 B end` instead.915 916 If the condition A produces multiple results, it is917 considered "true" if any of those results is not false or918 null. If it produces zero results, it's considered false.919 920 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"']933 934 - title: `>, >=, <=, <`935 body: |936 937 The comparison operators `>`, `>=`, `<=`, `<` return whether938 their left argument is greater than, greater than or equal939 to, less than or equal to or less than their right argument940 (respectively).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`.963 964 These three only produce the values "true" and "false", and965 so are only useful for genuine Boolean operations, rather966 than the common Perl/Python/Ruby idiom of967 "value_that_may_be_null or default". If you want to use this968 form of "or", picking between two values rather than969 evaluating a condition, see the "//" operator below.970 971 examples:972 - program: '42 and "a string"'973 input: 'null'974 output: ['true']975 - program: '(true, false) or false'976 input: 'null'977 output: ['true', 'false']978# - program: '(true, false) and (true, false)'979# input: 'null'980# output: ['true', 'false', 'false', 'false']981 - program: '(true, true) and (true, false)'982 input: 'null'983 output: ['true', 'false', 'true', 'false']984 - program: '[true, false | not]'985 input: 'null'986 output: ['[false, true]']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]1008 1009 - title: Advanced features1010 body: |1011 Variables are an absolute necessity in most programming languages, but1012 they're relegated to an "advanced feature" in jq.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: |1033 1034 In jq, all filters have an input and an output, so manual1035 plumbing is not necessary to pass a value from one part of a program1036 to the next. Many expressions, for instance `a + b`, pass their input1037 to two distinct subexpressions (here `a` and `b` are both passed the1038 same input), so variables aren't usually necessary in order to use a1039 value twice.1040 1041 For instance, calculating the average value of an array of numbers1042 requires a few variables in most languages - at least one to hold the1043 array, perhaps one for each element or for a loop counter. In jq, it's1044 simply `add / length` - the `add` expression is given the array and1045 produces its sum, and the `length` expression is given the array and1046 produces its length.1047 1048 So, there's generally a cleaner way to solve most problems in jq that1049 defining variables. Still, sometimes they do make things easier, so jq1050 lets you define variables using `expression as $variable`. All1051 variable names start with `$`. Here's a slightly uglier version of the1052 array-averaging example:1053 1054 length as $array_length | add / $array_length1055 1056 We'll need a more complicated problem to find a situation where using1057 variables actually makes our lives easier.1058 1059 1060 Suppose we have an array of blog posts, with "author" and "title"1061 fields, and another object which is used to map author usernames to1062 real names. Our input looks like:1063 1064 {"posts": [{"title": "Frist psot", "author": "anon"},1065 {"title": "A well-written article", "author": "person1"}],1066 "realnames": {"anon": "Anonymous Coward",1067 "person1": "Person McPherson"}}1068 1069 We want to produce the posts with the author field containing a real1070 name, as in:1071 1072 {"title": "Frist psot", "author": "Anonymous Coward"}1073 {"title": "A well-written article", "author": "Person McPherson"}1074 1075 We use a variable, $names, to store the realnames object, so that we1076 can refer to it later when looking up author usernames:1077 1078 .realnames as $names | .posts[] | {title, author: $names[.author]}1079 1080 The expression `exp as $x | ...` means: for each value of expression1081 `exp`, run the rest of the pipeline with the entire original input, and1082 with `$x` set to that value. Thus `as` functions as something of a 1083 foreach loop.10841085 Variables are scoped over the rest of the expression that defines1086 them, so 1087 1088 .realnames as $names | (.posts[] | {title, author: $names[.author]})1089 1090 will work, but 1091 1092 (.realnames as $names | .posts[]) | {title, author: $names[.author]}1093 1094 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: |1103 1104 You can give a filter a name using "def" syntax:11051106 def increment: . + 1;1107 1108 From then on, `increment` is usable as a filter just like a1109 builtin function (in fact, this is how some of the builtins1110 are defined). A function may take arguments: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: |1138 1139 The `reduce` syntax in jq allows you to combine all of the1140 results of an expression by accumulating them into a single1141 answer. As an example, we'll pass `[3,2,1]` to this expression:11421143 reduce .[] as $item (0; . + $item)1144 1145 For each result that `.[]` produces, `. + $item` is run to1146 accumulate a running total, starting from 0. In this1147 example, `.[]` produces the results 3, 2, and 1, so the1148 effect is similar to running something like this: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']1158 11591160 - 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: |1180 1181 The filter `.foo = 1` will take as input an object1182 and produce as output an object with the "foo" field set to1183 1. There is no notion of "modifying" or "changing" something1184 in jq - all jq values are immutable. For instance,1185 1186 .foo = .bar | .foo.baz = 11187 1188 will not have the side-effect of setting .bar.baz to be set1189 to 1, as the similar-looking program in Javascript, Python,1190 Ruby or other languages would. Unlike these languages (but1191 like Haskell and some other functional languages), there is1192 no notion of two arrays or objects being "the same array" or1193 "the same object". They can be equal, or not equal, but if1194 we change one of them in no circumstances will the other1195 change behind our backs.1196 1197 This means that it's impossible to build circular values in1198 jq (such as an array whose first element is itself). This is1199 quite intentional, and ensures that anything a jq program1200 can produce can be represented in JSON.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.1209 1210 This example should show the difference between '=' and '|=':1211 1212 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:1213 1214 .a = .b1215 .a |= .b1216 1217 The former will set the "a" field of the input to the "b" field of the1218 input, and produce the output {"a": 20}. The latter will set the "a"1219 field of the input to the "a" field's "b" field, producing {"a": 10}.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}']1231 1232 - title: Complex assignments1233 body: |1234 Lots more things are allowed on the left-hand side of a jq assignment1235 than in most langauges. We've already seen simple field accesses on1236 the left hand side, and it's no surprise that array accesses work just1237 as well:1238 1239 .posts[0].title = "JQ Manual"1240 1241 What may come as a surprise is that the expression on the left may1242 produce multiple results, referring to different points in the input1243 document:1244 1245 .posts[].comments |= . + ["this is great"]1246 1247 That example appends the string "this is great" to the "comments"1248 array of each post in the input (where the input is an object with a1249 field "posts" which is an array of posts).1250 1251 When jq encounters an assignment like 'a = b', it records the "path"1252 taken to select a part of the input document while executing a. This1253 path is then used to find which part of the input to change while1254 executing the assignment. Any filter may be used on the1255 left-hand side of an equals - whichever paths it selects from the1256 input will be where the assignment is performed.1257 1258 This is a very powerful operation. Suppose we wanted to add a comment1259 to blog posts, using the same "blog" input above. This time, we only1260 want to comment on the posts written by "stedolan". We can find those1261 posts using the "select" function described earlier:1262 1263 .posts[] | select(.author == "stedolan")1264 1265 The paths provided by this operation point to each of the posts that1266 "stedolan" wrote, and we can comment on each of them in the same way1267 that we did before:1268 1269 (.posts[] | select(.author == "stedolan") | .comments) |=1270 . + ["terrible."]
added:docs/content/3.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.19 20 Some filters produce multiple results, for instance there's one that21 produces all the elements of its input array. Piping that filter22 into a second runs the second filter for each element of the23 array. Generally, things that would be done with loops and iteration24 in other languages are just done by gluing filters together in jq.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.53 54 The <options> are described in the [INVOKING JQ] section, they55 mostly concern input and output formatting. The <filter> is written56 in the jq language and specifies how to transform the input57 document.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>`71 72sections:73 - title: Invoking jq74 body: |75 76 jq filters run on a stream of JSON data. The input to jq is77 parsed as a sequence of whitespace-separated JSON values which78 are passed through the provided filter one at a time. The79 output(s) of the filter are written to standard out, again as a80 sequence of whitespace-separated JSON data.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`:101 102 Instead of running the filter for each JSON object in the103 input, read the entire input stream into a large array and run104 the filter just once.105106 * `--online-input`/`-I`:107 108 When the top-level input value is an array produce its elements109 instead of the array. This allows on-line processing of110 potentially very large top-level arrays' elements.111 112 * `--raw-input`/`-R`:113 114 Don't parse the input as JSON. Instead, each line of text is115 passed to the filter as a string. If combined with `--slurp`,116 then the entire input is passed to the filter as a single long117 string.118 119 * `--null-input`/`-n`:120 121 Don't read any input at all! Instead, the filter is run once122 using `null` as the input. This is useful when using jq as a123 simple calculator or to construct JSON data from scratch.124 125 * `--compact-output` / `-c`:126 127 By default, jq pretty-prints JSON output. Using this option128 will result in more compact output by instead putting each129 JSON object on a single line.130 131 * `--colour-output` / `-C` and `--monochrome-output` / `-M`:132 133 By default, jq outputs colored JSON if writing to a134 terminal. You can force it to produce color even if writing to135 a pipe or a file using `-C`, and disable color with `-M`.136 137 * `--ascii-output` / `-a`:138 139 jq usually outputs non-ASCII Unicode codepoints as UTF-8, even140 if the input specified them as escape sequences (like141 "\u03bc"). Using this option, you can force jq to produce pure142 ASCII output with every non-ASCII character replaced with the143 equivalent escape sequence.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`:152 153 Output the fields of each object with the keys in sorted order.154155 * `--raw-output` / `-r`:156 157 With this option, if the filter's result is a string then it158 will be written directly to standard output rather than being159 formatted as a JSON string with quotes. This can be useful for160 making jq filters talk to non-JSON-based systems.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: |194 195 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: |210 211 The simplest *useful* filter is `.foo`. When given a212 JSON object (aka dictionary or hash) as input, it produces213 the value at the key "foo", or null if there's none present.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`.219 220 examples:221 - program: '.foo'222 input: '{"foo": 42, "bar": "less interesting data"}'223 output: [42]224 - program: '.foo'225 input: '{"notfoo": true, "alsonotfoo": false}'226 output: ['null']227 - program: '.["foo"]'228 input: '{"foo": 42}'229 output: [42]230231 - title: "`.foo?`"232 body: |233 234 Just like `.foo`, but does not output even an error when `.`235 is not an array or an object.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: |253 254 You can also look up fields of an object using syntax like255 `.["foo"]` (.foo above is a shorthand version of this). This256 one works for arrays as well, if the key is an257 integer. Arrays are zero-based (like javascript), so `.[2]`258 returns the third element of the array.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"']288 289 - 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: |299 300 If you use the `.[index]` syntax, but omit the index301 entirely, it will return *all* of the elements of an302 array. Running `.[]` with the input `[1,2,3]` will produce the303 numbers as three separate results, rather than as a single304 array.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: |326 327 Like `.[]`, but no errors will be output if . is not an array328 or object.329330 - title: "`,`"331 body: |332 333 If two filters are separated by a comma, then the334 input will be fed into both and there will be multiple335 outputs: first, all of the outputs produced by the left336 expression, and then all of the outputs produced by the337 right. For instance, filter `.foo, .bar`, produces338 both the "foo" fields and "bar" fields as separate outputs.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"'] 348 349 - program: '.[4,2]'350 input: '["a","b","c","d","e"]'351 output: ['"e"', '"c"']352 353 - title: "`|`"354 body: |355 The | operator combines two filters by feeding the output(s) of356 the one on the left into the input of the one on the right. It's357 pretty much the same as the Unix shell's pipe, if you're used to358 that. 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: |372 373 jq supports the same set of datatypes as JSON - numbers,374 strings, booleans, arrays, objects (which in JSON-speak are375 hashes with only string keys), and "null".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: |386 387 As in JSON, `[]` is used to construct arrays, as in388 `[1,2,3]`. The elements of the arrays can be any jq389 expression. All of the results produced by all of the390 expressions are collected into one big array. You can use it391 to construct an array out of a known quantity of values (as392 in `[.foo, .bar, .baz]`) or to "collect" all the results of a393 filter into an array (as in `[.items[].name]`)394 395 Once you understand the "," operator, you can look at jq's array396 syntax in a different light: the expression `[1,2,3]` is not using a397 built-in syntax for comma-separated arrays, but is instead applying398 the `[]` operator (collect results) to the expression 1,2,3 (which399 produces three different results).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}`.414 415 If the keys are "sensible" (all alphabetic characters), then416 the quotes can be left off. The value can be any expression417 (although you may need to wrap it in parentheses if it's a418 complicated one), which gets applied to the {} expression's419 input (remember, all filters have an input and an420 output).421 422 {foo: .bar}423 424 will produce the JSON object `{"foo": 42}` if given the JSON425 object `{"bar":42, "baz":43}`. You can use this to select426 particular fields of an object: if the input is an object427 with "user", "title", "id", and "content" fields and you428 just want "user" and "title", you can write429 430 {user: .user, title: .title}431 432 Because that's so common, there's a shortcut syntax: `{user, title}`.433 434 If one of the expressions produces multiple results,435 multiple dictionaries will be produced. If the input's436 437 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}438 439 then the expression440 441 {user, title: .titles[]}442 443 will produce two outputs: 444 445 {"user":"stedolan", "title": "JQ Primer"}446 {"user":"stedolan", "title": "More JQ"}447 448 Putting parentheses around the key means it will be evaluated as an449 expression. With the same input as above,450 451 {(.user): .titles}452 453 produces454 455 {"stedolan": ["JQ Primer", "More JQ"]}456 457 examples:458 - program: '{user, title: .titles[]}'459 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'460 output:461 - '{"user":"stedolan", "title": "JQ Primer"}'462 - '{"user":"stedolan", "title": "More JQ"}'463 - program: '{(.user): .titles}'464 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'465 output: ['{"stedolan": ["JQ Primer", "More JQ"]}']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.475 476 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.489 490 - **Objects** are added by merging, that is, inserting all491 the key-value pairs from both objects into a single492 combined object. If both objects contain a value for the493 same key, the object on the right of the `+` wins. (For494 recursive merge use the `*` operator.)495 496 `null` can be added to any value, and returns the other497 value unchanged.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: |581 582 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: |604 605 The builtin function `has` returns whether the input object606 has the given key, or the input array has an element at the607 given index.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: |623 624 The builtin function `del` removes a key and its corresponding625 value from an object.626 627 examples:628 - program: 'del(.foo)'629 input: '[{"foo": 42, "bar": 9001, "baz": 42}]'630 output: ['{"bar": 9001, "baz": 42}']631 - program: 'del(.[1, 2])'632 input: '[["foo", "bar", "baz"]]'633 output: ['["foo"]']634635 - title: "`to_entries`, `from_entries`, `with_entries`"636 body: |637 638 These functions convert between an object and an array of639 key-value pairs. If `to_entries` is passed an object, then640 for each `k: v` entry in the input, the output array641 includes `{"key": k, "value": v}`. 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: |662 663 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: |678 679 These built-ins select only inputs that are arrays, objects,680 iterables (arrays or objects), booleans, numbers, strings,681 null, non-null values, and non-iterables, respectively.682683 examples:684 - program: '.[]|numbers'685 input: '[[],{},1,"foo",null,true,false]'686 output: ['1']687688 - title: "`empty`"689 body: |690 691 `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 to 725726 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: |768 769 The filter `any` takes as input an array of boolean values,770 and produces `true` as output if any of the the elements of771 the array is `true`.772 773 If the input is an empty array, `any` returns `false`.774 775 examples:776 - program: any777 input: '[true, false]'778 output: ["true"]779 - program: any780 input: '[false, false]'781 output: ["false"]782 - program: any783 input: '[]'784 output: ["false"]785786 - title: "`all`"787 body: |788 789 The filter `all` takes as input an array of boolean values,790 and produces `true` as output if all of the the elements of791 the array are `true`.792 793 If the input is an empty array, `all` returns `true`.794 795 examples:796 - program: all797 input: '[true, false]'798 output: ["false"]799 - program: all800 input: '[true, true]'801 output: ["true"]802 - program: all803 input: '[]'804 output: ["true"]805806 - title: "`range`"807 body: |808 809 The `range` function produces a range of numbers. `range(4;10)`810 produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers811 are produced as separate outputs. Use `[range(4;10)]` to get a range as 812 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]']821 822 - 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']831 832 - 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']841 842 - 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: |868 869 The `type` function returns the type of its argument as a870 string, which is one of null, boolean, number, string, array871 or object.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: |880 881 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: |912 913 `group_by(.foo)` takes as input an array, groups the914 elements having the same `.foo` field into separate arrays,915 and produces all of these arrays as elements of a larger916 array, sorted by the value of the `.foo` field.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: |929 930 Find the minimum or maximum element of the input array. The931 `_by` versions allow you to specify a particular field or932 property to examine, e.g. `min_by(.foo)` finds the object933 with the smallest `foo` field.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: |945 946 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: |957 958 The `unique_by(.foo)` function takes as input an array and produces959 an array of the same elements, in sorted order, with960 elqements with a duplicate `.foo` field removed. Think of it as making961 an array by taking one element out of every group produced by962 `group_by`.963 964 examples:965 - program: 'unique_by(.foo)'966 input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'967 output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']968 - program: 'unique_by(length)'969 input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'970 output: ['["chunky", "bacon", "asparagus"]']971972973 - title: "`reverse`"974 body: |975 976 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, true, false, false]']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: |1120 1121 Joins the array of elements given as input, using the1122 argument as separator. It is the inverse of `split`: that is,1123 running `split("foo") | join("foo")` over any input string1124 returns said input string.1125 1126 examples:1127 - program: 'join(", ")'1128 input: '["a","b,c,d","e"]'1129 output: ['"a, b,c,d, e"']113011311132 - title: "`recurse`"1133 body: |1134 1135 The `recurse` function allows you to search through a1136 recursive structure, and extract interesting data from all1137 levels. Suppose your input represents a filesystem: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": []}]}]}]}1146 1147 Now suppose you want to extract all of the filenames1148 present. You need to retrieve `.name`, `.children[].name`,1149 `.children[].children[].name`, and so on. You can do this1150 with: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: |1165 1166 A quieter version of `recurse(.[])`, equivalent to:11671168 def recurse_down: recurse(.[]?);11691170 - title: "`..`"1171 body: |1172 1173 Short-hand for `recurse_down`. This is intended to resemble1174 the XPath `//` operator. Note that `..a` does not work; use1175 `..|a` instead.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"']1193 1194 - 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`:1241 1242 The input must be an array, and it is rendered as CSV1243 with double quotes for strings, and quotes escaped by1244 repetition.12451246 * `@sh`:1247 1248 The input is escaped suitable for use in a command-line1249 for a POSIX shell. If the input is an array, the output1250 will be a series of space-separated strings.1251 1252 * `@base64`: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 "http://www.google.com/search?q=\(.search)"12631264 will produce the following output for the input1265 `{"search":"what is jq?"}`:12661267 "http://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'\""]1284 1285 - 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.1296 1297 != 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.1309 1310 Checking for false or null is a simpler notion of1311 "truthiness" than is found in Javascript or Python, but it1312 means that you'll sometimes have to be more explicit about1313 the condition you want: you can't test whether, e.g. a1314 string is empty using `if .name then A else B end`, you'll1315 need something more like `if (.name | length) > 0 then A else1316 B end` instead.1317 1318 If the condition A produces multiple results, it is1319 considered "true" if any of those results is not false or1320 null. If it produces zero results, it's considered false.1321 1322 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"']1335 1336 - title: "`>, >=, <=, <`"1337 body: |1338 1339 The comparison operators `>`, `>=`, `<=`, `<` return whether1340 their left argument is greater than, greater than or equal1341 to, less than or equal to or less than their right argument1342 (respectively).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`.1365 1366 These three only produce the values "true" and "false", and1367 so are only useful for genuine Boolean operations, rather1368 than the common Perl/Python/Ruby idiom of1369 "value_that_may_be_null or default". If you want to use this1370 form of "or", picking between two values rather than1371 evaluating a condition, see the "//" operator below.1372 1373 examples:1374 - program: '42 and "a string"'1375 input: 'null'1376 output: ['true']1377 - program: '(true, false) or false'1378 input: 'null'1379 output: ['true', 'false']1380# - program: '(true, false) and (true, false)'1381# input: 'null'1382# output: ['true', 'false', 'false', 'false']1383 - program: '(true, true) and (true, false)'1384 input: 'null'1385 output: ['true', 'false', 'true', 'false']1386 - program: '[true, false | not]'1387 input: 'null'1388 output: ['[false, true]']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]1410 1411 - title: Advanced features1412 body: |1413 Variables are an absolute necessity in most programming languages, but1414 they're relegated to an "advanced feature" in jq.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: |1435 1436 In jq, all filters have an input and an output, so manual1437 plumbing is not necessary to pass a value from one part of a program1438 to the next. Many expressions, for instance `a + b`, pass their input1439 to two distinct subexpressions (here `a` and `b` are both passed the1440 same input), so variables aren't usually necessary in order to use a1441 value twice.1442 1443 For instance, calculating the average value of an array of numbers1444 requires a few variables in most languages - at least one to hold the1445 array, perhaps one for each element or for a loop counter. In jq, it's1446 simply `add / length` - the `add` expression is given the array and1447 produces its sum, and the `length` expression is given the array and1448 produces its length.1449 1450 So, there's generally a cleaner way to solve most problems in jq than1451 defining variables. Still, sometimes they do make things easier, so jq1452 lets you define variables using `expression as $variable`. All1453 variable names start with `$`. Here's a slightly uglier version of the1454 array-averaging example:1455 1456 length as $array_length | add / $array_length1457 1458 We'll need a more complicated problem to find a situation where using1459 variables actually makes our lives easier.1460 1461 1462 Suppose we have an array of blog posts, with "author" and "title"1463 fields, and another object which is used to map author usernames to1464 real names. Our input looks like:1465 1466 {"posts": [{"title": "Frist psot", "author": "anon"},1467 {"title": "A well-written article", "author": "person1"}],1468 "realnames": {"anon": "Anonymous Coward",1469 "person1": "Person McPherson"}}1470 1471 We want to produce the posts with the author field containing a real1472 name, as in:1473 1474 {"title": "Frist psot", "author": "Anonymous Coward"}1475 {"title": "A well-written article", "author": "Person McPherson"}1476 1477 We use a variable, $names, to store the realnames object, so that we1478 can refer to it later when looking up author usernames:1479 1480 .realnames as $names | .posts[] | {title, author: $names[.author]}1481 1482 The expression `exp as $x | ...` means: for each value of expression1483 `exp`, run the rest of the pipeline with the entire original input, and1484 with `$x` set to that value. Thus `as` functions as something of a 1485 foreach loop.14861487 Variables are scoped over the rest of the expression that defines1488 them, so 1489 1490 .realnames as $names | (.posts[] | {title, author: $names[.author]})1491 1492 will work, but 1493 1494 (.realnames as $names | .posts[]) | {title, author: $names[.author]}1495 1496 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: |1505 1506 You can give a filter a name using "def" syntax:15071508 def increment: . + 1;1509 1510 From then on, `increment` is usable as a filter just like a1511 builtin function (in fact, this is how some of the builtins1512 are defined). A function may take arguments: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: |1540 1541 The `reduce` syntax in jq allows you to combine all of the1542 results of an expression by accumulating them into a single1543 answer. As an example, we'll pass `[3,2,1]` to this expression:15441545 reduce .[] as $item (0; . + $item)1546 1547 For each result that `.[]` produces, `. + $item` is run to1548 accumulate a running total, starting from 0. In this1549 example, `.[]` produces the results 3, 2, and 1, so the1550 effect is similar to running something like this: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']1560 15611562 - 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: |1582 1583 The filter `.foo = 1` will take as input an object1584 and produce as output an object with the "foo" field set to1585 1. There is no notion of "modifying" or "changing" something1586 in jq - all jq values are immutable. For instance,1587 1588 .foo = .bar | .foo.baz = 11589 1590 will not have the side-effect of setting .bar.baz to be set1591 to 1, as the similar-looking program in Javascript, Python,1592 Ruby or other languages would. Unlike these languages (but1593 like Haskell and some other functional languages), there is1594 no notion of two arrays or objects being "the same array" or1595 "the same object". They can be equal, or not equal, but if1596 we change one of them in no circumstances will the other1597 change behind our backs.1598 1599 This means that it's impossible to build circular values in1600 jq (such as an array whose first element is itself). This is1601 quite intentional, and ensures that anything a jq program1602 can produce can be represented in JSON.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.1611 1612 This example should show the difference between '=' and '|=':1613 1614 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:1615 1616 .a = .b1617 .a |= .b1618 1619 The former will set the "a" field of the input to the "b" field of the1620 input, and produce the output {"a": 20}. The latter will set the "a"1621 field of the input to the "a" field's "b" field, producing {"a": 10}.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}']1633 1634 - title: Complex assignments1635 body: |1636 Lots more things are allowed on the left-hand side of a jq assignment1637 than in most langauges. We've already seen simple field accesses on1638 the left hand side, and it's no surprise that array accesses work just1639 as well:1640 1641 .posts[0].title = "JQ Manual"1642 1643 What may come as a surprise is that the expression on the left may1644 produce multiple results, referring to different points in the input1645 document:1646 1647 .posts[].comments |= . + ["this is great"]1648 1649 That example appends the string "this is great" to the "comments"1650 array of each post in the input (where the input is an object with a1651 field "posts" which is an array of posts).1652 1653 When jq encounters an assignment like 'a = b', it records the "path"1654 taken to select a part of the input document while executing a. This1655 path is then used to find which part of the input to change while1656 executing the assignment. Any filter may be used on the1657 left-hand side of an equals - whichever paths it selects from the1658 input will be where the assignment is performed.1659 1660 This is a very powerful operation. Suppose we wanted to add a comment1661 to blog posts, using the same "blog" input above. This time, we only1662 want to comment on the posts written by "stedolan". We can find those1663 posts using the "select" function described earlier:1664 1665 .posts[] | select(.author == "stedolan")1666 1667 The paths provided by this operation point to each of the posts that1668 "stedolan" wrote, and we can comment on each of them in the same way1669 that we did before:1670 1671 (.posts[] | select(.author == "stedolan") | .comments) |=1672 . + ["terrible."]
modified:docs/content/3.manual/manual.yml+7 added-1 removed
1---2headline: jq Manual2headline: jq Manual (development version)34history: |56 *For released versions, see [jq 1.4](/jq/manual/v1.4) or7 [jq 1.3](/jq/manual/v1.3).*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 a
2847 unmodified lines
modified:docs/templates/manual.liquid+1 added
55 unmodified lines
56 </div>57 </div>58 <div class="span9">59 <h1>{{headline}}</h1>60 {{ history | markdownify }}61 {{ body | markdownify }}62 {% for section in sections %}63 <section id="{{section.title | sanitize}}">64 <h2>{{section.title}}</h2>
58 unmodified lines