Remove all trailing whitespace
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 aff6f49 · Browse files · 16 files·+319 added−319 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+319 added−319 removed
- other:+319 added−319 removed
Provenance
- Commit
0f41956- Tree
da1189f- Author
David Tolnay <dtolnay@gmail.com>- Committer
David Tolnay <dtolnay@gmail.com>- Parent
aff6f49
16 files changed+319 added−319 removed
modified:docs/content/2.download/default.yml+2 added-2 removed
13 unmodified lines14151617181819202122102 unmodified linesExpand all1251261271281291291301311321339 unmodified lines13 unmodified lines details, read the file `COPYING` in the source distribution.
### Linux
* jq 1.4 is in the official [Debian](http://packages.debian.org/jq) and [Ubuntu](http://packages.ubuntu.com/jq) repositories. Install using `sudo apt-get install jq`.
102 unmodified linesExpand all Flex and Bison are used to generate the lexer and parser for jq. For jq 1.5, neither is required if you use `./configure --disable-maintainer-mode` instead of `./configure`. This flag says to use the pre-generated lexer and parser that come with the code.
#### Building the documentation
jq's documentation is compiled into static HTML using [Bonsai](http://www.tinytree.info). To view the documentation9 unmodified linesmodified:docs/content/3.manual/v1.3/manual.yml+126 added-126 removed
14 unmodified lines15 16 Filters can be combined in various ways - you can pipe the output of17 one filter into another filter, or collect the output of a filter18 into an array.19- 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 iteration25 unmodified lines49 50 By default, `jq` reads a stream of JSON objects (whitespace51 separated) from `stdin`. One or more <files> may be specified, in52 which case `jq` will read input from those instead.53- 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.9 unmodified lines67 68 ## AUTHOR69 70 Stephen Dolan `<mu@netsoc.tcd.ie>`71- 71+72 sections:73 - title: Invoking jq74 body: |75- 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 a2 unmodified lines82 You can affect how jq reads and writes its input and output83 using some command-line options:84 85 * `--slurp`/`-s`:86- 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- 90+91 * `--raw-input`/`-R`:92- 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- 97+98 * `--null-input`/`-n`:99- 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- 103+104 * `--compact-output` / `-c`:105- 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- 109+110 * `--colour-output` / `-C` and `--monochrome-output` / `-M`:111- 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- 115+116 * `--ascii-output` / `-a`:117- 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- 123+124 * `--raw-output` / `-r`:125- 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.7 unmodified lines137 - title: Basic filters138 entries:139 - title: "`.`"140 body: |141- 141+142 The absolute simplest (and least interesting) filter143 is `.`. This is a filter that takes its input and144 produces it unchanged as output.145 7 unmodified lines153 output: ['"Hello, world!"']154 155 - title: "`.foo`"156 body: |157- 157+158 The simplest *useful* filter is .foo. When given a159 JSON object (aka dictionary or hash) as input, it produces160 the value at the key "foo", or null if there's none present.161 6 unmodified lines168 output: ['null']169 170 - title: "`.[foo]`, `.[2]`, `.[10:15]`"171 body: |172- 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]`17 unmodified lines194 195 - program: '.[2:4]'196 input: '["a","b","c","d","e"]'197 output: ['["c", "d"]']198- 198+199 - program: '.[:3]'200 input: '["a","b","c","d","e"]'201 output: ['["a", "b", "c"]']202 2 unmodified lines205 output: ['["d", "e"]']206 207 - title: "`.[]`"208 body: |209- 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 single18 unmodified lines232 output: ['1', '1']233 234 - title: "`,`"235 body: |236- 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 the6 unmodified lines247 output: ['42', '"something else"']248 249 - program: ".user, .projects[]"250 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'251- output: ['"stedolan"', '"jq"', '"wikiflow"'] 252- 251+ output: ['"stedolan"', '"jq"', '"wikiflow"']252+253 - program: '.[4,2]'254 input: '["a","b","c","d","e"]'255 output: ['"e"', '"c"']256- 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. 262+ that.263 264 If the one on the left produces multiple results, the one on265 the right will be run for each of those results. So, the266 expression `.[] | .foo` retrieves the "foo" field of each5 unmodified lines272 output: ['"JSON"', '"XML"']273 274 - title: Types and Values275 body: |276- 276+277 jq supports the same set of datatypes as JSON - numbers,278 strings, booleans, arrays, objects (which in JSON-speak are279 hashes with only string keys), and "null".280 5 unmodified lines286 287 entries:288 - title: Array construction - `[]`289 body: |290- 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- 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 (which11 unmodified lines314 body: |315 316 Like JSON, `{}` is for constructing objects (aka317 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.318- 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- 325+326 {foo: .bar}327- 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- 333+334 {user: .user, title: .title}335- 335+336 Because that's so common, there's a shortcut syntax: `{user, title}`.337- 337+338 If one of the expressions produces multiple results,339 multiple dictionaries will be produced. If the input's340- 340+341 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}342- 342+343 then the expression344- 344+345 {user, title: .titles[]}346- 347- will produce two outputs: 348- 346+347+ will produce two outputs:348+349 {"user":"stedolan", "title": "JQ Primer"}350 {"user":"stedolan", "title": "More JQ"}351- 351+352 Putting parentheses around the key means it will be evaluated as an353 expression. With the same input as above,354- 354+355 {(.user): .titles}356- 356+357 produces358- 358+359 {"stedolan": ["JQ Primer", "More JQ"]}360- 360+361 examples:362 - program: '{user, title: .titles[]}'363 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'364 output:10 unmodified lines375 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- 379+380 entries:381 - title: Addition - `+`382 body: |383 5 unmodified lines389 390 - **Arrays** are added by being concatenated into a larger array.391 392 - **Strings** are added by being joined into a larger string.393- 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- 398+399 `null` can be added to any value, and returns the other400 value unchanged.401 402 examples:60 unmodified lines463 output: [2, 6, 1, 0]464 465 - title: `keys`466 body: |467- 467+468 The builtin function `keys`, when given an object, returns469 its keys in an array.470 471 The keys are sorted "alphabetically", by unicode codepoint14 unmodified lines486 output: ['[0,1,2]']487 488 - title: `has`489 body: |490- 490+491 The builtin function `has` returns whether the input object492 has the given key, or the input array has an element at the493 given index.494 10 unmodified lines505 output: ['[false, true]']506 507 - title: `to_entries`, `from_entries`, `with_entries`508 body: |509- 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}`. 513+ includes `{"key": k, "value": v}`.514 515 `from_entries` does the opposite conversion, and516 `with_entries(foo)` is a shorthand for `to_entries |517 map(foo) | from_entries`, useful for doing some operation to12 unmodified lines530 531 532 - title: `select`533 body: |534- 534+535 The function `select(foo)` produces its input unchanged if536 `foo` returns true for that input, and produces no output537 otherwise.538 6 unmodified lines545 output: ['[5,3,7]']546 547 - title: `empty`548 body: |549- 549+550 `empty` returns no results. None at all. Not even `null`.551 552 It's useful on occasion. You'll know if you need it :)553 43 unmodified lines597 output: ["null"]598 599 - title: `range`600 body: |601- 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 604+ are produced as separate outputs. Use `[range(4;10)]` to get a range as605 an array.606 607 examples:608 - program: 'range(2;4)'1 unmodified line610 output: ['2', '3']611 - program: '[range(2;4)]'612 input: 'null'613 output: ['[2,3]']614- 614+615 - title: `tonumber`616 body: |617 618 The `tonumber` function parses its input as a number. It18 unmodified lines637 output: ['"1"', '"1"', '"[1]"']638 639 - title: `type`640 body: |641- 641+642 The `type` function returns the type of its argument as a643 string, which is one of null, boolean, number, string, array644 or object.645 3 unmodified lines649 output: ['["number", "boolean", "array", "object", "null", "string"]']650 651 - title: `sort, sort_by`652 body: |653- 653+654 The `sort` functions sorts its input, which must be an655 array. Values are sorted in the following order:656 657 * `null`23 unmodified lines681 output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']682 683 - title: `group_by`684 body: |685- 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.8 unmodified lines698 output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']699 700 - title: `min`, `max`, `min_by`, `max_by`701 body: |702- 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.7 unmodified lines714 output: ['{"foo":2, "bar":3}']715 716 - title: `unique`717 body: |718- 718+719 The `unique` function takes as input an array and produces720 an array of the same elements, in sorted order, with721 duplicates removed.722 3 unmodified lines726 output: ['[1,2,3,5]']727 728 - title: `reverse`729 body: |730- 730+731 This function reverses an array.732 733 examples:734 - program: 'reverse'30 unmodified lines765 output: ['false']766 767 - title: `recurse`768 body: |769- 769+770 The `recurse` function allows you to search through a771 recursive structure, and extract interesting data from all772 levels. Suppose your input represents a filesystem:773 3 unmodified lines777 {"name": "/bin/sh", "children": []}]},778 {"name": "/home", "children": [779 {"name": "/home/stephen", "children": [780 {"name": "/home/stephen/jq", "children": []}]}]}]}781- 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:2 unmodified lines788 789 examples:790 - program: 'recurse(.foo[])'791 input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'792- output: 792+ output:793 - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'794 - '{"foo":[]}'795 - '{"foo":[{"foo":[]}]}'796 - '{"foo":[]}'9 unmodified lines806 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- 810+811 - title: "Format strings and escaping"812 body: |813 814 The `@foo` syntax is used to format and escape strings,20 unmodified lines835 Applies percent-encoding, by mapping all reserved URI836 characters to a `%xx` sequence.837 838 * `@csv`:839- 839+840 The input must be an array, and it is rendered as CSV841 with double quotes for strings, and quotes escaped by842 repetition.843 844 * `@sh`:845- 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- 849+850 * `@base64`:851 852 The input is converted to base64 as specified by RFC 4648.853 24 unmodified lines878 879 - program: '@sh "echo \(.)"'880 input: "\"O'Hara's Ale\""881 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]882- 882+883 - title: Conditionals and Comparisons884 entries:885 - title: `==`, `!=`886 body: |3 unmodified lines890 '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- 894+895 != is "not equal", and 'a != b' returns the opposite value of 'a == b'896 897 examples:898 - program: '.[] == 1'4 unmodified lines903 904 `if A then B else C end` will act the same as `B` if `A`905 produces a value other than false or null, but act the same906 as `C` otherwise.907- 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- 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- 919+920 More cases can be added to an if using `elif A then B` syntax.921 922 examples:923 - program: |-5 unmodified lines929 "many"930 end931 input: 2932 output: ['"many"']933- 933+934 - title: `>, >=, <=, <`935 body: |936- 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).18 unmodified lines959 `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- 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- 970+971 examples:972 - program: '42 and "a string"'973 input: 'null'974 output: ['true']29 unmodified lines1004 output: [19]1005 - program: '.foo // 42'1006 input: '{}'1007 output: [42]1008- 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.16 unmodified lines1029 1030 entries:1031 - title: Variables1032 body: |1033- 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- 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- 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- 1053+1054 length as $array_length | add / $array_length1055- 1055+1056 We'll need a more complicated problem to find a situation where using1057 variables actually makes our lives easier.1058- 1059- 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- 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- 1068+1069 We want to produce the posts with the author field containing a real1070 name, as in:1071- 1071+1072 {"title": "Frist psot", "author": "Anonymous Coward"}1073 {"title": "A well-written article", "author": "Person McPherson"}1074- 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- 1077+1078 .realnames as $names | .posts[] | {title, author: $names[.author]}1079- 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 1082+ with `$x` set to that value. Thus `as` functions as something of a1083 foreach loop.1084 1085 Variables are scoped over the rest of the expression that defines1086- them, so 1087- 1086+ them, so1087+1088 .realnames as $names | (.posts[] | {title, author: $names[.author]})1089- 1090- will work, but 1091- 1089+1090+ will work, but1091+1092 (.realnames as $names | .posts[]) | {title, author: $names[.author]}1093- 1093+1094 won't.1095 1096 examples:1097 - program: '.bar as $x | .foo | . + $x'1 unmodified line1099 output: ['210']1100 1101 - title: 'Defining Functions'1102 body: |1103- 1103+1104 You can give a filter a name using "def" syntax:1105 1106 def increment: . + 1;1107- 1107+1108 From then on, `increment` is usable as a filter just like a1109 builtin function (in fact, this is how some of the builtins1110 are defined). A function may take arguments:1111 22 unmodified lines1134 output: ['[[1,2,1,2], [10,20,1,2]]']1135 1136 - title: Reduce1137 body: |1138- 1138+1139 The `reduce` syntax in jq allows you to combine all of the1140 results of an expression by accumulating them into a single1141 answer. As an example, we'll pass `[3,2,1]` to this expression:1142 1143 reduce .[] as $item (0; . + $item)1144- 1144+1145 For each result that `.[]` produces, `. + $item` is run to1146 accumulate a running total, starting from 0. In this1147 example, `.[]` produces the results 3, 2, and 1, so the1148 effect is similar to running something like this:1149 1150- 0 | (3 as $item | . + $item) | 1150+ 0 | (3 as $item | . + $item) |1151 (2 as $item | . + $item) |1152 (1 as $item | . + $item)1153 1154 examples:1155 - program: 'reduce .[] as $item (0; . + $item)'1156 input: '[10,2,5,3]'1157 output: ['20']1158- 1158 1159+1160 - title: Assignment1161 body: |1162 1163 Assignment works a little differently in jq than in most12 unmodified lines1176 1177 entries:1178 - title: "`=`"1179 body: |1180- 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- 1185+1186 .foo = .bar | .foo.baz = 11187- 1187+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- 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.4 unmodified lines1205 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- 1209+1210 This example should show the difference between '=' and '|=':1211- 1211+1212 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:1213- 1213+1214 .a = .b1215 .a |= .b1216- 1216+1217 The former will set the "a" field of the input to the "b" field of the1218 input, and produce the output {"a": 20}. The latter will set the "a"1219 field of the input to the "a" field's "b" field, producing {"a": 10}.1220 6 unmodified lines1227 examples:1228 - program: .foo += 11229 input: '{"foo": 42}'1230 output: ['{"foo": 43}']1231- 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- 1238+1239 .posts[0].title = "JQ Manual"1240- 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- 1244+1245 .posts[].comments |= . + ["this is great"]1246- 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- 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- 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- 1262+1263 .posts[] | select(.author == "stedolan")1264- 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- 1268+1269 (.posts[] | select(.author == "stedolan") | .comments) |=1270 . + ["terrible."]modified:docs/content/3.manual/v1.4/manual.yml+148 added-148 removed
14 unmodified lines15 16 Filters can be combined in various ways - you can pipe the output of17 one filter into another filter, or collect the output of a filter18 into an array.19- 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 iteration25 unmodified lines49 50 By default, `jq` reads a stream of JSON objects (whitespace51 separated) from `stdin`. One or more <files> may be specified, in52 which case `jq` will read input from those instead.53- 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.9 unmodified lines67 68 ## AUTHOR69 70 Stephen Dolan `<mu@netsoc.tcd.ie>`71- 71+72 sections:73 - title: Invoking jq74 body: |75- 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 a17 unmodified lines97 98 Output the jq version and exit with zero.99 100 * `--slurp`/`-s`:101- 101+102 Instead of running the filter for each JSON object in the103 input, read the entire input stream into a large array and run104 the filter just once.105 106 * `--online-input`/`-I`:107- 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- 111+112 * `--raw-input`/`-R`:113- 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- 118+119 * `--null-input`/`-n`:120- 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- 124+125 * `--compact-output` / `-c`:126- 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- 130+131 * `--colour-output` / `-C` and `--monochrome-output` / `-M`:132- 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- 136+137 * `--ascii-output` / `-a`:138- 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 the5 unmodified lines148 you're piping a slow data source into jq and piping jq's149 output elsewhere).150 151 * `--sort-keys` / `-S`:152- 152+153 Output the fields of each object with the keys in sorted order.154 155 * `--raw-output` / `-r`:156- 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.29 unmodified lines190 - title: Basic filters191 entries:192 - title: "`.`"193 body: |194- 194+195 The absolute simplest (and least interesting) filter196 is `.`. This is a filter that takes its input and197 produces it unchanged as output.198 7 unmodified lines206 output: ['"Hello, world!"']207 208 - title: "`.foo`, `.foo.bar`"209 body: |210- 210+211 The simplest *useful* filter is `.foo`. When given a212 JSON object (aka dictionary or hash) as input, it produces213 the value at the key "foo", or null if there's none present.214 215 If the key contains special characters, you need to surround216 it with double quotes like this: `."foo$"`.217 218 A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.219- 219+220 examples:221 - program: '.foo'222 input: '{"foo": 42, "bar": "less interesting data"}'223 output: [42]5 unmodified lines229 output: [42]230 231 - title: "`.foo?`"232 body: |233- 233+234 Just like `.foo`, but does not output even an error when `.`235 is not an array or an object.236 237 examples:11 unmodified lines249 output: ['[]']250 251 - title: "`.[<string>]`, `.[2]`, `.[10:15]`"252 body: |253- 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]`26 unmodified lines284 285 - program: '.[2:4]'286 input: '"abcdefghi"'287 output: ['"cd"']288- 288+289 - program: '.[:3]'290 input: '["a","b","c","d","e"]'291 output: ['["a", "b", "c"]']292 2 unmodified lines295 output: ['["d", "e"]']296 297 - title: "`.[]`"298 body: |299- 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 single18 unmodified lines322 output: ['1', '1']323 324 - title: "`.[]?`"325 body: |326- 326+327 Like `.[]`, but no errors will be output if . is not an array328 or object.329 330 - title: "`,`"331 body: |332- 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 the6 unmodified lines343 output: ['42', '"something else"']344 345 - program: ".user, .projects[]"346 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'347- output: ['"stedolan"', '"jq"', '"wikiflow"'] 348- 347+ output: ['"stedolan"', '"jq"', '"wikiflow"']348+349 - program: '.[4,2]'350 input: '["a","b","c","d","e"]'351 output: ['"e"', '"c"']352- 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. 358+ that.359 360 If the one on the left produces multiple results, the one on361 the right will be run for each of those results. So, the362 expression `.[] | .foo` retrieves the "foo" field of each5 unmodified lines368 output: ['"JSON"', '"XML"']369 370 - title: Types and Values371 body: |372- 372+373 jq supports the same set of datatypes as JSON - numbers,374 strings, booleans, arrays, objects (which in JSON-speak are375 hashes with only string keys), and "null".376 5 unmodified lines382 383 entries:384 - title: Array construction - `[]`385 body: |386- 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- 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 (which11 unmodified lines410 body: |411 412 Like JSON, `{}` is for constructing objects (aka413 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.414- 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- 421+422 {foo: .bar}423- 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- 429+430 {user: .user, title: .title}431- 431+432 Because that's so common, there's a shortcut syntax: `{user, title}`.433- 433+434 If one of the expressions produces multiple results,435 multiple dictionaries will be produced. If the input's436- 436+437 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}438- 438+439 then the expression440- 440+441 {user, title: .titles[]}442- 443- will produce two outputs: 444- 442+443+ will produce two outputs:444+445 {"user":"stedolan", "title": "JQ Primer"}446 {"user":"stedolan", "title": "More JQ"}447- 447+448 Putting parentheses around the key means it will be evaluated as an449 expression. With the same input as above,450- 450+451 {(.user): .titles}452- 452+453 produces454- 454+455 {"stedolan": ["JQ Primer", "More JQ"]}456- 456+457 examples:458 - program: '{user, title: .titles[]}'459 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'460 output:10 unmodified lines471 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- 475+476 entries:477 - title: Addition - `+`478 body: |479 5 unmodified lines485 486 - **Arrays** are added by being concatenated into a larger array.487 488 - **Strings** are added by being joined into a larger string.489- 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- 495+496 `null` can be added to any value, and returns the other497 value unchanged.498 499 examples:77 unmodified lines577 output: [2, 6, 1, 0]578 579 - title: "`keys`"580 body: |581- 581+582 The builtin function `keys`, when given an object, returns583 its keys in an array.584 585 The keys are sorted "alphabetically", by unicode codepoint14 unmodified lines600 output: ['[0,1,2]']601 602 - title: "`has`"603 body: |604- 604+605 The builtin function `has` returns whether the input object606 has the given key, or the input array has an element at the607 given index.608 10 unmodified lines619 output: ['[false, true]']620 621 - title: "`del`"622 body: |623- 623+624 The builtin function `del` removes a key and its corresponding625 value from an object.626- 626+627 examples:628 - program: 'del(.foo)'629 input: '[{"foo": 42, "bar": 9001, "baz": 42}]'630 output: ['{"bar": 9001, "baz": 42}']2 unmodified lines633 output: ['["foo"]']634 635 - title: "`to_entries`, `from_entries`, `with_entries`"636 body: |637- 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}`. 641+ includes `{"key": k, "value": v}`.642 643 `from_entries` does the opposite conversion, and644 `with_entries(foo)` is a shorthand for `to_entries |645 map(foo) | from_entries`, useful for doing some operation to12 unmodified lines658 659 660 - title: "`select`"661 body: |662- 662+663 The function `select(foo)` produces its input unchanged if664 `foo` returns true for that input, and produces no output665 otherwise.666 7 unmodified lines674 675 676 - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `strings`, `nulls`, `values`, `scalars`"677 body: |678- 678+679 These built-ins select only inputs that are arrays, objects,680 iterables (arrays or objects), booleans, numbers, strings,681 null, non-null values, and non-iterables, respectively.682 3 unmodified lines686 output: ['1']687 688 - title: "`empty`"689 body: |690- 690+691 `empty` returns no results. None at all. Not even `null`.692 693 It's useful on occasion. You'll know if you need it :)694 25 unmodified lines720 721 Outputs the paths to all the elements in its input (except it722 does not output the empty list, representing . itself).723 724- `paths` is equivalent to 724+ `paths` is equivalent to725 726 def paths: path(recurse(if (type|. == "array" or . == "object") then .[] else empty end))|select(length > 0);727 728 examples:35 unmodified lines764 output: ["null"]765 766 - title: "`any`"767 body: |768- 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- 772+773 If the input is an empty array, `any` returns `false`.774- 774+775 examples:776 - program: any777 input: '[true, false]'778 output: ["true"]5 unmodified lines784 output: ["false"]785 786 - title: "`all`"787 body: |788- 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- 792+793 If the input is an empty array, `all` returns `true`.794- 794+795 examples:796 - program: all797 input: '[true, false]'798 output: ["false"]5 unmodified lines804 output: ["true"]805 806 - title: "`range`"807 body: |808- 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 811+ are produced as separate outputs. Use `[range(4;10)]` to get a range as812 an array.813 814 examples:815 - program: 'range(2;4)'1 unmodified line817 output: ['2', '3']818 - program: '[range(2;4)]'819 input: 'null'820 output: ['[2,3]']821- 821+822 - title: "`floor`"823 body: |824 825 The `floor` function returns the floor of its numeric input.1 unmodified line827 examples:828 - program: 'floor'829 input: '3.14159'830 output: ['3']831- 831+832 - title: "`sqrt`"833 body: |834 835 The `sqrt` function returns the square root of its numeric input.1 unmodified line837 examples:838 - program: 'sqrt'839 input: '9'840 output: ['3']841- 841+842 - title: "`tonumber`"843 body: |844 845 The `tonumber` function parses its input as a number. It18 unmodified lines864 output: ['"1"', '"1"', '"[1]"']865 866 - title: "`type`"867 body: |868- 868+869 The `type` function returns the type of its argument as a870 string, which is one of null, boolean, number, string, array871 or object.872 3 unmodified lines876 output: ['["number", "boolean", "array", "object", "null", "string"]']877 878 - title: "`sort, sort_by`"879 body: |880- 880+881 The `sort` functions sorts its input, which must be an882 array. Values are sorted in the following order:883 884 * `null`23 unmodified lines908 output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']909 910 - title: "`group_by`"911 body: |912- 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.8 unmodified lines925 output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']926 927 - title: "`min`, `max`, `min_by`, `max_by`"928 body: |929- 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.7 unmodified lines941 output: ['{"foo":2, "bar":3}']942 943 - title: "`unique`"944 body: |945- 945+946 The `unique` function takes as input an array and produces947 an array of the same elements, in sorted order, with948 duplicates removed.949 3 unmodified lines953 output: ['[1,2,3,5]']954 955 - title: "`unique_by`"956 body: |957- 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- 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}]']3 unmodified lines971 972 973 - title: "`reverse`"974 body: |975- 975+976 This function reverses an array.977 978 examples:979 - program: 'reverse'136 unmodified lines1116 output: ['["a","b,c,d","e"]']1117 1118 - title: "`join`"1119 body: |1120- 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- 1125+1126 examples:1127 - program: 'join(", ")'1128 input: '["a","b,c,d","e"]'1129 output: ['"a, b,c,d, e"']1130 1131 1132 - title: "`recurse`"1133 body: |1134- 1134+1135 The `recurse` function allows you to search through a1136 recursive structure, and extract interesting data from all1137 levels. Suppose your input represents a filesystem:1138 3 unmodified lines1142 {"name": "/bin/sh", "children": []}]},1143 {"name": "/home", "children": [1144 {"name": "/home/stephen", "children": [1145 {"name": "/home/stephen/jq", "children": []}]}]}]}1146- 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:2 unmodified lines1153 1154 examples:1155 - program: 'recurse(.foo[])'1156 input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'1157- output: 1157+ output:1158 - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'1159 - '{"foo":[]}'1160 - '{"foo":[{"foo":[]}]}'1161 - '{"foo":[]}'1162 1163 - title: "`recurse_down`"1164 body: |1165- 1165+1166 A quieter version of `recurse(.[])`, equivalent to:1167 1168 def recurse_down: recurse(.[]?);1169 1170 - title: "`..`"1171 body: |1172- 1172+1173 Short-hand for `recurse_down`. This is intended to resemble1174 the XPath `//` operator. Note that `..a` does not work; use1175 `..|a` instead.1176 12 unmodified lines1189 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- 1193+1194 - title: "Convert to/from JSON"1195 body: |1196 1197 The `tojson` and `fromjson` builtins dump values as JSON texts39 unmodified lines1237 Applies percent-encoding, by mapping all reserved URI1238 characters to a `%xx` sequence.1239 1240 * `@csv`:1241- 1241+1242 The input must be an array, and it is rendered as CSV1243 with double quotes for strings, and quotes escaped by1244 repetition.1245 1246 * `@sh`:1247- 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- 1251+1252 * `@base64`:1253 1254 The input is converted to base64 as specified by RFC 4648.1255 24 unmodified lines1280 1281 - program: '@sh "echo \(.)"'1282 input: "\"O'Hara's Ale\""1283 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]1284- 1284+1285 - title: Conditionals and Comparisons1286 entries:1287 - title: "`==`, `!=`"1288 body: |3 unmodified lines1292 '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- 1296+1297 != is "not equal", and 'a != b' returns the opposite value of 'a == b'1298 1299 examples:1300 - program: '.[] == 1'4 unmodified lines1305 1306 `if A then B else C end` will act the same as `B` if `A`1307 produces a value other than false or null, but act the same1308 as `C` otherwise.1309- 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- 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- 1321+1322 More cases can be added to an if using `elif A then B` syntax.1323 1324 examples:1325 - program: |-5 unmodified lines1331 "many"1332 end1333 input: 21334 output: ['"many"']1335- 1335+1336 - title: "`>, >=, <=, <`"1337 body: |1338- 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).18 unmodified lines1361 `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- 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- 1372+1373 examples:1374 - program: '42 and "a string"'1375 input: 'null'1376 output: ['true']29 unmodified lines1406 output: [19]1407 - program: '.foo // 42'1408 input: '{}'1409 output: [42]1410- 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.16 unmodified lines1431 1432 entries:1433 - title: Variables1434 body: |1435- 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- 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- 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- 1455+1456 length as $array_length | add / $array_length1457- 1457+1458 We'll need a more complicated problem to find a situation where using1459 variables actually makes our lives easier.1460- 1461- 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- 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- 1470+1471 We want to produce the posts with the author field containing a real1472 name, as in:1473- 1473+1474 {"title": "Frist psot", "author": "Anonymous Coward"}1475 {"title": "A well-written article", "author": "Person McPherson"}1476- 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- 1479+1480 .realnames as $names | .posts[] | {title, author: $names[.author]}1481- 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 1484+ with `$x` set to that value. Thus `as` functions as something of a1485 foreach loop.1486 1487 Variables are scoped over the rest of the expression that defines1488- them, so 1489- 1488+ them, so1489+1490 .realnames as $names | (.posts[] | {title, author: $names[.author]})1491- 1492- will work, but 1493- 1491+1492+ will work, but1493+1494 (.realnames as $names | .posts[]) | {title, author: $names[.author]}1495- 1495+1496 won't.1497 1498 examples:1499 - program: '.bar as $x | .foo | . + $x'1 unmodified line1501 output: ['210']1502 1503 - title: 'Defining Functions'1504 body: |1505- 1505+1506 You can give a filter a name using "def" syntax:1507 1508 def increment: . + 1;1509- 1509+1510 From then on, `increment` is usable as a filter just like a1511 builtin function (in fact, this is how some of the builtins1512 are defined). A function may take arguments:1513 22 unmodified lines1536 output: ['[[1,2,1,2], [10,20,1,2]]']1537 1538 - title: Reduce1539 body: |1540- 1540+1541 The `reduce` syntax in jq allows you to combine all of the1542 results of an expression by accumulating them into a single1543 answer. As an example, we'll pass `[3,2,1]` to this expression:1544 1545 reduce .[] as $item (0; . + $item)1546- 1546+1547 For each result that `.[]` produces, `. + $item` is run to1548 accumulate a running total, starting from 0. In this1549 example, `.[]` produces the results 3, 2, and 1, so the1550 effect is similar to running something like this:1551 1552- 0 | (3 as $item | . + $item) | 1552+ 0 | (3 as $item | . + $item) |1553 (2 as $item | . + $item) |1554 (1 as $item | . + $item)1555 1556 examples:1557 - program: 'reduce .[] as $item (0; . + $item)'1558 input: '[10,2,5,3]'1559 output: ['20']1560- 1560 1561+1562 - title: Assignment1563 body: |1564 1565 Assignment works a little differently in jq than in most12 unmodified lines1578 1579 entries:1580 - title: "`=`"1581 body: |1582- 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- 1587+1588 .foo = .bar | .foo.baz = 11589- 1589+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- 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.4 unmodified lines1607 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- 1611+1612 This example should show the difference between '=' and '|=':1613- 1613+1614 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:1615- 1615+1616 .a = .b1617 .a |= .b1618- 1618+1619 The former will set the "a" field of the input to the "b" field of the1620 input, and produce the output {"a": 20}. The latter will set the "a"1621 field of the input to the "a" field's "b" field, producing {"a": 10}.1622 6 unmodified lines1629 examples:1630 - program: .foo += 11631 input: '{"foo": 42}'1632 output: ['{"foo": 43}']1633- 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- 1640+1641 .posts[0].title = "JQ Manual"1642- 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- 1646+1647 .posts[].comments |= . + ["this is great"]1648- 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- 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- 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- 1664+1665 .posts[] | select(.author == "stedolan")1666- 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- 1670+1671 (.posts[] | select(.author == "stedolan") | .comments) |=1672 . + ["terrible."]modified:docs/content/3.manual/manual.yml+12 added-12 removed
617 unmodified lines618 Multiplying a string by a number produces the concatenation of619 that string that many times. `"x" * 0` produces **null**.620 621 Dividing a string by another splits the first using the second622- as separators. 622+ as separators.623 624 Multiplying two objects will merge them recursively: this works625 like addition but if both objects contain a value for the626 same key, and the values are objects, the two are merged with82 unmodified lines709 output: ['[false, true]']710 711 - title: "`in`"712 body: |713- 713+714 The builtin function `in` returns the input key is in the715 given object, or the input index corresponds to an element716 in the given array. It is, essentially, an inversed version717 of `has`.718- 718+719 examples:720 - program: '.[] | in({"foo": 42})'721 input: '["foo", "bar"]'722 output: ['true', 'false']723 - program: 'map(in([0,1]))'724 input: '[2, 0]'725 output: ['[false, true]']726- 726+727 - title: "`path(path_expression)`"728 body: |729 730 Outputs array representations of the given path expression136 unmodified lines867 868 For any filter `x`, `map(x)` will run that filter for each869 element of the input array, and produce the outputs a new870 array. `map(.+1)` will increment each element of an array of numbers.871- 871+872 Similarly, `map_values(x)` will run that filter for each element,873 but it will return an object when an object is passed.874- 874+875 `map(x)` is equivalent to `[.[] | x]`. In fact, this is how876 it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`.877 878 examples:879 - program: 'map(.+1)'880 input: '[1,2,3]'881 output: ['[2,3,4]']882- 882+883 - program: 'map_values(.+1)'884 input: '{"a": 1, "b": 2, "c": 3}'885 output: ['{"a": 2, "b": 3, "c": 4}']886 525 unmodified lines1412 1413 - title: "`ascii_downcase`, `ascii_upcase`"1414 body: |1415 1416- Emit a copy of the input string with its alphabetic characters (a-z and A-Z) 1416+ Emit a copy of the input string with its alphabetic characters (a-z and A-Z)1417 converted to the specified case.1418 1419 example:1420 - program: 'ascii_upcase'154 unmodified lines1575 1576 - title: "`transpose`"1577 body: |1578 1579- Transpose a possibly jagged matrix (an array of arrays). 1579+ Transpose a possibly jagged matrix (an array of arrays).1580 Rows are padded with nulls so the result is always rectangular.1581 1582 examples:1583 - program: 'transpose'1004 unmodified lines2588 to process it much more quickly.2589 2590 However, streaming isn't easy to deal with as the jq program will2591 have `[<path>, <leaf-value>]` (and a few other forms) as inputs.2592- 2592+2593 Several builtins are provided to make handling streams easier.2594 2595 The examples below use the the streamed form of `[0,[1]]`, which2596 is `[[0],0],[[1,0],1],[[1,0]],[[1]]`.244 unmodified lines2841 should be an object with keys like "homepage" and so on. At2842 this time jq only uses the "search" key/value of the metadata.2843 The metadata is also made available to users via the2844 `modulemeta` builtin.2845- 2845+2846 The "search" key in the metadata, if present, should have a2847 string or array value (array of strings); this is the search2848 path to be prefixed to the top-level search path.2849 24 unmodified lines2874 should be an object with keys like "homepage" and so on. At2875 this time jq only uses the "search" key/value of the metadata.2876 The metadata is also made available to users via the2877 `modulemeta` builtin.2878- 2878+2879 The "search" key in the metadata, if present, should have a2880 string or array value (array of strings); this is the search2881 path to be prefixed to the top-level search path.2882 23 unmodified linesmodified:docs/public/.htaccess+2 added-2 removed
10 unmodified lines11 Header append Vary User-Agent12 </IfModule>13 </IfModule>14 15-# Cache, aggressively 15+# Cache, aggressively16 <IfModule mod_expires.c>17 ExpiresActive On18 ExpiresDefault "access plus 10 days"19 4 unmodified lines24 25 # Mime-types26 AddType application/vnd.ms-fontobject .eot27 AddType font/ttf .ttf28-AddType font/otf .otf28+AddType font/otf .otfmodified:docs/default_manpage.md+2 added-2 removed
2 unmodified lines345677891011121313141516175 unmodified lines2 unmodified lines
## DESCRIPTION
`jq` can transform JSON in various ways, by selecting, iterating,reducing and otherwise mangling JSON documents. reducing and otherwise mangling JSON documents.
This version of `jq` was built without a manual, so this manpage is astub. For full documentation of the `jq` language, see:
http://stedolan.github.io/jq
## BUGS
Presumably. Report them or discuss them at:
5 unmodified linesmodified:docs/Rakefile+8 added-8 removed
17 unmodified lines18 19 def json(input)20 input.to_json21 end22- 22+23 def unique(input)24 @n = (@n || 0) + 125 input + @n.to_s26 end4 unmodified lines31 32 task :serve do33 begin34 Bonsai.log "Press Control+C to quit"35- 35+36 require 'rack'37 require 'sinatra'38 require 'watch'39 require 'launchy'40- 40+41 Bonsai.root_dir = Dir.pwd42- 43- server = fork { 42+43+ server = fork {44 app = Rack::Builder.app {45 map "/jq" do46 use Bonsai::StaticPassThrough, :root => Bonsai.root_dir + "/output", :urls => ["/"]47 end1 unmodified line49 }50 Rack::Handler.default.run(app, :Port => 5000) do51 Launchy.open("http://localhost:5000/jq/")52 end53- } 53+ }54 Watch.new("{content,templates,public}/**/*") { Bonsai::Exporter.process! }55 rescue Interrupt56 Process.kill("QUIT", server)57 Process.wait(server)37 unmodified lines95 manual = load_manual96 f.puts manual['manpage_intro']97 f.puts manual['body']98 manual['sections'].each do |section|99- 99+100 f.puts "## #{section['title'].upcase}\n"101 f.puts section['body']102 f.puts ""103 (section['entries'] || []).each do |entry|11 unmodified lines115 end116 f.puts manual['manpage_epilogue']117 f.close118 puts Ronn::Document.new(f.path).convert('roff').gsub(/<\/?code>/,"")119- end 119+ end120 end121 122 task :manpage_default => ["default_manpage.md"] do123 puts Ronn::Document.new("default_manpage.md").convert('roff').gsub(/<\/?code>/,"")22 unmodified linesmodified:docs/site.yml+1 added-1 removed
6 unmodified lines789101111121314153 unmodified lines6 unmodified linesjq_version: "1.4-2-g15c4a7f-dirty"
root: '/jq'footer: |
This website is made with [Bonsai](http://www.tinytree.info) and [Twitter Bootstrap](http://twitter.github.com/bootstrap/), themed with [Bootswatch](http://bootswatch.com).
3 unmodified linesmodified:scripts/crosscompile+1 added-1 removed
1 #!/bin/sh2 3-# This script is used to cross-compile binaries for 3+# This script is used to cross-compile binaries for4 # platforms other than the current one5 6 # Usage: $0 <platformname> <configure options>7 # <platformname> is arbitrary, it is the name35 unmodified linesmodified:scripts/gen_utf8_tables.py+2 added-2 removed
8 unmodified lines9 print("static const %s %s[] =" % (type, name))10 first = True11 for i in range(0,len(t),16):12 print ((" {" if i == 0 else " ") +13- ", ".join("0x%02x"%n for n in t[i:i+16]) + 13+ ", ".join("0x%02x"%n for n in t[i:i+16]) +14 ("," if i + 16 < len(t) else "};"))15 16 17 def utf8info(c):3 unmodified lines21 if 0xC2 <= c <= 0xDF: return 2, mask(5)22 if 0xE0 <= c <= 0xEF: return 3, mask(4)23 if 0xF0 <= c <= 0xF4: return 4, mask(3)24 if 0xF4 <= c <= 0xFF: return 0, 025- 25+26 table = lambda i: [utf8info(c)[i] for c in range(256)]27 28 print("#define UTF8_CONTINUATION_BYTE ((unsigned char)255)")29 3 unmodified linesmodified:AUTHORS+1 added-1 removed
16 unmodified lines17 Filippo Valsorda <filippo.valsorda@gmail.com> - recursive object merge (`*`)18 Jack Pearkes <jackpearkes@gmail.com> - update tutorial19 Jingwen Owen Ou <jingweno@gmail.com> - jqplay.org and link to it20 Joe Littlejohn <joe.littlejohn@nokia.com> - bug fixes21-Juan Guerrero <juan.guerrero.lozano@gmail.com> - bug fixes 21+Juan Guerrero <juan.guerrero.lozano@gmail.com> - bug fixes22 Kenny Shen <kenny.shen@zalora.com> - doc fixes23 Lee Thompson <stagr.lee@gmail.com> - autoconf stuff24 Markus Lanthaler <mark_lanthaler@gmx.net> - doc fixes25 Michael Daines <michael@mdaines.com> - add sqrt; doc fixes48 unmodified linesmodified:configure.ac+1 added-1 removed
198 unmodified lines199 AC_LINK_IFELSE([AC_LANG_SOURCE([200 static __thread int x ;201 int main () { x = 123; return x; }202 ])], have___thread=yes)203-if test $have___thread = yes; then 203+if test $have___thread = yes; then204 AC_DEFINE([HAVE___THREAD],1,[Define to 1 if the system supports __thread])205 fi206 AC_MSG_RESULT($have___thread)207 14 unmodified linesmodified:COPYING+2 added-2 removed
28 unmodified lines29 30 The documentation website includes a copy of Twitter's Boostrap and31 relies on Bonsai, Liquid templates and various other projects, look32 them up for detailed licensing conditions.33- 33 35- 34+35+36 jq incorporates David M. Gay's dtoa.c and g_fmt.c, which bear the37 following notices:38 39 dtoa.c:31 unmodified linesmodified:lexer.c+3 added-3 removed
1132 unmodified lines1133 YY_BREAK1134 case 38:1135 YY_RULE_SETUP1136 #line 88 "lexer.l"1137-{ 1138- yylval->literal = jv_parse_sized(yytext, yyleng); return LITERAL; 1137+{1138+ yylval->literal = jv_parse_sized(yytext, yyleng); return LITERAL;1139 }1140 YY_BREAK1141 case 39:1142 YY_RULE_SETUP1255 unmodified lines2398 case IN_BRACKET: match = ret = ']'; break;2399 case IN_BRACE: match = ret = '}'; break;2400 2401 case IN_QQINTERP:2402- match = ')'; 2402+ match = ')';2403 ret = QQSTRING_INTERP_END;2404 break;2405 2406 default:36 unmodified linesmodified:lexer.l+4 added-4 removed
83 unmodified lines84 "@"[a-zA-Z0-9_]+ {85 yylval->literal = jv_string_sized(yytext + 1, yyleng - 1); return FORMAT;86 }87 88-[0-9.]+([eE][+-]?[0-9]+)? { 89- yylval->literal = jv_parse_sized(yytext, yyleng); return LITERAL; 88+[0-9.]+([eE][+-]?[0-9]+)? {89+ yylval->literal = jv_parse_sized(yytext, yyleng); return LITERAL;90 }91 92 "\"" {93 yy_push_state(IN_QQSTRING, yyscanner);22 unmodified lines116 . {117 return INVALID_CHARACTER;118 }119 }120- 120 121+122 ([a-zA-Z_][a-zA-Z_0-9]*::)*[a-zA-Z_][a-zA-Z_0-9]* { yylval->literal = jv_string(yytext); return IDENT;}123 \.[a-zA-Z_][a-zA-Z_0-9]* { yylval->literal = jv_string(yytext+1); return FIELD;}124 125 [ \n\t]+ {}15 unmodified lines141 case IN_BRACKET: match = ret = ']'; break;142 case IN_BRACE: match = ret = '}'; break;143 144 case IN_QQINTERP:145- match = ')'; 145+ match = ')';146 ret = QQSTRING_INTERP_END;147 break;148 149 default:35 unmodified linesmodified:Makefile.am+4 added-4 removed
24 unmodified lines25 lexer.c: lexer.l26 $(AM_V_LEX) flex -o lexer.c --header-file=lexer.h $<27 lexer.h: lexer.c28 else29-BUILT_SOURCES = 29+BUILT_SOURCES =30 .y.c:31 $(AM_V_YACC) echo "NOT building parser.c!"32 .l.c:33 $(AM_V_LEX) echo "NOT building lexer.c!"111 unmodified lines145 docs/Gemfile docs/Gemfile.lock docs/Rakefile docs/README.md \146 docs/default_manpage.md jq.1.default147 148 # setup is only used by distribution developers, not package developers.149-# Still, as a matter of allowing patching, its not a bad idea to distribute 149+# Still, as a matter of allowing patching, its not a bad idea to distribute150 # the developer setup script in the tarball.151 EXTRA_DIST = $(man_MANS) $(TESTS) $(TEST_LOG_COMPILER) jq.spec \152 $(DOC_FILES) scripts/version parser.h parser.c lexer.h \153 lexer.c tests/onig.supp tests/torture/input0.json \9 unmodified lines163 tests/modules/test_bind_order2.jq \164 jq.1.prebuilt165 166 167-# README.md is expected in Github projects, good stuff in it, so we'll 167+# README.md is expected in Github projects, good stuff in it, so we'll168 # distribute it and install it with the package in the doc directory.169 docdir = ${datadir}/doc/${PACKAGE}170 dist_doc_DATA = README.md COPYING AUTHORS README171 14 unmodified lines186 # 'make clean' doesn't delete the manpage if it can't be rebuilt187 clean-local-docs:188 if ENABLE_DOCS189 rm -f jq.1190-endif 190+endif191 192 clean-local-gcov:193 rm -f *.gcno *.gcda *.gcov194 4 unmodified lines