Skip to content
Myr

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

16 files+319 added−319 removed

modified:docs/content/2.download/default.yml+2 added-2 removed
modified:docs/content/3.manual/v1.3/manual.yml+126 added-126 removed
14 unmodified lines
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 1920 Some filters produce multiple results, for instance there's one that21 produces all the elements of its input array. Piping that filter22 into a second runs the second filter for each element of the23 array. Generally, things that would be done with loops and iteration
25 unmodified lines
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 5354 The <options> are described in the [INVOKING JQ] section, they55 mostly concern input and output formatting. The <filter> is written56 in the jq language and specifies how to transform the input57 document.
9 unmodified lines
6768 ## AUTHOR6970 Stephen Dolan `<mu@netsoc.tcd.ie>`71 7172sections:73 - title: Invoking jq74 body: |75 7576 jq filters run on a stream of JSON data. The input to jq is77 parsed as a sequence of whitespace-separated JSON values which78 are passed through the provided filter one at a time. The79 output(s) of the filter are written to standard out, again as a
2 unmodified lines
82 You can affect how jq reads and writes its input and output83 using some command-line options:8485 * `--slurp`/`-s`:86 8687 Instead of running the filter for each JSON object in the88 input, read the entire input stream into a large array and run89 the filter just once.90 9091 * `--raw-input`/`-R`:92 9293 Don't parse the input as JSON. Instead, each line of text is94 passed to the filter as a string. If combined with `--slurp`,95 then the entire input is passed to the filter as a single long96 string.97 9798 * `--null-input`/`-n`:99 99100 Don't read any input at all! Instead, the filter is run once101 using `null` as the input. This is useful when using jq as a102 simple calculator or to construct JSON data from scratch.103 103104 * `--compact-output` / `-c`:105 105106 By default, jq pretty-prints JSON output. Using this option107 will result in more compact output by instead putting each108 JSON object on a single line.109 109110 * `--colour-output` / `-C` and `--monochrome-output` / `-M`:111 111112 By default, jq outputs colored JSON if writing to a113 terminal. You can force it to produce color even if writing to114 a pipe or a file using `-C`, and disable color with `-M`.115 115116 * `--ascii-output` / `-a`:117 117118 jq usually outputs non-ASCII Unicode codepoints as UTF-8, even119 if the input specified them as escape sequences (like120 "\u03bc"). Using this option, you can force jq to produce pure121 ASCII output with every non-ASCII character replaced with the122 equivalent escape sequence.123 123124 * `--raw-output` / `-r`:125 125126 With this option, if the filter's result is a string then it127 will be written directly to standard output rather than being128 formatted as a JSON string with quotes. This can be useful for129 making jq filters talk to non-JSON-based systems.
7 unmodified lines
137 - title: Basic filters138 entries:139 - title: "`.`"140 body: |141 141142 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 lines
153 output: ['"Hello, world!"']154155 - title: "`.foo`"156 body: |157 157158 The simplest *useful* filter is .foo. When given a159 JSON object (aka dictionary or hash) as input, it produces160 the value at the key "foo", or null if there's none present.161
6 unmodified lines
168 output: ['null']169170 - title: "`.[foo]`, `.[2]`, `.[10:15]`"171 body: |172 172173 You can also look up fields of an object using syntax like174 `.["foo"]` (.foo above is a shorthand version of this). This175 one works for arrays as well, if the key is an176 integer. Arrays are zero-based (like javascript), so `.[2]`
17 unmodified lines
194195 - program: '.[2:4]'196 input: '["a","b","c","d","e"]'197 output: ['["c", "d"]']198 198199 - program: '.[:3]'200 input: '["a","b","c","d","e"]'201 output: ['["a", "b", "c"]']202
2 unmodified lines
205 output: ['["d", "e"]']206207 - title: "`.[]`"208 body: |209 209210 If you use the `.[foo]` syntax, but omit the index211 entirely, it will return *all* of the elements of an212 array. Running `.[]` with the input `[1,2,3]` will produce the213 numbers as three separate results, rather than as a single
18 unmodified lines
232 output: ['1', '1']233234 - title: "`,`"235 body: |236 236237 If two filters are separated by a comma, then the238 input will be fed into both and there will be multiple239 outputs: first, all of the outputs produced by the left240 expression, and then all of the outputs produced by the
6 unmodified lines
247 output: ['42', '"something else"']248249 - program: ".user, .projects[]"250 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'251 output: ['"stedolan"', '"jq"', '"wikiflow"'] 252 251 output: ['"stedolan"', '"jq"', '"wikiflow"']252253 - program: '.[4,2]'254 input: '["a","b","c","d","e"]'255 output: ['"e"', '"c"']256 256257 - title: "`|`"258 body: |259 The | operator combines two filters by feeding the output(s) of260 the one on the left into the input of the one on the right. It's261 pretty much the same as the Unix shell's pipe, if you're used to262 that. 262 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 each
5 unmodified lines
272 output: ['"JSON"', '"XML"']273274 - title: Types and Values275 body: |276 276277 jq supports the same set of datatypes as JSON - numbers,278 strings, booleans, arrays, objects (which in JSON-speak are279 hashes with only string keys), and "null".280
5 unmodified lines
286287 entries:288 - title: Array construction - `[]`289 body: |290 290291 As in JSON, `[]` is used to construct arrays, as in292 `[1,2,3]`. The elements of the arrays can be any jq293 expression. All of the results produced by all of the294 expressions are collected into one big array. You can use it295 to construct an array out of a known quantity of values (as296 in `[.foo, .bar, .baz]`) or to "collect" all the results of a297 filter into an array (as in `[.items[].name]`)298 298299 Once you understand the "," operator, you can look at jq's array300 syntax in a different light: the expression `[1,2,3]` is not using a301 built-in syntax for comma-separated arrays, but is instead applying302 the `[]` operator (collect results) to the expression 1,2,3 (which
11 unmodified lines
314 body: |315316 Like JSON, `{}` is for constructing objects (aka317 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.318 318319 If the keys are "sensible" (all alphabetic characters), then320 the quotes can be left off. The value can be any expression321 (although you may need to wrap it in parentheses if it's a322 complicated one), which gets applied to the {} expression's323 input (remember, all filters have an input and an324 output).325 325326 {foo: .bar}327 327328 will produce the JSON object `{"foo": 42}` if given the JSON329 object `{"bar":42, "baz":43}`. You can use this to select330 particular fields of an object: if the input is an object331 with "user", "title", "id", and "content" fields and you332 just want "user" and "title", you can write333 333334 {user: .user, title: .title}335 335336 Because that's so common, there's a shortcut syntax: `{user, title}`.337 337338 If one of the expressions produces multiple results,339 multiple dictionaries will be produced. If the input's340 340341 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}342 342343 then the expression344 344345 {user, title: .titles[]}346 347 will produce two outputs: 348 346347 will produce two outputs:348349 {"user":"stedolan", "title": "JQ Primer"}350 {"user":"stedolan", "title": "More JQ"}351 351352 Putting parentheses around the key means it will be evaluated as an353 expression. With the same input as above,354 354355 {(.user): .titles}356 356357 produces358 358359 {"stedolan": ["JQ Primer", "More JQ"]}360 360361 examples:362 - program: '{user, title: .titles[]}'363 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'364 output:
10 unmodified lines
375 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 379380 entries:381 - title: Addition - `+`382 body: |383
5 unmodified lines
389390 - **Arrays** are added by being concatenated into a larger array.391392 - **Strings** are added by being joined into a larger string.393 393394 - **Objects** are added by merging, that is, inserting all395 the key-value pairs from both objects into a single396 combined object. If both objects contain a value for the397 same key, the object on the right of the `+` wins.398 398399 `null` can be added to any value, and returns the other400 value unchanged.401402 examples:
60 unmodified lines
463 output: [2, 6, 1, 0]464465 - title: `keys`466 body: |467 467468 The builtin function `keys`, when given an object, returns469 its keys in an array.470471 The keys are sorted "alphabetically", by unicode codepoint
14 unmodified lines
486 output: ['[0,1,2]']487488 - title: `has`489 body: |490 490491 The builtin function `has` returns whether the input object492 has the given key, or the input array has an element at the493 given index.494
10 unmodified lines
505 output: ['[false, true]']506507 - title: `to_entries`, `from_entries`, `with_entries`508 body: |509 509510 These functions convert between an object and an array of511 key-value pairs. If `to_entries` is passed an object, then512 for each `k: v` entry in the input, the output array513 includes `{"key": k, "value": v}`. 513 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 to
12 unmodified lines
530531532 - title: `select`533 body: |534 534535 The function `select(foo)` produces its input unchanged if536 `foo` returns true for that input, and produces no output537 otherwise.538
6 unmodified lines
545 output: ['[5,3,7]']546547 - title: `empty`548 body: |549 549550 `empty` returns no results. None at all. Not even `null`.551552 It's useful on occasion. You'll know if you need it :)553
43 unmodified lines
597 output: ["null"]598599 - title: `range`600 body: |601 601602 The `range` function produces a range of numbers. `range(4;10)`603 produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers604 are produced as separate outputs. Use `[range(4;10)]` to get a range as 604 are produced as separate outputs. Use `[range(4;10)]` to get a range as605 an array.606607 examples:608 - program: 'range(2;4)'
1 unmodified line
610 output: ['2', '3']611 - program: '[range(2;4)]'612 input: 'null'613 output: ['[2,3]']614 614615 - title: `tonumber`616 body: |617618 The `tonumber` function parses its input as a number. It
18 unmodified lines
637 output: ['"1"', '"1"', '"[1]"']638639 - title: `type`640 body: |641 641642 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 lines
649 output: ['["number", "boolean", "array", "object", "null", "string"]']650651 - title: `sort, sort_by`652 body: |653 653654 The `sort` functions sorts its input, which must be an655 array. Values are sorted in the following order:656657 * `null`
23 unmodified lines
681 output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']682683 - title: `group_by`684 body: |685 685686 `group_by(.foo)` takes as input an array, groups the687 elements having the same `.foo` field into separate arrays,688 and produces all of these arrays as elements of a larger689 array, sorted by the value of the `.foo` field.
8 unmodified lines
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 702703 Find the minimum or maximum element of the input array. The704 `_by` versions allow you to specify a particular field or705 property to examine, e.g. `min_by(.foo)` finds the object706 with the smallest `foo` field.
7 unmodified lines
714 output: ['{"foo":2, "bar":3}']715716 - title: `unique`717 body: |718 718719 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 lines
726 output: ['[1,2,3,5]']727728 - title: `reverse`729 body: |730 730731 This function reverses an array.732733 examples:734 - program: 'reverse'
30 unmodified lines
765 output: ['false']766767 - title: `recurse`768 body: |769 769770 The `recurse` function allows you to search through a771 recursive structure, and extract interesting data from all772 levels. Suppose your input represents a filesystem:773
3 unmodified lines
777 {"name": "/bin/sh", "children": []}]},778 {"name": "/home", "children": [779 {"name": "/home/stephen", "children": [780 {"name": "/home/stephen/jq", "children": []}]}]}]}781 781782 Now suppose you want to extract all of the filenames783 present. You need to retrieve `.name`, `.children[].name`,784 `.children[].children[].name`, and so on. You can do this785 with:
2 unmodified lines
788789 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 lines
806 examples:807 - program: '"The input was \(.), which is one less than \(.+1)"'808 input: '42'809 output: ['"The input was 42, which is one less than 43"']810 810811 - title: "Format strings and escaping"812 body: |813814 The `@foo` syntax is used to format and escape strings,
20 unmodified lines
835 Applies percent-encoding, by mapping all reserved URI836 characters to a `%xx` sequence.837838 * `@csv`:839 839840 The input must be an array, and it is rendered as CSV841 with double quotes for strings, and quotes escaped by842 repetition.843844 * `@sh`:845 845846 The input is escaped suitable for use in a command-line847 for a POSIX shell. If the input is an array, the output848 will be a series of space-separated strings.849 849850 * `@base64`:851852 The input is converted to base64 as specified by RFC 4648.853
24 unmodified lines
878879 - program: '@sh "echo \(.)"'880 input: "\"O'Hara's Ale\""881 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]882 882883 - title: Conditionals and Comparisons884 entries:885 - title: `==`, `!=`886 body: |
3 unmodified lines
890 '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 894895 != is "not equal", and 'a != b' returns the opposite value of 'a == b'896897 examples:898 - program: '.[] == 1'
4 unmodified lines
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 907908 Checking for false or null is a simpler notion of909 "truthiness" than is found in Javascript or Python, but it910 means that you'll sometimes have to be more explicit about911 the condition you want: you can't test whether, e.g. a912 string is empty using `if .name then A else B end`, you'll913 need something more like `if (.name | count) > 0 then A else914 B end` instead.915 915916 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 919920 More cases can be added to an if using `elif A then B` syntax.921922 examples:923 - program: |-
5 unmodified lines
929 "many"930 end931 input: 2932 output: ['"many"']933 933934 - title: `>, >=, <=, <`935 body: |936 936937 The comparison operators `>`, `>=`, `<=`, `<` return whether938 their left argument is greater than, greater than or equal939 to, less than or equal to or less than their right argument940 (respectively).
18 unmodified lines
959 `not` is in fact a builtin function rather than an operator,960 so it is called as a filter to which things can be piped961 rather than with special syntax, as in `.foo and .bar |962 not`.963 963964 These three only produce the values "true" and "false", and965 so are only useful for genuine Boolean operations, rather966 than the common Perl/Python/Ruby idiom of967 "value_that_may_be_null or default". If you want to use this968 form of "or", picking between two values rather than969 evaluating a condition, see the "//" operator below.970 970971 examples:972 - program: '42 and "a string"'973 input: 'null'974 output: ['true']
29 unmodified lines
1004 output: [19]1005 - program: '.foo // 42'1006 input: '{}'1007 output: [42]1008 10081009 - title: Advanced features1010 body: |1011 Variables are an absolute necessity in most programming languages, but1012 they're relegated to an "advanced feature" in jq.
16 unmodified lines
10291030 entries:1031 - title: Variables1032 body: |1033 10331034 In jq, all filters have an input and an output, so manual1035 plumbing is not necessary to pass a value from one part of a program1036 to the next. Many expressions, for instance `a + b`, pass their input1037 to two distinct subexpressions (here `a` and `b` are both passed the1038 same input), so variables aren't usually necessary in order to use a1039 value twice.1040 10401041 For instance, calculating the average value of an array of numbers1042 requires a few variables in most languages - at least one to hold the1043 array, perhaps one for each element or for a loop counter. In jq, it's1044 simply `add / length` - the `add` expression is given the array and1045 produces its sum, and the `length` expression is given the array and1046 produces its length.1047 10471048 So, there's generally a cleaner way to solve most problems in jq that1049 defining variables. Still, sometimes they do make things easier, so jq1050 lets you define variables using `expression as $variable`. All1051 variable names start with `$`. Here's a slightly uglier version of the1052 array-averaging example:1053 10531054 length as $array_length | add / $array_length1055 10551056 We'll need a more complicated problem to find a situation where using1057 variables actually makes our lives easier.1058 1059 105810591060 Suppose we have an array of blog posts, with "author" and "title"1061 fields, and another object which is used to map author usernames to1062 real names. Our input looks like:1063 10631064 {"posts": [{"title": "Frist psot", "author": "anon"},1065 {"title": "A well-written article", "author": "person1"}],1066 "realnames": {"anon": "Anonymous Coward",1067 "person1": "Person McPherson"}}1068 10681069 We want to produce the posts with the author field containing a real1070 name, as in:1071 10711072 {"title": "Frist psot", "author": "Anonymous Coward"}1073 {"title": "A well-written article", "author": "Person McPherson"}1074 10741075 We use a variable, $names, to store the realnames object, so that we1076 can refer to it later when looking up author usernames:1077 10771078 .realnames as $names | .posts[] | {title, author: $names[.author]}1079 10791080 The expression `exp as $x | ...` means: for each value of expression1081 `exp`, run the rest of the pipeline with the entire original input, and1082 with `$x` set to that value. Thus `as` functions as something of a 1082 with `$x` set to that value. Thus `as` functions as something of a1083 foreach loop.10841085 Variables are scoped over the rest of the expression that defines1086 them, so 1087 1086 them, so10871088 .realnames as $names | (.posts[] | {title, author: $names[.author]})1089 1090 will work, but 1091 10891090 will work, but10911092 (.realnames as $names | .posts[]) | {title, author: $names[.author]}1093 10931094 won't.10951096 examples:1097 - program: '.bar as $x | .foo | . + $x'
1 unmodified line
1099 output: ['210']11001101 - title: 'Defining Functions'1102 body: |1103 11031104 You can give a filter a name using "def" syntax:11051106 def increment: . + 1;1107 11071108 From then on, `increment` is usable as a filter just like a1109 builtin function (in fact, this is how some of the builtins1110 are defined). A function may take arguments:1111
22 unmodified lines
1134 output: ['[[1,2,1,2], [10,20,1,2]]']11351136 - title: Reduce1137 body: |1138 11381139 The `reduce` syntax in jq allows you to combine all of the1140 results of an expression by accumulating them into a single1141 answer. As an example, we'll pass `[3,2,1]` to this expression:11421143 reduce .[] as $item (0; . + $item)1144 11441145 For each result that `.[]` produces, `. + $item` is run to1146 accumulate a running total, starting from 0. In this1147 example, `.[]` produces the results 3, 2, and 1, so the1148 effect is similar to running something like this:11491150 0 | (3 as $item | . + $item) | 1150 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 115811591160 - title: Assignment1161 body: |11621163 Assignment works a little differently in jq than in most
12 unmodified lines
11761177 entries:1178 - title: "`=`"1179 body: |1180 11801181 The filter `.foo = 1` will take as input an object1182 and produce as output an object with the "foo" field set to1183 1. There is no notion of "modifying" or "changing" something1184 in jq - all jq values are immutable. For instance,1185 11851186 .foo = .bar | .foo.baz = 11187 11871188 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 11961197 This means that it's impossible to build circular values in1198 jq (such as an array whose first element is itself). This is1199 quite intentional, and ensures that anything a jq program1200 can produce can be represented in JSON.
4 unmodified lines
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 12091210 This example should show the difference between '=' and '|=':1211 12111212 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:1213 12131214 .a = .b1215 .a |= .b1216 12161217 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 lines
1227 examples:1228 - program: .foo += 11229 input: '{"foo": 42}'1230 output: ['{"foo": 43}']1231 12311232 - title: Complex assignments1233 body: |1234 Lots more things are allowed on the left-hand side of a jq assignment1235 than in most langauges. We've already seen simple field accesses on1236 the left hand side, and it's no surprise that array accesses work just1237 as well:1238 12381239 .posts[0].title = "JQ Manual"1240 12401241 What may come as a surprise is that the expression on the left may1242 produce multiple results, referring to different points in the input1243 document:1244 12441245 .posts[].comments |= . + ["this is great"]1246 12461247 That example appends the string "this is great" to the "comments"1248 array of each post in the input (where the input is an object with a1249 field "posts" which is an array of posts).1250 12501251 When jq encounters an assignment like 'a = b', it records the "path"1252 taken to select a part of the input document while executing a. This1253 path is then used to find which part of the input to change while1254 executing the assignment. Any filter may be used on the1255 left-hand side of an equals - whichever paths it selects from the1256 input will be where the assignment is performed.1257 12571258 This is a very powerful operation. Suppose we wanted to add a comment1259 to blog posts, using the same "blog" input above. This time, we only1260 want to comment on the posts written by "stedolan". We can find those1261 posts using the "select" function described earlier:1262 12621263 .posts[] | select(.author == "stedolan")1264 12641265 The paths provided by this operation point to each of the posts that1266 "stedolan" wrote, and we can comment on each of them in the same way1267 that we did before:1268 12681269 (.posts[] | select(.author == "stedolan") | .comments) |=1270 . + ["terrible."]
modified:docs/content/3.manual/v1.4/manual.yml+148 added-148 removed
14 unmodified lines
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 1920 Some filters produce multiple results, for instance there's one that21 produces all the elements of its input array. Piping that filter22 into a second runs the second filter for each element of the23 array. Generally, things that would be done with loops and iteration
25 unmodified lines
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 5354 The <options> are described in the [INVOKING JQ] section, they55 mostly concern input and output formatting. The <filter> is written56 in the jq language and specifies how to transform the input57 document.
9 unmodified lines
6768 ## AUTHOR6970 Stephen Dolan `<mu@netsoc.tcd.ie>`71 7172sections:73 - title: Invoking jq74 body: |75 7576 jq filters run on a stream of JSON data. The input to jq is77 parsed as a sequence of whitespace-separated JSON values which78 are passed through the provided filter one at a time. The79 output(s) of the filter are written to standard out, again as a
17 unmodified lines
9798 Output the jq version and exit with zero.99100 * `--slurp`/`-s`:101 101102 Instead of running the filter for each JSON object in the103 input, read the entire input stream into a large array and run104 the filter just once.105106 * `--online-input`/`-I`:107 107108 When the top-level input value is an array produce its elements109 instead of the array. This allows on-line processing of110 potentially very large top-level arrays' elements.111 111112 * `--raw-input`/`-R`:113 113114 Don't parse the input as JSON. Instead, each line of text is115 passed to the filter as a string. If combined with `--slurp`,116 then the entire input is passed to the filter as a single long117 string.118 118119 * `--null-input`/`-n`:120 120121 Don't read any input at all! Instead, the filter is run once122 using `null` as the input. This is useful when using jq as a123 simple calculator or to construct JSON data from scratch.124 124125 * `--compact-output` / `-c`:126 126127 By default, jq pretty-prints JSON output. Using this option128 will result in more compact output by instead putting each129 JSON object on a single line.130 130131 * `--colour-output` / `-C` and `--monochrome-output` / `-M`:132 132133 By default, jq outputs colored JSON if writing to a134 terminal. You can force it to produce color even if writing to135 a pipe or a file using `-C`, and disable color with `-M`.136 136137 * `--ascii-output` / `-a`:138 138139 jq usually outputs non-ASCII Unicode codepoints as UTF-8, even140 if the input specified them as escape sequences (like141 "\u03bc"). Using this option, you can force jq to produce pure142 ASCII output with every non-ASCII character replaced with the
5 unmodified lines
148 you're piping a slow data source into jq and piping jq's149 output elsewhere).150151 * `--sort-keys` / `-S`:152 152153 Output the fields of each object with the keys in sorted order.154155 * `--raw-output` / `-r`:156 156157 With this option, if the filter's result is a string then it158 will be written directly to standard output rather than being159 formatted as a JSON string with quotes. This can be useful for160 making jq filters talk to non-JSON-based systems.
29 unmodified lines
190 - title: Basic filters191 entries:192 - title: "`.`"193 body: |194 194195 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 lines
206 output: ['"Hello, world!"']207208 - title: "`.foo`, `.foo.bar`"209 body: |210 210211 The simplest *useful* filter is `.foo`. When given a212 JSON object (aka dictionary or hash) as input, it produces213 the value at the key "foo", or null if there's none present.214215 If the key contains special characters, you need to surround216 it with double quotes like this: `."foo$"`.217218 A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.219 219220 examples:221 - program: '.foo'222 input: '{"foo": 42, "bar": "less interesting data"}'223 output: [42]
5 unmodified lines
229 output: [42]230231 - title: "`.foo?`"232 body: |233 233234 Just like `.foo`, but does not output even an error when `.`235 is not an array or an object.236237 examples:
11 unmodified lines
249 output: ['[]']250251 - title: "`.[<string>]`, `.[2]`, `.[10:15]`"252 body: |253 253254 You can also look up fields of an object using syntax like255 `.["foo"]` (.foo above is a shorthand version of this). This256 one works for arrays as well, if the key is an257 integer. Arrays are zero-based (like javascript), so `.[2]`
26 unmodified lines
284285 - program: '.[2:4]'286 input: '"abcdefghi"'287 output: ['"cd"']288 288289 - program: '.[:3]'290 input: '["a","b","c","d","e"]'291 output: ['["a", "b", "c"]']292
2 unmodified lines
295 output: ['["d", "e"]']296297 - title: "`.[]`"298 body: |299 299300 If you use the `.[index]` syntax, but omit the index301 entirely, it will return *all* of the elements of an302 array. Running `.[]` with the input `[1,2,3]` will produce the303 numbers as three separate results, rather than as a single
18 unmodified lines
322 output: ['1', '1']323324 - title: "`.[]?`"325 body: |326 326327 Like `.[]`, but no errors will be output if . is not an array328 or object.329330 - title: "`,`"331 body: |332 332333 If two filters are separated by a comma, then the334 input will be fed into both and there will be multiple335 outputs: first, all of the outputs produced by the left336 expression, and then all of the outputs produced by the
6 unmodified lines
343 output: ['42', '"something else"']344345 - program: ".user, .projects[]"346 input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'347 output: ['"stedolan"', '"jq"', '"wikiflow"'] 348 347 output: ['"stedolan"', '"jq"', '"wikiflow"']348349 - program: '.[4,2]'350 input: '["a","b","c","d","e"]'351 output: ['"e"', '"c"']352 352353 - title: "`|`"354 body: |355 The | operator combines two filters by feeding the output(s) of356 the one on the left into the input of the one on the right. It's357 pretty much the same as the Unix shell's pipe, if you're used to358 that. 358 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 each
5 unmodified lines
368 output: ['"JSON"', '"XML"']369370 - title: Types and Values371 body: |372 372373 jq supports the same set of datatypes as JSON - numbers,374 strings, booleans, arrays, objects (which in JSON-speak are375 hashes with only string keys), and "null".376
5 unmodified lines
382383 entries:384 - title: Array construction - `[]`385 body: |386 386387 As in JSON, `[]` is used to construct arrays, as in388 `[1,2,3]`. The elements of the arrays can be any jq389 expression. All of the results produced by all of the390 expressions are collected into one big array. You can use it391 to construct an array out of a known quantity of values (as392 in `[.foo, .bar, .baz]`) or to "collect" all the results of a393 filter into an array (as in `[.items[].name]`)394 394395 Once you understand the "," operator, you can look at jq's array396 syntax in a different light: the expression `[1,2,3]` is not using a397 built-in syntax for comma-separated arrays, but is instead applying398 the `[]` operator (collect results) to the expression 1,2,3 (which
11 unmodified lines
410 body: |411412 Like JSON, `{}` is for constructing objects (aka413 dictionaries or hashes), as in: `{"a": 42, "b": 17}`.414 414415 If the keys are "sensible" (all alphabetic characters), then416 the quotes can be left off. The value can be any expression417 (although you may need to wrap it in parentheses if it's a418 complicated one), which gets applied to the {} expression's419 input (remember, all filters have an input and an420 output).421 421422 {foo: .bar}423 423424 will produce the JSON object `{"foo": 42}` if given the JSON425 object `{"bar":42, "baz":43}`. You can use this to select426 particular fields of an object: if the input is an object427 with "user", "title", "id", and "content" fields and you428 just want "user" and "title", you can write429 429430 {user: .user, title: .title}431 431432 Because that's so common, there's a shortcut syntax: `{user, title}`.433 433434 If one of the expressions produces multiple results,435 multiple dictionaries will be produced. If the input's436 436437 {"user":"stedolan","titles":["JQ Primer", "More JQ"]}438 438439 then the expression440 440441 {user, title: .titles[]}442 443 will produce two outputs: 444 442443 will produce two outputs:444445 {"user":"stedolan", "title": "JQ Primer"}446 {"user":"stedolan", "title": "More JQ"}447 447448 Putting parentheses around the key means it will be evaluated as an449 expression. With the same input as above,450 450451 {(.user): .titles}452 452453 produces454 454455 {"stedolan": ["JQ Primer", "More JQ"]}456 456457 examples:458 - program: '{user, title: .titles[]}'459 input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'460 output:
10 unmodified lines
471 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 475476 entries:477 - title: Addition - `+`478 body: |479
5 unmodified lines
485486 - **Arrays** are added by being concatenated into a larger array.487488 - **Strings** are added by being joined into a larger string.489 489490 - **Objects** are added by merging, that is, inserting all491 the key-value pairs from both objects into a single492 combined object. If both objects contain a value for the493 same key, the object on the right of the `+` wins. (For494 recursive merge use the `*` operator.)495 495496 `null` can be added to any value, and returns the other497 value unchanged.498499 examples:
77 unmodified lines
577 output: [2, 6, 1, 0]578579 - title: "`keys`"580 body: |581 581582 The builtin function `keys`, when given an object, returns583 its keys in an array.584585 The keys are sorted "alphabetically", by unicode codepoint
14 unmodified lines
600 output: ['[0,1,2]']601602 - title: "`has`"603 body: |604 604605 The builtin function `has` returns whether the input object606 has the given key, or the input array has an element at the607 given index.608
10 unmodified lines
619 output: ['[false, true]']620621 - title: "`del`"622 body: |623 623624 The builtin function `del` removes a key and its corresponding625 value from an object.626 626627 examples:628 - program: 'del(.foo)'629 input: '[{"foo": 42, "bar": 9001, "baz": 42}]'630 output: ['{"bar": 9001, "baz": 42}']
2 unmodified lines
633 output: ['["foo"]']634635 - title: "`to_entries`, `from_entries`, `with_entries`"636 body: |637 637638 These functions convert between an object and an array of639 key-value pairs. If `to_entries` is passed an object, then640 for each `k: v` entry in the input, the output array641 includes `{"key": k, "value": v}`. 641 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 to
12 unmodified lines
658659660 - title: "`select`"661 body: |662 662663 The function `select(foo)` produces its input unchanged if664 `foo` returns true for that input, and produces no output665 otherwise.666
7 unmodified lines
674675676 - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `strings`, `nulls`, `values`, `scalars`"677 body: |678 678679 These built-ins select only inputs that are arrays, objects,680 iterables (arrays or objects), booleans, numbers, strings,681 null, non-null values, and non-iterables, respectively.682
3 unmodified lines
686 output: ['1']687688 - title: "`empty`"689 body: |690 690691 `empty` returns no results. None at all. Not even `null`.692693 It's useful on occasion. You'll know if you need it :)694
25 unmodified lines
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 724 `paths` is equivalent to725726 def paths: path(recurse(if (type|. == "array" or . == "object") then .[] else empty end))|select(length > 0);727728 examples:
35 unmodified lines
764 output: ["null"]765766 - title: "`any`"767 body: |768 768769 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 772773 If the input is an empty array, `any` returns `false`.774 774775 examples:776 - program: any777 input: '[true, false]'778 output: ["true"]
5 unmodified lines
784 output: ["false"]785786 - title: "`all`"787 body: |788 788789 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 792793 If the input is an empty array, `all` returns `true`.794 794795 examples:796 - program: all797 input: '[true, false]'798 output: ["false"]
5 unmodified lines
804 output: ["true"]805806 - title: "`range`"807 body: |808 808809 The `range` function produces a range of numbers. `range(4;10)`810 produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers811 are produced as separate outputs. Use `[range(4;10)]` to get a range as 811 are produced as separate outputs. Use `[range(4;10)]` to get a range as812 an array.813814 examples:815 - program: 'range(2;4)'
1 unmodified line
817 output: ['2', '3']818 - program: '[range(2;4)]'819 input: 'null'820 output: ['[2,3]']821 821822 - title: "`floor`"823 body: |824825 The `floor` function returns the floor of its numeric input.
1 unmodified line
827 examples:828 - program: 'floor'829 input: '3.14159'830 output: ['3']831 831832 - title: "`sqrt`"833 body: |834835 The `sqrt` function returns the square root of its numeric input.
1 unmodified line
837 examples:838 - program: 'sqrt'839 input: '9'840 output: ['3']841 841842 - title: "`tonumber`"843 body: |844845 The `tonumber` function parses its input as a number. It
18 unmodified lines
864 output: ['"1"', '"1"', '"[1]"']865866 - title: "`type`"867 body: |868 868869 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 lines
876 output: ['["number", "boolean", "array", "object", "null", "string"]']877878 - title: "`sort, sort_by`"879 body: |880 880881 The `sort` functions sorts its input, which must be an882 array. Values are sorted in the following order:883884 * `null`
23 unmodified lines
908 output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']909910 - title: "`group_by`"911 body: |912 912913 `group_by(.foo)` takes as input an array, groups the914 elements having the same `.foo` field into separate arrays,915 and produces all of these arrays as elements of a larger916 array, sorted by the value of the `.foo` field.
8 unmodified lines
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 929930 Find the minimum or maximum element of the input array. The931 `_by` versions allow you to specify a particular field or932 property to examine, e.g. `min_by(.foo)` finds the object933 with the smallest `foo` field.
7 unmodified lines
941 output: ['{"foo":2, "bar":3}']942943 - title: "`unique`"944 body: |945 945946 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 lines
953 output: ['[1,2,3,5]']954955 - title: "`unique_by`"956 body: |957 957958 The `unique_by(.foo)` function takes as input an array and produces959 an array of the same elements, in sorted order, with960 elqements with a duplicate `.foo` field removed. Think of it as making961 an array by taking one element out of every group produced by962 `group_by`.963 963964 examples:965 - program: 'unique_by(.foo)'966 input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'967 output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']
3 unmodified lines
971972973 - title: "`reverse`"974 body: |975 975976 This function reverses an array.977978 examples:979 - program: 'reverse'
136 unmodified lines
1116 output: ['["a","b,c,d","e"]']11171118 - title: "`join`"1119 body: |1120 11201121 Joins the array of elements given as input, using the1122 argument as separator. It is the inverse of `split`: that is,1123 running `split("foo") | join("foo")` over any input string1124 returns said input string.1125 11251126 examples:1127 - program: 'join(", ")'1128 input: '["a","b,c,d","e"]'1129 output: ['"a, b,c,d, e"']113011311132 - title: "`recurse`"1133 body: |1134 11341135 The `recurse` function allows you to search through a1136 recursive structure, and extract interesting data from all1137 levels. Suppose your input represents a filesystem:1138
3 unmodified lines
1142 {"name": "/bin/sh", "children": []}]},1143 {"name": "/home", "children": [1144 {"name": "/home/stephen", "children": [1145 {"name": "/home/stephen/jq", "children": []}]}]}]}1146 11461147 Now suppose you want to extract all of the filenames1148 present. You need to retrieve `.name`, `.children[].name`,1149 `.children[].children[].name`, and so on. You can do this1150 with:
2 unmodified lines
11531154 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":[]}'11621163 - title: "`recurse_down`"1164 body: |1165 11651166 A quieter version of `recurse(.[])`, equivalent to:11671168 def recurse_down: recurse(.[]?);11691170 - title: "`..`"1171 body: |1172 11721173 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 lines
1189 examples:1190 - program: '"The input was \(.), which is one less than \(.+1)"'1191 input: '42'1192 output: ['"The input was 42, which is one less than 43"']1193 11931194 - title: "Convert to/from JSON"1195 body: |11961197 The `tojson` and `fromjson` builtins dump values as JSON texts
39 unmodified lines
1237 Applies percent-encoding, by mapping all reserved URI1238 characters to a `%xx` sequence.12391240 * `@csv`:1241 12411242 The input must be an array, and it is rendered as CSV1243 with double quotes for strings, and quotes escaped by1244 repetition.12451246 * `@sh`:1247 12471248 The input is escaped suitable for use in a command-line1249 for a POSIX shell. If the input is an array, the output1250 will be a series of space-separated strings.1251 12511252 * `@base64`:12531254 The input is converted to base64 as specified by RFC 4648.1255
24 unmodified lines
12801281 - program: '@sh "echo \(.)"'1282 input: "\"O'Hara's Ale\""1283 output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]1284 12841285 - title: Conditionals and Comparisons1286 entries:1287 - title: "`==`, `!=`"1288 body: |
3 unmodified lines
1292 '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 12961297 != is "not equal", and 'a != b' returns the opposite value of 'a == b'12981299 examples:1300 - program: '.[] == 1'
4 unmodified lines
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 13091310 Checking for false or null is a simpler notion of1311 "truthiness" than is found in Javascript or Python, but it1312 means that you'll sometimes have to be more explicit about1313 the condition you want: you can't test whether, e.g. a1314 string is empty using `if .name then A else B end`, you'll1315 need something more like `if (.name | length) > 0 then A else1316 B end` instead.1317 13171318 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 13211322 More cases can be added to an if using `elif A then B` syntax.13231324 examples:1325 - program: |-
5 unmodified lines
1331 "many"1332 end1333 input: 21334 output: ['"many"']1335 13351336 - title: "`>, >=, <=, <`"1337 body: |1338 13381339 The comparison operators `>`, `>=`, `<=`, `<` return whether1340 their left argument is greater than, greater than or equal1341 to, less than or equal to or less than their right argument1342 (respectively).
18 unmodified lines
1361 `not` is in fact a builtin function rather than an operator,1362 so it is called as a filter to which things can be piped1363 rather than with special syntax, as in `.foo and .bar |1364 not`.1365 13651366 These three only produce the values "true" and "false", and1367 so are only useful for genuine Boolean operations, rather1368 than the common Perl/Python/Ruby idiom of1369 "value_that_may_be_null or default". If you want to use this1370 form of "or", picking between two values rather than1371 evaluating a condition, see the "//" operator below.1372 13721373 examples:1374 - program: '42 and "a string"'1375 input: 'null'1376 output: ['true']
29 unmodified lines
1406 output: [19]1407 - program: '.foo // 42'1408 input: '{}'1409 output: [42]1410 14101411 - title: Advanced features1412 body: |1413 Variables are an absolute necessity in most programming languages, but1414 they're relegated to an "advanced feature" in jq.
16 unmodified lines
14311432 entries:1433 - title: Variables1434 body: |1435 14351436 In jq, all filters have an input and an output, so manual1437 plumbing is not necessary to pass a value from one part of a program1438 to the next. Many expressions, for instance `a + b`, pass their input1439 to two distinct subexpressions (here `a` and `b` are both passed the1440 same input), so variables aren't usually necessary in order to use a1441 value twice.1442 14421443 For instance, calculating the average value of an array of numbers1444 requires a few variables in most languages - at least one to hold the1445 array, perhaps one for each element or for a loop counter. In jq, it's1446 simply `add / length` - the `add` expression is given the array and1447 produces its sum, and the `length` expression is given the array and1448 produces its length.1449 14491450 So, there's generally a cleaner way to solve most problems in jq than1451 defining variables. Still, sometimes they do make things easier, so jq1452 lets you define variables using `expression as $variable`. All1453 variable names start with `$`. Here's a slightly uglier version of the1454 array-averaging example:1455 14551456 length as $array_length | add / $array_length1457 14571458 We'll need a more complicated problem to find a situation where using1459 variables actually makes our lives easier.1460 1461 146014611462 Suppose we have an array of blog posts, with "author" and "title"1463 fields, and another object which is used to map author usernames to1464 real names. Our input looks like:1465 14651466 {"posts": [{"title": "Frist psot", "author": "anon"},1467 {"title": "A well-written article", "author": "person1"}],1468 "realnames": {"anon": "Anonymous Coward",1469 "person1": "Person McPherson"}}1470 14701471 We want to produce the posts with the author field containing a real1472 name, as in:1473 14731474 {"title": "Frist psot", "author": "Anonymous Coward"}1475 {"title": "A well-written article", "author": "Person McPherson"}1476 14761477 We use a variable, $names, to store the realnames object, so that we1478 can refer to it later when looking up author usernames:1479 14791480 .realnames as $names | .posts[] | {title, author: $names[.author]}1481 14811482 The expression `exp as $x | ...` means: for each value of expression1483 `exp`, run the rest of the pipeline with the entire original input, and1484 with `$x` set to that value. Thus `as` functions as something of a 1484 with `$x` set to that value. Thus `as` functions as something of a1485 foreach loop.14861487 Variables are scoped over the rest of the expression that defines1488 them, so 1489 1488 them, so14891490 .realnames as $names | (.posts[] | {title, author: $names[.author]})1491 1492 will work, but 1493 14911492 will work, but14931494 (.realnames as $names | .posts[]) | {title, author: $names[.author]}1495 14951496 won't.14971498 examples:1499 - program: '.bar as $x | .foo | . + $x'
1 unmodified line
1501 output: ['210']15021503 - title: 'Defining Functions'1504 body: |1505 15051506 You can give a filter a name using "def" syntax:15071508 def increment: . + 1;1509 15091510 From then on, `increment` is usable as a filter just like a1511 builtin function (in fact, this is how some of the builtins1512 are defined). A function may take arguments:1513
22 unmodified lines
1536 output: ['[[1,2,1,2], [10,20,1,2]]']15371538 - title: Reduce1539 body: |1540 15401541 The `reduce` syntax in jq allows you to combine all of the1542 results of an expression by accumulating them into a single1543 answer. As an example, we'll pass `[3,2,1]` to this expression:15441545 reduce .[] as $item (0; . + $item)1546 15461547 For each result that `.[]` produces, `. + $item` is run to1548 accumulate a running total, starting from 0. In this1549 example, `.[]` produces the results 3, 2, and 1, so the1550 effect is similar to running something like this:15511552 0 | (3 as $item | . + $item) | 1552 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 156015611562 - title: Assignment1563 body: |15641565 Assignment works a little differently in jq than in most
12 unmodified lines
15781579 entries:1580 - title: "`=`"1581 body: |1582 15821583 The filter `.foo = 1` will take as input an object1584 and produce as output an object with the "foo" field set to1585 1. There is no notion of "modifying" or "changing" something1586 in jq - all jq values are immutable. For instance,1587 15871588 .foo = .bar | .foo.baz = 11589 15891590 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 15981599 This means that it's impossible to build circular values in1600 jq (such as an array whose first element is itself). This is1601 quite intentional, and ensures that anything a jq program1602 can produce can be represented in JSON.
4 unmodified lines
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 16111612 This example should show the difference between '=' and '|=':1613 16131614 Provide input '{"a": {"b": 10}, "b": 20}' to the programs:1615 16151616 .a = .b1617 .a |= .b1618 16181619 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 lines
1629 examples:1630 - program: .foo += 11631 input: '{"foo": 42}'1632 output: ['{"foo": 43}']1633 16331634 - title: Complex assignments1635 body: |1636 Lots more things are allowed on the left-hand side of a jq assignment1637 than in most langauges. We've already seen simple field accesses on1638 the left hand side, and it's no surprise that array accesses work just1639 as well:1640 16401641 .posts[0].title = "JQ Manual"1642 16421643 What may come as a surprise is that the expression on the left may1644 produce multiple results, referring to different points in the input1645 document:1646 16461647 .posts[].comments |= . + ["this is great"]1648 16481649 That example appends the string "this is great" to the "comments"1650 array of each post in the input (where the input is an object with a1651 field "posts" which is an array of posts).1652 16521653 When jq encounters an assignment like 'a = b', it records the "path"1654 taken to select a part of the input document while executing a. This1655 path is then used to find which part of the input to change while1656 executing the assignment. Any filter may be used on the1657 left-hand side of an equals - whichever paths it selects from the1658 input will be where the assignment is performed.1659 16591660 This is a very powerful operation. Suppose we wanted to add a comment1661 to blog posts, using the same "blog" input above. This time, we only1662 want to comment on the posts written by "stedolan". We can find those1663 posts using the "select" function described earlier:1664 16641665 .posts[] | select(.author == "stedolan")1666 16661667 The paths provided by this operation point to each of the posts that1668 "stedolan" wrote, and we can comment on each of them in the same way1669 that we did before:1670 16701671 (.posts[] | select(.author == "stedolan") | .comments) |=1672 . + ["terrible."]
modified:docs/content/3.manual/manual.yml+12 added-12 removed
617 unmodified lines
618 Multiplying a string by a number produces the concatenation of619 that string that many times. `"x" * 0` produces **null**.620621 Dividing a string by another splits the first using the second622 as separators. 622 as separators.623624 Multiplying two objects will merge them recursively: this works625 like addition but if both objects contain a value for the626 same key, and the values are objects, the two are merged with
82 unmodified lines
709 output: ['[false, true]']710711 - title: "`in`"712 body: |713 713714 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 718719 examples:720 - program: '.[] | in({"foo": 42})'721 input: '["foo", "bar"]'722 output: ['true', 'false']723 - program: 'map(in([0,1]))'724 input: '[2, 0]'725 output: ['[false, true]']726 726727 - title: "`path(path_expression)`"728 body: |729730 Outputs array representations of the given path expression
136 unmodified lines
867868 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 871872 Similarly, `map_values(x)` will run that filter for each element,873 but it will return an object when an object is passed.874 874875 `map(x)` is equivalent to `[.[] | x]`. In fact, this is how876 it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`.877878 examples:879 - program: 'map(.+1)'880 input: '[1,2,3]'881 output: ['[2,3,4]']882 882883 - program: 'map_values(.+1)'884 input: '{"a": 1, "b": 2, "c": 3}'885 output: ['{"a": 2, "b": 3, "c": 4}']886
525 unmodified lines
14121413 - title: "`ascii_downcase`, `ascii_upcase`"1414 body: |14151416 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.14181419 example:1420 - program: 'ascii_upcase'
154 unmodified lines
15751576 - title: "`transpose`"1577 body: |15781579 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.15811582 examples:1583 - program: 'transpose'
1004 unmodified lines
2588 to process it much more quickly.25892590 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 25922593 Several builtins are provided to make handling streams easier.25942595 The examples below use the the streamed form of `[0,[1]]`, which2596 is `[[0],0],[[1,0],1],[[1,0]],[[1]]`.
244 unmodified lines
2841 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 28452846 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 lines
2874 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 28782879 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 lines
modified:docs/public/.htaccess+2 added-2 removed
10 unmodified lines
11 Header append Vary User-Agent12 </IfModule>13</IfModule>1415# Cache, aggressively 15# Cache, aggressively16<IfModule mod_expires.c>17 ExpiresActive On18 ExpiresDefault "access plus 10 days"19
4 unmodified lines
2425# Mime-types26AddType application/vnd.ms-fontobject .eot27AddType font/ttf .ttf28AddType font/otf .otf28AddType font/otf .otf
modified:docs/default_manpage.md+2 added-2 removed
modified:docs/Rakefile+8 added-8 removed
17 unmodified lines
1819 def json(input)20 input.to_json21 end22 2223 def unique(input)24 @n = (@n || 0) + 125 input + @n.to_s26 end
4 unmodified lines
3132task :serve do33 begin34 Bonsai.log "Press Control+C to quit"35 3536 require 'rack'37 require 'sinatra'38 require 'watch'39 require 'launchy'40 4041 Bonsai.root_dir = Dir.pwd42 43 server = fork { 4243 server = fork {44 app = Rack::Builder.app {45 map "/jq" do46 use Bonsai::StaticPassThrough, :root => Bonsai.root_dir + "/output", :urls => ["/"]47 end
1 unmodified line
49 }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 lines
95 manual = load_manual96 f.puts manual['manpage_intro']97 f.puts manual['body']98 manual['sections'].each do |section|99 99100 f.puts "## #{section['title'].upcase}\n"101 f.puts section['body']102 f.puts ""103 (section['entries'] || []).each do |entry|
11 unmodified lines
115 end116 f.puts manual['manpage_epilogue']117 f.close118 puts Ronn::Document.new(f.path).convert('roff').gsub(/<\/?code>/,"")119 end 119 end120end121122task :manpage_default => ["default_manpage.md"] do123 puts Ronn::Document.new("default_manpage.md").convert('roff').gsub(/<\/?code>/,"")
22 unmodified lines
modified:docs/site.yml+1 added-1 removed
modified:scripts/crosscompile+1 added-1 removed
1#!/bin/sh23# This script is used to cross-compile binaries for 3# This script is used to cross-compile binaries for4# platforms other than the current one56# Usage: $0 <platformname> <configure options>7# <platformname> is arbitrary, it is the name
35 unmodified lines
modified:scripts/gen_utf8_tables.py+2 added-2 removed
8 unmodified lines
9 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 "};"))151617def utf8info(c):
3 unmodified lines
21 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 2526table = lambda i: [utf8info(c)[i] for c in range(256)]2728print("#define UTF8_CONTINUATION_BYTE ((unsigned char)255)")29
3 unmodified lines
modified:AUTHORS+1 added-1 removed
16 unmodified lines
17Filippo Valsorda <filippo.valsorda@gmail.com> - recursive object merge (`*`)18Jack Pearkes <jackpearkes@gmail.com> - update tutorial19Jingwen Owen Ou <jingweno@gmail.com> - jqplay.org and link to it20Joe Littlejohn <joe.littlejohn@nokia.com> - bug fixes21Juan Guerrero <juan.guerrero.lozano@gmail.com> - bug fixes 21Juan Guerrero <juan.guerrero.lozano@gmail.com> - bug fixes22Kenny Shen <kenny.shen@zalora.com> - doc fixes23Lee Thompson <stagr.lee@gmail.com> - autoconf stuff24Markus Lanthaler <mark_lanthaler@gmx.net> - doc fixes25Michael Daines <michael@mdaines.com> - add sqrt; doc fixes
48 unmodified lines
modified:configure.ac+1 added-1 removed
198 unmodified lines
199AC_LINK_IFELSE([AC_LANG_SOURCE([200static __thread int x ;201int main () { x = 123; return x; }202])], have___thread=yes)203if test $have___thread = yes; then 203if test $have___thread = yes; then204 AC_DEFINE([HAVE___THREAD],1,[Define to 1 if the system supports __thread])205fi206AC_MSG_RESULT($have___thread)207
14 unmodified lines
modified:COPYING+2 added-2 removed
28 unmodified lines
2930The documentation website includes a copy of Twitter's Boostrap and31relies on Bonsai, Liquid templates and various other projects, look32them up for detailed licensing conditions.33 3335 343536jq incorporates David M. Gay's dtoa.c and g_fmt.c, which bear the37following notices:3839dtoa.c:
31 unmodified lines
modified:lexer.c+3 added-3 removed
1132 unmodified lines
1133 YY_BREAK1134case 38:1135YY_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_BREAK1141case 39:1142YY_RULE_SETUP
1255 unmodified lines
2398 case IN_BRACKET: match = ret = ']'; break;2399 case IN_BRACE: match = ret = '}'; break;24002401 case IN_QQINTERP:2402 match = ')'; 2402 match = ')';2403 ret = QQSTRING_INTERP_END;2404 break;24052406 default:
36 unmodified lines
modified:lexer.l+4 added-4 removed
83 unmodified lines
84"@"[a-zA-Z0-9_]+ {85 yylval->literal = jv_string_sized(yytext + 1, yyleng - 1); return FORMAT;86}8788[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}9192"\"" {93 yy_push_state(IN_QQSTRING, yyscanner);
22 unmodified lines
116 . {117 return INVALID_CHARACTER;118 }119}120 120121122([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;}124125[ \n\t]+ {}
15 unmodified lines
141 case IN_BRACKET: match = ret = ']'; break;142 case IN_BRACE: match = ret = '}'; break;143144 case IN_QQINTERP:145 match = ')'; 145 match = ')';146 ret = QQSTRING_INTERP_END;147 break;148149 default:
35 unmodified lines
modified:Makefile.am+4 added-4 removed
24 unmodified lines
25lexer.c: lexer.l26 $(AM_V_LEX) flex -o lexer.c --header-file=lexer.h $<27lexer.h: lexer.c28else29BUILT_SOURCES = 29BUILT_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 lines
145 docs/Gemfile docs/Gemfile.lock docs/Rakefile docs/README.md \146 docs/default_manpage.md jq.1.default147148# 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.151EXTRA_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 lines
163 tests/modules/test_bind_order2.jq \164 jq.1.prebuilt165166167# 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.169docdir = ${datadir}/doc/${PACKAGE}170dist_doc_DATA = README.md COPYING AUTHORS README171
14 unmodified lines
186# 'make clean' doesn't delete the manpage if it can't be rebuilt187clean-local-docs:188if ENABLE_DOCS189 rm -f jq.1190endif 190endif191192clean-local-gcov:193 rm -f *.gcno *.gcda *.gcov194
4 unmodified lines