@port-labs/jq-node-bindings 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/.editorconfig +5 -0
  2. package/.jshintignore +1 -0
  3. package/.jshintrc +23 -0
  4. package/binding.gyp +56 -0
  5. package/configure +26 -0
  6. package/deps/jq/.gitattributes +2 -0
  7. package/deps/jq/.travis.yml +53 -0
  8. package/deps/jq/AUTHORS +73 -0
  9. package/deps/jq/COPYING +70 -0
  10. package/deps/jq/ChangeLog +1349 -0
  11. package/deps/jq/Makefile.am +198 -0
  12. package/deps/jq/NEWS +88 -0
  13. package/deps/jq/README.md +64 -0
  14. package/deps/jq/builtin.c +1684 -0
  15. package/deps/jq/builtin.h +10 -0
  16. package/deps/jq/bytecode.c +161 -0
  17. package/deps/jq/bytecode.h +92 -0
  18. package/deps/jq/compile-ios.sh +102 -0
  19. package/deps/jq/compile.c +1210 -0
  20. package/deps/jq/compile.h +101 -0
  21. package/deps/jq/config/m4/check-math-func.m4 +4 -0
  22. package/deps/jq/config/m4/find-func-no-libs.m4 +8 -0
  23. package/deps/jq/config/m4/find-func-no-libs2.m4 +62 -0
  24. package/deps/jq/config/m4/find-func.m4 +9 -0
  25. package/deps/jq/config/m4/misc.m4 +3 -0
  26. package/deps/jq/configure.ac +221 -0
  27. package/deps/jq/docs/Gemfile +7 -0
  28. package/deps/jq/docs/Gemfile.lock +63 -0
  29. package/deps/jq/docs/README.md +25 -0
  30. package/deps/jq/docs/Rakefile +145 -0
  31. package/deps/jq/docs/content/1.tutorial/default.yml +327 -0
  32. package/deps/jq/docs/content/2.download/default.yml +117 -0
  33. package/deps/jq/docs/content/3.manual/manual.yml +2878 -0
  34. package/deps/jq/docs/content/3.manual/v1.3/manual.yml +1270 -0
  35. package/deps/jq/docs/content/3.manual/v1.4/manual.yml +1672 -0
  36. package/deps/jq/docs/content/index/index.yml +51 -0
  37. package/deps/jq/docs/default_manpage.md +22 -0
  38. package/deps/jq/docs/public/.htaccess +28 -0
  39. package/deps/jq/docs/public/bootstrap/css/bootstrap-responsive.css +1058 -0
  40. package/deps/jq/docs/public/bootstrap/css/bootstrap-responsive.min.css +9 -0
  41. package/deps/jq/docs/public/bootstrap/css/bootstrap.css +5224 -0
  42. package/deps/jq/docs/public/bootstrap/css/bootstrap.min.css +9 -0
  43. package/deps/jq/docs/public/bootstrap/img/glyphicons-halflings-white.png +0 -0
  44. package/deps/jq/docs/public/bootstrap/img/glyphicons-halflings.png +0 -0
  45. package/deps/jq/docs/public/bootstrap/js/bootstrap.js +2027 -0
  46. package/deps/jq/docs/public/bootstrap/js/bootstrap.min.js +6 -0
  47. package/deps/jq/docs/public/css/base.scss +99 -0
  48. package/deps/jq/docs/public/jq.png +0 -0
  49. package/deps/jq/docs/public/robots.txt +2 -0
  50. package/deps/jq/docs/site.yml +18 -0
  51. package/deps/jq/docs/templates/default.liquid +34 -0
  52. package/deps/jq/docs/templates/index.liquid +60 -0
  53. package/deps/jq/docs/templates/manual.liquid +122 -0
  54. package/deps/jq/docs/templates/shared/_footer.liquid +5 -0
  55. package/deps/jq/docs/templates/shared/_head.liquid +12 -0
  56. package/deps/jq/docs/templates/shared/_header.liquid +26 -0
  57. package/deps/jq/exec_stack.h +112 -0
  58. package/deps/jq/execute.c +1155 -0
  59. package/deps/jq/inject_errors.c +112 -0
  60. package/deps/jq/jq.1.default +39 -0
  61. package/deps/jq/jq.1.prebuilt +3075 -0
  62. package/deps/jq/jq.h +60 -0
  63. package/deps/jq/jq.spec +70 -0
  64. package/deps/jq/jq_parser.h +9 -0
  65. package/deps/jq/jq_test.c +346 -0
  66. package/deps/jq/jv.c +1333 -0
  67. package/deps/jq/jv.h +240 -0
  68. package/deps/jq/jv_alloc.c +179 -0
  69. package/deps/jq/jv_alloc.h +27 -0
  70. package/deps/jq/jv_aux.c +619 -0
  71. package/deps/jq/jv_dtoa.c +4275 -0
  72. package/deps/jq/jv_dtoa.h +22 -0
  73. package/deps/jq/jv_file.c +49 -0
  74. package/deps/jq/jv_parse.c +852 -0
  75. package/deps/jq/jv_print.c +348 -0
  76. package/deps/jq/jv_unicode.c +96 -0
  77. package/deps/jq/jv_unicode.h +11 -0
  78. package/deps/jq/jv_utf8_tables.h +37 -0
  79. package/deps/jq/lexer.c +2442 -0
  80. package/deps/jq/lexer.h +362 -0
  81. package/deps/jq/lexer.l +184 -0
  82. package/deps/jq/libm.h +160 -0
  83. package/deps/jq/linker.c +393 -0
  84. package/deps/jq/linker.h +7 -0
  85. package/deps/jq/locfile.c +91 -0
  86. package/deps/jq/locfile.h +29 -0
  87. package/deps/jq/m4/ax_compare_version.m4 +177 -0
  88. package/deps/jq/m4/ax_prog_bison_version.m4 +68 -0
  89. package/deps/jq/main.c +566 -0
  90. package/deps/jq/opcode_list.h +44 -0
  91. package/deps/jq/parser.c +3914 -0
  92. package/deps/jq/parser.h +193 -0
  93. package/deps/jq/parser.y +923 -0
  94. package/deps/jq/scripts/crosscompile +42 -0
  95. package/deps/jq/scripts/gen_utf8_tables.py +32 -0
  96. package/deps/jq/scripts/version +5 -0
  97. package/deps/jq/setup.sh +33 -0
  98. package/deps/jq/tests/jq.test +1235 -0
  99. package/deps/jq/tests/jqtest +5 -0
  100. package/deps/jq/tests/mantest +7 -0
  101. package/deps/jq/tests/modules/.jq +5 -0
  102. package/deps/jq/tests/modules/a.jq +2 -0
  103. package/deps/jq/tests/modules/b/b.jq +2 -0
  104. package/deps/jq/tests/modules/c/c.jq +16 -0
  105. package/deps/jq/tests/modules/c/d.jq +1 -0
  106. package/deps/jq/tests/modules/data.json +4 -0
  107. package/deps/jq/tests/modules/lib/jq/e/e.jq +1 -0
  108. package/deps/jq/tests/modules/lib/jq/f.jq +1 -0
  109. package/deps/jq/tests/modules/syntaxerror/syntaxerror.jq +1 -0
  110. package/deps/jq/tests/modules/test_bind_order.jq +4 -0
  111. package/deps/jq/tests/modules/test_bind_order0.jq +1 -0
  112. package/deps/jq/tests/modules/test_bind_order1.jq +2 -0
  113. package/deps/jq/tests/modules/test_bind_order2.jq +2 -0
  114. package/deps/jq/tests/onig.supp +21 -0
  115. package/deps/jq/tests/onig.test +85 -0
  116. package/deps/jq/tests/onigtest +5 -0
  117. package/deps/jq/tests/setup +36 -0
  118. package/deps/jq/tests/shtest +205 -0
  119. package/deps/jq/tests/torture/input0.json +7 -0
  120. package/deps/jq/util.c +462 -0
  121. package/deps/jq/util.h +64 -0
  122. package/deps/jq.gyp +35 -0
  123. package/index.d.ts +3 -0
  124. package/jest.config.js +10 -0
  125. package/lib/index.js +14 -0
  126. package/package.json +48 -0
  127. package/reports/jest-port-api.xml +35 -0
  128. package/src/binding.cc +177 -0
  129. package/src/binding.h +13 -0
  130. package/test/santiy.test.js +122 -0
  131. package/util/configure.js +27 -0
@@ -0,0 +1,2878 @@
1
+ ---
2
+ headline: jq Manual (development version)
3
+
4
+ history: |
5
+
6
+ *For released versions, see [jq 1.4](/jq/manual/v1.4) or
7
+ [jq 1.3](/jq/manual/v1.3).*
8
+
9
+ body: |
10
+
11
+ A jq program is a "filter": it takes an input, and produces an
12
+ output. There are a lot of builtin filters for extracting a
13
+ particular field of an object, or converting a number to a string,
14
+ or various other standard tasks.
15
+
16
+ Filters can be combined in various ways - you can pipe the output of
17
+ one filter into another filter, or collect the output of a filter
18
+ into an array.
19
+
20
+ Some filters produce multiple results, for instance there's one that
21
+ produces all the elements of its input array. Piping that filter
22
+ into a second runs the second filter for each element of the
23
+ array. Generally, things that would be done with loops and iteration
24
+ in other languages are just done by gluing filters together in jq.
25
+
26
+ It's important to remember that every filter has an input and an
27
+ output. Even literals like "hello" or 42 are filters - they take an
28
+ input but always produce the same literal as output. Operations that
29
+ combine two filters, like addition, generally feed the same input to
30
+ both and combine the results. So, you can implement an averaging
31
+ filter as `add / length` - feeding the input array both to the `add`
32
+ filter and the `length` filter and then performing the division.
33
+
34
+ But that's getting ahead of ourselves. :) Let's start with something
35
+ simpler:
36
+
37
+ manpage_intro: |
38
+ jq(1) -- Command-line JSON processor
39
+ ====================================
40
+
41
+ ## SYNOPSIS
42
+
43
+ `jq` [<options>...] <filter> [<files>...]
44
+
45
+ `jq` can transform JSON in various ways, by selecting, iterating,
46
+ reducing and otherwise mangling JSON documents. For instance,
47
+ running the command `jq 'map(.price) | add'` will take an array of
48
+ JSON objects as input and return the sum of their "price" fields.
49
+
50
+ `jq` can accept text input as well, but by default, `jq` reads a
51
+ stream of JSON entities (including numbers and other literals) from
52
+ `stdin`. Whitespace is only needed to separate entities such as 1
53
+ and 2, and true and false. One or more <files> may be specified, in
54
+ which case `jq` will read input from those instead.
55
+
56
+ The <options> are described in the [INVOKING JQ] section; they
57
+ mostly concern input and output formatting. The <filter> is written
58
+ in the jq language and specifies how to transform the input
59
+ file or document.
60
+
61
+ ## FILTERS
62
+
63
+ manpage_epilogue: |
64
+ ## BUGS
65
+
66
+ Presumably. Report them or discuss them at:
67
+
68
+ https://github.com/stedolan/jq/issues
69
+
70
+ ## AUTHOR
71
+
72
+ Stephen Dolan `<mu@netsoc.tcd.ie>`
73
+
74
+ sections:
75
+ - title: Invoking jq
76
+ body: |
77
+
78
+ jq filters run on a stream of JSON data. The input to jq is
79
+ parsed as a sequence of whitespace-separated JSON values which
80
+ are passed through the provided filter one at a time. The
81
+ output(s) of the filter are written to standard out, again as a
82
+ sequence of whitespace-separated JSON data.
83
+
84
+ Note: it is important to mind the shell's quoting rules. As a
85
+ general rule it's best to always quote (with single-quote
86
+ characters) the jq program, as too many characters with special
87
+ meaning to jq are also shell meta-characters. For example, `jq
88
+ "foo"` will fail on most Unix shells because that will be the same
89
+ as `jq foo`, which will generally fail because `foo is not
90
+ defined`. When using the Windows command shell (cmd.exe) it's
91
+ best to use double quotes around your jq program when given on the
92
+ command-line (instead of the `-f program-file` option), but then
93
+ double-quotes in the jq program need backslash escaping.
94
+
95
+ You can affect how jq reads and writes its input and output
96
+ using some command-line options:
97
+
98
+ * `--version`:
99
+
100
+ Output the jq version and exit with zero.
101
+
102
+ * `--seq`:
103
+
104
+ Use the `application/json-seq` MIME type scheme for separating
105
+ JSON texts in jq's input and output. This means that an ASCII
106
+ RS (record separator) character is printed before each value on
107
+ output and an ASCII LF (line feed) is printed after every
108
+ output. Input JSON texts that fail to parse are ignored (but
109
+ warned about), discarding all subsequent input until the next
110
+ RS. This more also parses the output of jq without the `--seq`
111
+ option.
112
+
113
+ * `--stream`:
114
+
115
+ Parse the input in streaming fashion, outputing arrays of path
116
+ and leaf values (scalars and empty arrays or empty objects).
117
+ For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]`
118
+ becomes `[[0],[]]`, `[[1],"a"]`, and `[[1,0],"b"]`.
119
+
120
+ This is useful for processing very large inputs. Use this in
121
+ conjunction with filtering and the `reduce` and `foreach` syntax
122
+ to reduce large inputs incrementally.
123
+
124
+ * `--slurp`/`-s`:
125
+
126
+ Instead of running the filter for each JSON object in the
127
+ input, read the entire input stream into a large array and run
128
+ the filter just once.
129
+
130
+ * `--raw-input`/`-R`:
131
+
132
+ Don't parse the input as JSON. Instead, each line of text is
133
+ passed to the filter as a string. If combined with `--slurp`,
134
+ then the entire input is passed to the filter as a single long
135
+ string.
136
+
137
+ * `--null-input`/`-n`:
138
+
139
+ Don't read any input at all! Instead, the filter is run once
140
+ using `null` as the input. This is useful when using jq as a
141
+ simple calculator or to construct JSON data from scratch.
142
+
143
+ * `--compact-output` / `-c`:
144
+
145
+ By default, jq pretty-prints JSON output. Using this option
146
+ will result in more compact output by instead putting each
147
+ JSON object on a single line.
148
+
149
+ * `--tab`:
150
+
151
+ Use a tab for each indentation level instead of two spaces.
152
+
153
+ * `--indent n`:
154
+
155
+ Use the given number of spaces (no more than 8) for indentation.
156
+
157
+ * `--color-output` / `-C` and `--monochrome-output` / `-M`:
158
+
159
+ By default, jq outputs colored JSON if writing to a
160
+ terminal. You can force it to produce color even if writing to
161
+ a pipe or a file using `-C`, and disable color with `-M`.
162
+
163
+ * `--ascii-output` / `-a`:
164
+
165
+ jq usually outputs non-ASCII Unicode codepoints as UTF-8, even
166
+ if the input specified them as escape sequences (like
167
+ "\u03bc"). Using this option, you can force jq to produce pure
168
+ ASCII output with every non-ASCII character replaced with the
169
+ equivalent escape sequence.
170
+
171
+ * `--unbuffered`
172
+
173
+ Flush the output after each JSON object is printed (useful if
174
+ you're piping a slow data source into jq and piping jq's
175
+ output elsewhere).
176
+
177
+ * `--sort-keys` / `-S`:
178
+
179
+ Output the fields of each object with the keys in sorted order.
180
+
181
+ * `--raw-output` / `-r`:
182
+
183
+ With this option, if the filter's result is a string then it
184
+ will be written directly to standard output rather than being
185
+ formatted as a JSON string with quotes. This can be useful for
186
+ making jq filters talk to non-JSON-based systems.
187
+
188
+ * `--join-output` / `-j`:
189
+
190
+ Like `-r` but jq won't print a newline after each output.
191
+
192
+ * `-f filename` / `--from-file filename`:
193
+
194
+ Read filter from the file rather than from a command line, like
195
+ awk's -f option. You can also use '#' to make comments.
196
+
197
+ * `-Ldirectory` / `-L directory`:
198
+
199
+ Prepend `directory` to the search list for modules. If this
200
+ option is used then no builtin search list is used. See the
201
+ section on modules below.
202
+
203
+ * `-e` / `--exit-status`:
204
+
205
+ Sets the exit status of jq to 0 if the last output values was
206
+ neither `false` nor `null`, 1 if the last output value was
207
+ either `false` or `null`, or 4 if no valid result was ever
208
+ produced. Normally jq exits with 2 if there was any usage
209
+ problem or system error, 3 if there was a jq program compile
210
+ error, or 0 if the jq program ran.
211
+
212
+ * `--arg name value`:
213
+
214
+ This option passes a value to the jq program as a predefined
215
+ variable. If you run jq with `--arg foo bar`, then `$foo` is
216
+ available in the program and has the value `"bar"`. Note that
217
+ `value` will be treated as a string, so `--arg foo 123` will
218
+ bind `$foo` to `"123"`.
219
+
220
+ * `--argjson name JSON-text`:
221
+
222
+ This option passes a JSON-encoded value to the jq program as a
223
+ predefined variable. If you run jq with `--argjson foo 123`, then
224
+ `$foo` is available in the program and has the value `123`.
225
+
226
+ * `--slurpfile variable-name filename`:
227
+
228
+ This option reads all the JSON texts in the named file and binds
229
+ an array of the parsed JSON values to the given global variable.
230
+ If you run jq with `--argfile foo bar`, then `$foo` is available
231
+ in the program and has an array whose elements correspond to the
232
+ texts in the file named `bar`.
233
+
234
+ * `--argfile variable-name filename`:
235
+
236
+ Do not use. Use `--slurpfile` instead.
237
+
238
+ (This option is like `--slurpfile`, but when the file has just
239
+ one text, then that is used, else an array of texts is used as
240
+ in `--slurpfile`.)
241
+
242
+ * `--run-tests [filename]`:
243
+
244
+ Runs the tests in the given file or standard input. This must
245
+ be the last option given and does not honor all preceding
246
+ options. The input consists of comment lines, empty lines, and
247
+ program lines followed by one input line, as many lines of
248
+ output as are expected (one per output), and a terminating empty
249
+ line. Compilation failure tests start with a line containing
250
+ only "%%FAIL", then a line containing the program to compile,
251
+ then a line containing an error message to compare to the
252
+ actual.
253
+
254
+ Be warned that this option can change backwards-incompatibly.
255
+
256
+ - title: Basic filters
257
+ entries:
258
+ - title: "`.`"
259
+ body: |
260
+
261
+ The absolute simplest (and least interesting) filter
262
+ is `.`. This is a filter that takes its input and
263
+ produces it unchanged as output.
264
+
265
+ Since jq by default pretty-prints all output, this trivial
266
+ program can be a useful way of formatting JSON output from,
267
+ say, `curl`.
268
+
269
+ examples:
270
+ - program: '.'
271
+ input: '"Hello, world!"'
272
+ output: ['"Hello, world!"']
273
+
274
+ - title: "`.foo`, `.foo.bar`"
275
+ body: |
276
+
277
+ The simplest *useful* filter is `.foo`. When given a
278
+ JSON object (aka dictionary or hash) as input, it produces
279
+ the value at the key "foo", or null if there's none present.
280
+
281
+ If the key contains special characters, you need to surround
282
+ it with double quotes like this: `."foo$"`.
283
+
284
+ A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.
285
+
286
+ examples:
287
+ - program: '.foo'
288
+ input: '{"foo": 42, "bar": "less interesting data"}'
289
+ output: [42]
290
+ - program: '.foo'
291
+ input: '{"notfoo": true, "alsonotfoo": false}'
292
+ output: ['null']
293
+ - program: '.["foo"]'
294
+ input: '{"foo": 42}'
295
+ output: [42]
296
+
297
+ - title: "`.foo?`"
298
+ body: |
299
+
300
+ Just like `.foo`, but does not output even an error when `.`
301
+ is not an array or an object.
302
+
303
+ examples:
304
+ - program: '.foo?'
305
+ input: '{"foo": 42, "bar": "less interesting data"}'
306
+ output: [42]
307
+ - program: '.foo?'
308
+ input: '{"notfoo": true, "alsonotfoo": false}'
309
+ output: ['null']
310
+ - program: '.["foo"]?'
311
+ input: '{"foo": 42}'
312
+ output: [42]
313
+ - program: '[.foo?]'
314
+ input: '[1,2]'
315
+ output: ['[]']
316
+
317
+ - title: "`.[<string>]`, `.[2]`, `.[10:15]`"
318
+ body: |
319
+
320
+ You can also look up fields of an object using syntax like
321
+ `.["foo"]` (.foo above is a shorthand version of this). This
322
+ one works for arrays as well, if the key is an
323
+ integer. Arrays are zero-based (like javascript), so `.[2]`
324
+ returns the third element of the array.
325
+
326
+ The `.[10:15]` syntax can be used to return a subarray of an
327
+ array or substring of a string. The array returned by
328
+ `.[10:15]` will be of length 5, containing the elements from
329
+ index 10 (inclusive) to index 15 (exclusive). Either index may
330
+ be negative (in which case it counts backwards from the end of
331
+ the array), or omitted (in which case it refers to the start
332
+ or end of the array).
333
+
334
+ The `.[2]` syntax can be used to return the element at the
335
+ given index. Negative indices are allowed, with -1 referring
336
+ to the last element, -2 referring to the next to last element,
337
+ and so on.
338
+
339
+ The `.foo` syntax only works for simply keys i.e. keys that
340
+ are all alphanumeric characters. `.[<string>]` works with
341
+ keys that contain special characters such as colons and dots.
342
+ For example `.["foo::bar"]` and `.["foo.bar"]` work while
343
+ `.foo::bar` and `.foo.bar` would not.
344
+
345
+ The `?` "operator" can also be used with the slice operator,
346
+ as in `.[10:15]?`, which outputs values where the inputs are
347
+ slice-able.
348
+
349
+ examples:
350
+ - program: '.[0]'
351
+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'
352
+ output: ['{"name":"JSON", "good":true}']
353
+
354
+ - program: '.[2]'
355
+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'
356
+ output: ['null']
357
+
358
+ - program: '.[2:4]'
359
+ input: '["a","b","c","d","e"]'
360
+ output: ['["c", "d"]']
361
+
362
+ - program: '.[2:4]'
363
+ input: '"abcdefghi"'
364
+ output: ['"cd"']
365
+
366
+ - program: '.[:3]'
367
+ input: '["a","b","c","d","e"]'
368
+ output: ['["a", "b", "c"]']
369
+
370
+ - program: '.[-2:]'
371
+ input: '["a","b","c","d","e"]'
372
+ output: ['["d", "e"]']
373
+
374
+ - program: '.[-2]'
375
+ input: '[1,2,3]'
376
+ output: ['2']
377
+
378
+ - title: "`.[]`"
379
+ body: |
380
+
381
+ If you use the `.[index]` syntax, but omit the index
382
+ entirely, it will return *all* of the elements of an
383
+ array. Running `.[]` with the input `[1,2,3]` will produce the
384
+ numbers as three separate results, rather than as a single
385
+ array.
386
+
387
+ You can also use this on an object, and it will return all
388
+ the values of the object.
389
+
390
+ examples:
391
+ - program: '.[]'
392
+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'
393
+ output:
394
+ - '{"name":"JSON", "good":true}'
395
+ - '{"name":"XML", "good":false}'
396
+
397
+ - program: '.[]'
398
+ input: '[]'
399
+ output: []
400
+
401
+ - program: '.[]'
402
+ input: '{"a": 1, "b": 1}'
403
+ output: ['1', '1']
404
+
405
+ - title: "`.[]?`"
406
+ body: |
407
+
408
+ Like `.[]`, but no errors will be output if . is not an array
409
+ or object.
410
+
411
+ - title: "`,`"
412
+ body: |
413
+
414
+ If two filters are separated by a comma, then the
415
+ input will be fed into both and there will be multiple
416
+ outputs: first, all of the outputs produced by the left
417
+ expression, and then all of the outputs produced by the
418
+ right. For instance, filter `.foo, .bar`, produces
419
+ both the "foo" fields and "bar" fields as separate outputs.
420
+
421
+ examples:
422
+ - program: '.foo, .bar'
423
+ input: '{"foo": 42, "bar": "something else", "baz": true}'
424
+ output: ['42', '"something else"']
425
+
426
+ - program: ".user, .projects[]"
427
+ input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'
428
+ output: ['"stedolan"', '"jq"', '"wikiflow"']
429
+
430
+ - program: '.[4,2]'
431
+ input: '["a","b","c","d","e"]'
432
+ output: ['"e"', '"c"']
433
+
434
+ - title: "`|`"
435
+ body: |
436
+ The | operator combines two filters by feeding the output(s) of
437
+ the one on the left into the input of the one on the right. It's
438
+ pretty much the same as the Unix shell's pipe, if you're used to
439
+ that.
440
+
441
+ If the one on the left produces multiple results, the one on
442
+ the right will be run for each of those results. So, the
443
+ expression `.[] | .foo` retrieves the "foo" field of each
444
+ element of the input array.
445
+
446
+ examples:
447
+ - program: '.[] | .name'
448
+ input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'
449
+ output: ['"JSON"', '"XML"']
450
+
451
+ - title: Types and Values
452
+ body: |
453
+
454
+ jq supports the same set of datatypes as JSON - numbers,
455
+ strings, booleans, arrays, objects (which in JSON-speak are
456
+ hashes with only string keys), and "null".
457
+
458
+ Booleans, null, strings and numbers are written the same way as
459
+ in javascript. Just like everything else in jq, these simple
460
+ values take an input and produce an output - `42` is a valid jq
461
+ expression that takes an input, ignores it, and returns 42
462
+ instead.
463
+
464
+ entries:
465
+ - title: Array construction - `[]`
466
+ body: |
467
+
468
+ As in JSON, `[]` is used to construct arrays, as in
469
+ `[1,2,3]`. The elements of the arrays can be any jq
470
+ expression. All of the results produced by all of the
471
+ expressions are collected into one big array. You can use it
472
+ to construct an array out of a known quantity of values (as
473
+ in `[.foo, .bar, .baz]`) or to "collect" all the results of a
474
+ filter into an array (as in `[.items[].name]`)
475
+
476
+ Once you understand the "," operator, you can look at jq's array
477
+ syntax in a different light: the expression `[1,2,3]` is not using a
478
+ built-in syntax for comma-separated arrays, but is instead applying
479
+ the `[]` operator (collect results) to the expression 1,2,3 (which
480
+ produces three different results).
481
+
482
+ If you have a filter `X` that produces four results,
483
+ then the expression `[X]` will produce a single result, an
484
+ array of four elements.
485
+
486
+ examples:
487
+ - program: "[.user, .projects[]]"
488
+ input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'
489
+ output: ['["stedolan", "jq", "wikiflow"]']
490
+ - title: Objects - `{}`
491
+ body: |
492
+
493
+ Like JSON, `{}` is for constructing objects (aka
494
+ dictionaries or hashes), as in: `{"a": 42, "b": 17}`.
495
+
496
+ If the keys are "sensible" (all alphabetic characters), then
497
+ the quotes can be left off. The value can be any expression
498
+ (although you may need to wrap it in parentheses if it's a
499
+ complicated one), which gets applied to the {} expression's
500
+ input (remember, all filters have an input and an
501
+ output).
502
+
503
+ {foo: .bar}
504
+
505
+ will produce the JSON object `{"foo": 42}` if given the JSON
506
+ object `{"bar":42, "baz":43}`. You can use this to select
507
+ particular fields of an object: if the input is an object
508
+ with "user", "title", "id", and "content" fields and you
509
+ just want "user" and "title", you can write
510
+
511
+ {user: .user, title: .title}
512
+
513
+ Because that's so common, there's a shortcut syntax: `{user, title}`.
514
+
515
+ If one of the expressions produces multiple results,
516
+ multiple dictionaries will be produced. If the input's
517
+
518
+ {"user":"stedolan","titles":["JQ Primer", "More JQ"]}
519
+
520
+ then the expression
521
+
522
+ {user, title: .titles[]}
523
+
524
+ will produce two outputs:
525
+
526
+ {"user":"stedolan", "title": "JQ Primer"}
527
+ {"user":"stedolan", "title": "More JQ"}
528
+
529
+ Putting parentheses around the key means it will be evaluated as an
530
+ expression. With the same input as above,
531
+
532
+ {(.user): .titles}
533
+
534
+ produces
535
+
536
+ {"stedolan": ["JQ Primer", "More JQ"]}
537
+
538
+ examples:
539
+ - program: '{user, title: .titles[]}'
540
+ input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'
541
+ output:
542
+ - '{"user":"stedolan", "title": "JQ Primer"}'
543
+ - '{"user":"stedolan", "title": "More JQ"}'
544
+ - program: '{(.user): .titles}'
545
+ input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'
546
+ output: ['{"stedolan": ["JQ Primer", "More JQ"]}']
547
+
548
+ - title: Builtin operators and functions
549
+ body: |
550
+
551
+ Some jq operator (for instance, `+`) do different things
552
+ depending on the type of their arguments (arrays, numbers,
553
+ etc.). However, jq never does implicit type conversions. If you
554
+ try to add a string to an object you'll get an error message and
555
+ no result.
556
+
557
+ entries:
558
+ - title: Addition - `+`
559
+ body: |
560
+
561
+ The operator `+` takes two filters, applies them both
562
+ to the same input, and adds the results together. What
563
+ "adding" means depends on the types involved:
564
+
565
+ - **Numbers** are added by normal arithmetic.
566
+
567
+ - **Arrays** are added by being concatenated into a larger array.
568
+
569
+ - **Strings** are added by being joined into a larger string.
570
+
571
+ - **Objects** are added by merging, that is, inserting all
572
+ the key-value pairs from both objects into a single
573
+ combined object. If both objects contain a value for the
574
+ same key, the object on the right of the `+` wins. (For
575
+ recursive merge use the `*` operator.)
576
+
577
+ `null` can be added to any value, and returns the other
578
+ value unchanged.
579
+
580
+ examples:
581
+ - program: '.a + 1'
582
+ input: '{"a": 7}'
583
+ output: ['8']
584
+ - program: '.a + .b'
585
+ input: '{"a": [1,2], "b": [3,4]}'
586
+ output: ['[1,2,3,4]']
587
+ - program: '.a + null'
588
+ input: '{"a": 1}'
589
+ output: ['1']
590
+ - program: '.a + 1'
591
+ input: '{}'
592
+ output: ['1']
593
+ - program: '{a: 1} + {b: 2} + {c: 3} + {a: 42}'
594
+ input: 'null'
595
+ output: ['{"a": 42, "b": 2, "c": 3}']
596
+
597
+ - title: Subtraction - `-`
598
+ body: |
599
+
600
+ As well as normal arithmetic subtraction on numbers, the `-`
601
+ operator can be used on arrays to remove all occurrences of
602
+ the second array's elements from the first array.
603
+
604
+ examples:
605
+ - program: '4 - .a'
606
+ input: '{"a":3}'
607
+ output: ['1']
608
+ - program: . - ["xml", "yaml"]
609
+ input: '["xml", "yaml", "json"]'
610
+ output: ['["json"]']
611
+
612
+ - title: Multiplication, division, modulo - `*`, `/`, and `%`
613
+ body: |
614
+
615
+ These infix operators behave as expected when given two numbers.
616
+ Division by zero raises an error. `x % y` computes x modulo y.
617
+
618
+ Multiplying a string by a number produces the concatenation of
619
+ that string that many times. `"x" * 0` produces **null**.
620
+
621
+ Dividing a string by another splits the first using the second
622
+ as separators.
623
+
624
+ Multiplying two objects will merge them recursively: this works
625
+ like addition but if both objects contain a value for the
626
+ same key, and the values are objects, the two are merged with
627
+ the same strategy.
628
+
629
+ examples:
630
+ - program: '10 / . * 3'
631
+ input: 5
632
+ output: [6]
633
+ - program: '. / ", "'
634
+ input: '"a, b,c,d, e"'
635
+ output: ['["a","b,c,d","e"]']
636
+ - program: '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'
637
+ input: 'null'
638
+ output: ['{"k": {"a": 0, "b": 2, "c": 3}}']
639
+ - program: '.[] | (1 / .)?'
640
+ input: '[1,0,-1]'
641
+ output: ['1', '-1']
642
+
643
+
644
+ - title: "`length`"
645
+ body: |
646
+
647
+ The builtin function `length` gets the length of various
648
+ different types of value:
649
+
650
+ - The length of a **string** is the number of Unicode
651
+ codepoints it contains (which will be the same as its
652
+ JSON-encoded length in bytes if it's pure ASCII).
653
+
654
+ - The length of an **array** is the number of elements.
655
+
656
+ - The length of an **object** is the number of key-value pairs.
657
+
658
+ - The length of **null** is zero.
659
+
660
+ examples:
661
+ - program: '.[] | length'
662
+ input: '[[1,2], "string", {"a":2}, null]'
663
+ output: [2, 6, 1, 0]
664
+
665
+ - title: "`keys`, `keys_unsorted`"
666
+ body: |
667
+
668
+ The builtin function `keys`, when given an object, returns
669
+ its keys in an array.
670
+
671
+ The keys are sorted "alphabetically", by unicode codepoint
672
+ order. This is not an order that makes particular sense in
673
+ any particular language, but you can count on it being the
674
+ same for any two objects with the same set of keys,
675
+ regardless of locale settings.
676
+
677
+ When `keys` is given an array, it returns the valid indices
678
+ for that array: the integers from 0 to length-1.
679
+
680
+ The `keys_unsorted` function is just like `keys`, but if
681
+ the input is an object then the keys will not be sorted,
682
+ instead the keys will roughly be in insertion order.
683
+
684
+ examples:
685
+ - program: 'keys'
686
+ input: '{"abc": 1, "abcd": 2, "Foo": 3}'
687
+ output: ['["Foo", "abc", "abcd"]']
688
+ - program: 'keys'
689
+ input: '[42,3,35]'
690
+ output: ['[0,1,2]']
691
+
692
+ - title: "`has(key)`"
693
+ body: |
694
+
695
+ The builtin function `has` returns whether the input object
696
+ has the given key, or the input array has an element at the
697
+ given index.
698
+
699
+ `has($key)` has the same effect as checking whether `$key`
700
+ is a member of the array returned by `keys`, although `has`
701
+ will be faster.
702
+
703
+ examples:
704
+ - program: 'map(has("foo"))'
705
+ input: '[{"foo": 42}, {}]'
706
+ output: ['[true, false]']
707
+ - program: 'map(has(2))'
708
+ input: '[[0,1], ["a","b","c"]]'
709
+ output: ['[false, true]']
710
+
711
+ - title: "`in`"
712
+ body: |
713
+
714
+ The builtin function `in` returns the input key is in the
715
+ given object, or the input index corresponds to an element
716
+ in the given array. It is, essentially, an inversed version
717
+ of `has`.
718
+
719
+ examples:
720
+ - program: '.[] | in({"foo": 42})'
721
+ input: '["foo", "bar"]'
722
+ output: ['true', 'false']
723
+ - program: 'map(in([0,1]))'
724
+ input: '[2, 0]'
725
+ output: ['[false, true]']
726
+
727
+ - title: "`path(path_expression)`"
728
+ body: |
729
+
730
+ Outputs array representations of the given path expression
731
+ in `.`. The outputs are arrays of strings (keys in objects0
732
+ and/or numbers (array indices.
733
+
734
+ Path expressions are jq expressions like `.a`, but also `.[]`.
735
+ There are two types of path expressions: ones that can match
736
+ exactly, and ones that cannot. For example, `.a.b.c` is an
737
+ exact match path expression, while `.a[].b` is not.
738
+
739
+ `path(exact_path_expression)` will produce the array
740
+ representation of the path expression even if it does not
741
+ exist in `.`, if `.` is `null` or an array or an object.
742
+
743
+ `path(pattern)` will produce array representations of the
744
+ paths matching `pattern` if the paths exist in `.`.
745
+
746
+ Note that the path expressions are not different from normal
747
+ expressions. The expression
748
+ `path(..|select(type=="boolean"))` outputs all the paths to
749
+ boolean values in `.`, and only those paths.
750
+
751
+ examples:
752
+ - program: 'path(.a[0].b)'
753
+ input: 'null'
754
+ output: ['["a",0,"b"]']
755
+ - program: '[path(..)]'
756
+ input: '{"a":[{"b":1}]}'
757
+ output: ['[[],["a"],["a",0],["a",0,"b"]]']
758
+
759
+ - title: "`del(path_expression)`"
760
+ body: |
761
+
762
+ The builtin function `del` removes a key and its corresponding
763
+ value from an object.
764
+
765
+ examples:
766
+ - program: 'del(.foo)'
767
+ input: '{"foo": 42, "bar": 9001, "baz": 42}'
768
+ output: ['{"bar": 9001, "baz": 42}']
769
+ - program: 'del(.[1, 2])'
770
+ input: '["foo", "bar", "baz"]'
771
+ output: ['["foo"]']
772
+
773
+ - title: "`to_entries`, `from_entries`, `with_entries`"
774
+ body: |
775
+
776
+ These functions convert between an object and an array of
777
+ key-value pairs. If `to_entries` is passed an object, then
778
+ for each `k: v` entry in the input, the output array
779
+ includes `{"key": k, "value": v}`.
780
+
781
+ `from_entries` does the opposite conversion, and
782
+ `with_entries(foo)` is a shorthand for `to_entries |
783
+ map(foo) | from_entries`, useful for doing some operation to
784
+ all keys and values of an object. `from_entries` accepts key, Key,
785
+ Name, value and Value as keys.
786
+
787
+ examples:
788
+ - program: 'to_entries'
789
+ input: '{"a": 1, "b": 2}'
790
+ output: ['[{"key":"a", "value":1}, {"key":"b", "value":2}]']
791
+ - program: 'from_entries'
792
+ input: '[{"key":"a", "value":1}, {"key":"b", "value":2}]'
793
+ output: ['{"a": 1, "b": 2}']
794
+ - program: 'with_entries(.key |= "KEY_" + .)'
795
+ input: '{"a": 1, "b": 2}'
796
+ output: ['{"KEY_a": 1, "KEY_b": 2}']
797
+
798
+
799
+ - title: "`select(boolean_expression)`"
800
+ body: |
801
+
802
+ The function `select(foo)` produces its input unchanged if
803
+ `foo` returns true for that input, and produces no output
804
+ otherwise.
805
+
806
+ It's useful for filtering lists: `[1,2,3] | map(select(. >= 2))`
807
+ will give you `[2,3]`.
808
+
809
+ examples:
810
+ - program: 'map(select(. >= 2))'
811
+ input: '[1,5,3,0,7]'
812
+ output: ['[5,3,7]']
813
+ - program: '.[] | select(.id == "second")'
814
+ input: '[{"id": "first", "val": 1}, {"id": "second", "val": 2}]'
815
+ output: ['{"id": "second", "val": 2}']
816
+
817
+
818
+ - title: "`arrays`, `objects`, `iterables`, `booleans`, `numbers`, `normals`, `finites`, `strings`, `nulls`, `values`, `scalars`"
819
+ body: |
820
+
821
+ These built-ins select only inputs that are arrays, objects,
822
+ iterables (arrays or objects), booleans, numbers, normal
823
+ numbers, finite numbers, strings, null, non-null values, and
824
+ non-iterables, respectively.
825
+
826
+ examples:
827
+ - program: '.[]|numbers'
828
+ input: '[[],{},1,"foo",null,true,false]'
829
+ output: ['1']
830
+
831
+ - title: "`empty`"
832
+ body: |
833
+
834
+ `empty` returns no results. None at all. Not even `null`.
835
+
836
+ It's useful on occasion. You'll know if you need it :)
837
+
838
+ examples:
839
+ - program: '1, empty, 2'
840
+ input: 'null'
841
+ output: [1, 2]
842
+ - program: '[1,2,empty,3]'
843
+ input: 'null'
844
+ output: ['[1,2,3]']
845
+
846
+ - title: "`error(message)`"
847
+ body: |
848
+
849
+ Produces an error, just like `.a` applied to values other than
850
+ null and objects would, but with the given message as the
851
+ error's value.
852
+
853
+ - title: "`$__loc__`"
854
+ body: |
855
+
856
+ Produces an object with a "file" key and a "line" key, with
857
+ the filename and line number where `$__loc__` occurs, as
858
+ values.
859
+
860
+ examples:
861
+ - program: 'try error("\($__loc__)") catch .'
862
+ input: 'null'
863
+ output: ['"{\"file\":\"<top-level>\",\"line\":1}"']
864
+
865
+ - title: "`map(x)`, `map_values(x)`"
866
+ body: |
867
+
868
+ For any filter `x`, `map(x)` will run that filter for each
869
+ element of the input array, and produce the outputs a new
870
+ array. `map(.+1)` will increment each element of an array of numbers.
871
+
872
+ Similarly, `map_values(x)` will run that filter for each element,
873
+ but it will return an object when an object is passed.
874
+
875
+ `map(x)` is equivalent to `[.[] | x]`. In fact, this is how
876
+ it's defined. Similarly, `map_values(x)` is defined as `.[] |= x`.
877
+
878
+ examples:
879
+ - program: 'map(.+1)'
880
+ input: '[1,2,3]'
881
+ output: ['[2,3,4]']
882
+
883
+ - program: 'map_values(.+1)'
884
+ input: '{"a": 1, "b": 2, "c": 3}'
885
+ output: ['{"a": 2, "b": 3, "c": 4}']
886
+
887
+ - title: "`paths`, `paths(node_filter)`, `leaf_paths`"
888
+ body: |
889
+
890
+ `paths` outputs the paths to all the elements in its input
891
+ (except it does not output the empty list, representing .
892
+ itself).
893
+
894
+ `paths(f)` outputs the paths to any values for which `f` is true.
895
+ That is, `paths(numbers)` outputs the paths to all numeric
896
+ values.
897
+
898
+ `leaf_paths` is an alias of `paths(scalars)`; `leaf_paths` is
899
+ *deprecated* and will be removed in the next major release.
900
+
901
+ examples:
902
+ - program: '[paths]'
903
+ input: '[1,[[],{"a":2}]]'
904
+ output: ['[[0],[1],[1,0],[1,1],[1,1,"a"]]']
905
+ - program: '[paths(scalars)]'
906
+ input: '[1,[[],{"a":2}]]'
907
+ output: ['[[0],[1,1,"a"]]']
908
+
909
+ - title: "`add`"
910
+ body: |
911
+
912
+ The filter `add` takes as input an array, and produces as
913
+ output the elements of the array added together. This might
914
+ mean summed, concatenated or merged depending on the types
915
+ of the elements of the input array - the rules are the same
916
+ as those for the `+` operator (described above).
917
+
918
+ If the input is an empty array, `add` returns `null`.
919
+
920
+ examples:
921
+ - program: add
922
+ input: '["a","b","c"]'
923
+ output: ['"abc"']
924
+ - program: add
925
+ input: '[1, 2, 3]'
926
+ output: [6]
927
+ - program: add
928
+ input: '[]'
929
+ output: ["null"]
930
+
931
+ - title: "`any`, `any(condition)`, `any(generator; condition)`"
932
+ body: |
933
+
934
+ The filter `any` takes as input an array of boolean values,
935
+ and produces `true` as output if any of the the elements of
936
+ the array is `true`.
937
+
938
+ If the input is an empty array, `any` returns `false`.
939
+
940
+ The `any(condition)` form applies the given condition to the
941
+ elements of the input array.
942
+
943
+ The `any(generator; condition)` form applies the given
944
+ condition to all the outputs of the given generator.
945
+
946
+ examples:
947
+ - program: any
948
+ input: '[true, false]'
949
+ output: ["true"]
950
+ - program: any
951
+ input: '[false, false]'
952
+ output: ["false"]
953
+ - program: any
954
+ input: '[]'
955
+ output: ["false"]
956
+
957
+ - title: "`all`, `all(condition)`, `all(generator; condition)`"
958
+ body: |
959
+
960
+ The filter `all` takes as input an array of boolean values,
961
+ and produces `true` as output if all of the the elements of
962
+ the array are `true`.
963
+
964
+ The `all(condition)` form applies the given condition to the
965
+ elements of the input array.
966
+
967
+ The `all(generator; condition)` form applies the given
968
+ condition to all the outputs of the given generator.
969
+
970
+ If the input is an empty array, `all` returns `true`.
971
+
972
+ examples:
973
+ - program: all
974
+ input: '[true, false]'
975
+ output: ["false"]
976
+ - program: all
977
+ input: '[true, true]'
978
+ output: ["true"]
979
+ - program: all
980
+ input: '[]'
981
+ output: ["true"]
982
+
983
+ - title: "\\[Requires 1.5\\] `flatten`, `flatten(depth)`"
984
+ body: |
985
+
986
+ The filter `flatten` takes as input an array of nested arrays,
987
+ and produces a flat array in which all arrays inside the original
988
+ array have been recursively replaced by their values. You can pass
989
+ an argument to it to specify how many levels of nesting to flatten.
990
+
991
+ `flatten(2)` is like `flatten`, but going only up to two
992
+ levels deep.
993
+
994
+ examples:
995
+ - program: flatten
996
+ input: '[1, [2], [[3]]]'
997
+ output: ["[1, 2, 3]"]
998
+ - program: flatten(1)
999
+ input: '[1, [2], [[3]]]'
1000
+ output: ["[1, 2, [3]]"]
1001
+ - program: flatten
1002
+ input: '[[]]'
1003
+ output: ["[]"]
1004
+ - program: flatten
1005
+ input: '[{"foo": "bar"}, [{"foo": "baz"}]]'
1006
+ output: ['[{"foo": "bar"}, {"foo": "baz"}]']
1007
+
1008
+ - title: "`range(upto)`, `range(from;upto)` `range(from;upto;by)`"
1009
+ body: |
1010
+
1011
+ The `range` function produces a range of numbers. `range(4;10)`
1012
+ produces 6 numbers, from 4 (inclusive) to 10 (exclusive). The numbers
1013
+ are produced as separate outputs. Use `[range(4;10)]` to get a range as
1014
+ an array.
1015
+
1016
+ The one argument form generates numbers from 0 to the given
1017
+ number, with an increment of 1.
1018
+
1019
+ The two argument form generates numbers from `from` to `upto`
1020
+ with an increment of 1.
1021
+
1022
+ The three argument form generates numbers `from` to `upto`
1023
+ with an increment of `by`.
1024
+
1025
+ examples:
1026
+ - program: 'range(2;4)'
1027
+ input: 'null'
1028
+ output: ['2', '3']
1029
+ - program: '[range(2;4)]'
1030
+ input: 'null'
1031
+ output: ['[2,3]']
1032
+ - program: '[range(4)]'
1033
+ input: 'null'
1034
+ output: ['[0,1,2,3]']
1035
+ - program: '[range(0;10;3)]'
1036
+ input: 'null'
1037
+ output: ['[0,3,6,9]']
1038
+ - program: '[range(0;10;-1)]'
1039
+ input: 'null'
1040
+ output: ['[]']
1041
+ - program: '[range(0;-5;-1)]'
1042
+ input: 'null'
1043
+ output: ['[0,-1,-2,-3,-4]']
1044
+
1045
+ - title: "`floor`"
1046
+ body: |
1047
+
1048
+ The `floor` function returns the floor of its numeric input.
1049
+
1050
+ examples:
1051
+ - program: 'floor'
1052
+ input: '3.14159'
1053
+ output: ['3']
1054
+
1055
+ - title: "`sqrt`"
1056
+ body: |
1057
+
1058
+ The `sqrt` function returns the square root of its numeric input.
1059
+
1060
+ examples:
1061
+ - program: 'sqrt'
1062
+ input: '9'
1063
+ output: ['3']
1064
+
1065
+ - title: "`tonumber`"
1066
+ body: |
1067
+
1068
+ The `tonumber` function parses its input as a number. It
1069
+ will convert correctly-formatted strings to their numeric
1070
+ equivalent, leave numbers alone, and give an error on all other input.
1071
+
1072
+ examples:
1073
+ - program: '.[] | tonumber'
1074
+ input: '[1, "1"]'
1075
+ output: [1, 1]
1076
+
1077
+ - title: "`tostring`"
1078
+ body: |
1079
+
1080
+ The `tostring` function prints its input as a
1081
+ string. Strings are left unchanged, and all other values are
1082
+ JSON-encoded.
1083
+
1084
+ examples:
1085
+ - program: '.[] | tostring'
1086
+ input: '[1, "1", [1]]'
1087
+ output: ['"1"', '"1"', '"[1]"']
1088
+
1089
+ - title: "`type`"
1090
+ body: |
1091
+
1092
+ The `type` function returns the type of its argument as a
1093
+ string, which is one of null, boolean, number, string, array
1094
+ or object.
1095
+
1096
+ examples:
1097
+ - program: 'map(type)'
1098
+ input: '[0, false, [], {}, null, "hello"]'
1099
+ output: ['["number", "boolean", "array", "object", "null", "string"]']
1100
+
1101
+ - title: "`infinite`, `nan`, `isinfinite`, `isnan`, `isfinite`, `isnormal`"
1102
+ body: |
1103
+
1104
+ Some arithmetic operations can yield infinities and "not a
1105
+ number" (NaN) values. The `isinfinite` builtin returns `true`
1106
+ if its input is infinite. The `isnan` builtin returns `true`
1107
+ if its input is a NaN. The `infinite` builtin returns a
1108
+ positive infinite value. The `nan` builtin returns a NaN.
1109
+ The `isnormal` builtin returns true if its input is a normal
1110
+ number.
1111
+
1112
+ Note that division by zero raises an error.
1113
+
1114
+ Currently most arithmetic operations operating on infinities,
1115
+ NaNs, and sub-normals do not raise errors.
1116
+
1117
+ examples:
1118
+ - program: '.[] | (infinite * .) < 0'
1119
+ input: '[-1, 1]'
1120
+ output: ['true', 'false']
1121
+ - program: 'infinite, nan | type'
1122
+ input: 'null'
1123
+ output: ['"number"', '"number"']
1124
+
1125
+ - title: "`sort, sort_by(path_expression)`"
1126
+ body: |
1127
+
1128
+ The `sort` functions sorts its input, which must be an
1129
+ array. Values are sorted in the following order:
1130
+
1131
+ * `null`
1132
+ * `false`
1133
+ * `true`
1134
+ * numbers
1135
+ * strings, in alphabetical order (by unicode codepoint value)
1136
+ * arrays, in lexical order
1137
+ * objects
1138
+
1139
+ The ordering for objects is a little complex: first they're
1140
+ compared by comparing their sets of keys (as arrays in
1141
+ sorted order), and if their keys are equal then the values
1142
+ are compared key by key.
1143
+
1144
+ `sort` may be used to sort by a particular field of an
1145
+ object, or by applying any jq filter.
1146
+
1147
+ `sort_by(foo)` compares two elements by comparing the result of
1148
+ `foo` on each element.
1149
+
1150
+ examples:
1151
+ - program: 'sort'
1152
+ input: '[8,3,null,6]'
1153
+ output: ['[null,3,6,8]']
1154
+ - program: 'sort_by(.foo)'
1155
+ input: '[{"foo":4, "bar":10}, {"foo":3, "bar":100}, {"foo":2, "bar":1}]'
1156
+ output: ['[{"foo":2, "bar":1}, {"foo":3, "bar":100}, {"foo":4, "bar":10}]']
1157
+
1158
+ - title: "`group_by(path_expression)`"
1159
+ body: |
1160
+
1161
+ `group_by(.foo)` takes as input an array, groups the
1162
+ elements having the same `.foo` field into separate arrays,
1163
+ and produces all of these arrays as elements of a larger
1164
+ array, sorted by the value of the `.foo` field.
1165
+
1166
+ Any jq expression, not just a field access, may be used in
1167
+ place of `.foo`. The sorting order is the same as described
1168
+ in the `sort` function above.
1169
+
1170
+ examples:
1171
+ - program: 'group_by(.foo)'
1172
+ input: '[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]'
1173
+ output: ['[[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]']
1174
+
1175
+ - title: "`min`, `max`, `min_by(path_exp)`, `max_by(path_exp)`"
1176
+ body: |
1177
+
1178
+ Find the minimum or maximum element of the input array.
1179
+
1180
+ The `min_by(path_exp)` and `max_by(path_exp)` functions allow
1181
+ you to specify a particular field or property to examine, e.g.
1182
+ `min_by(.foo)` finds the object with the smallest `foo` field.
1183
+
1184
+ examples:
1185
+ - program: 'min'
1186
+ input: '[5,4,2,7]'
1187
+ output: ['2']
1188
+ - program: 'max_by(.foo)'
1189
+ input: '[{"foo":1, "bar":14}, {"foo":2, "bar":3}]'
1190
+ output: ['{"foo":2, "bar":3}']
1191
+
1192
+ - title: "`unique`, `unique_by(path_exp)`"
1193
+ body: |
1194
+
1195
+ The `unique` function takes as input an array and produces
1196
+ an array of the same elements, in sorted order, with
1197
+ duplicates removed.
1198
+
1199
+ The `unique_by(path_exp)` function will keep only one element
1200
+ for each value obtained by applying the argument. Think of it
1201
+ as making an array by taking one element out of every group
1202
+ produced by `group`.
1203
+
1204
+ examples:
1205
+ - program: 'unique'
1206
+ input: '[1,2,5,3,5,3,1,3]'
1207
+ output: ['[1,2,3,5]']
1208
+ - program: 'unique_by(.foo)'
1209
+ input: '[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]'
1210
+ output: ['[{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]']
1211
+ - program: 'unique_by(length)'
1212
+ input: '["chunky", "bacon", "kitten", "cicada", "asparagus"]'
1213
+ output: ['["bacon", "chunky", "asparagus"]']
1214
+
1215
+ - title: "`reverse`"
1216
+ body: |
1217
+
1218
+ This function reverses an array.
1219
+
1220
+ examples:
1221
+ - program: 'reverse'
1222
+ input: '[1,2,3,4]'
1223
+ output: ['[4,3,2,1]']
1224
+
1225
+ - title: "`contains(element)`"
1226
+ body: |
1227
+
1228
+ The filter `contains(b)` will produce true if b is
1229
+ completely contained within the input. A string B is
1230
+ contained in a string A if B is a substring of A. An array B
1231
+ is contained in an array A if all elements in B are
1232
+ contained in any element in A. An object B is contained in
1233
+ object A if all of the values in B are contained in the
1234
+ value in A with the same key. All other types are assumed to
1235
+ be contained in each other if they are equal.
1236
+
1237
+ examples:
1238
+ - program: 'contains("bar")'
1239
+ input: '"foobar"'
1240
+ output: ['true']
1241
+ - program: 'contains(["baz", "bar"])'
1242
+ input: '["foobar", "foobaz", "blarp"]'
1243
+ output: ['true']
1244
+ - program: 'contains(["bazzzzz", "bar"])'
1245
+ input: '["foobar", "foobaz", "blarp"]'
1246
+ output: ['false']
1247
+ - program: 'contains({foo: 12, bar: [{barp: 12}]})'
1248
+ input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'
1249
+ output: ['true']
1250
+ - program: 'contains({foo: 12, bar: [{barp: 15}]})'
1251
+ input: '{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}'
1252
+ output: ['false']
1253
+
1254
+ - title: "`indices(s)`"
1255
+ body: |
1256
+
1257
+ Outputs an array containing the indices in `.` where `s`
1258
+ occurs. The input may be an array, in which case if `s` is an
1259
+ array then the indices output will be those where all elements
1260
+ in `.` match those of `s`.
1261
+
1262
+ examples:
1263
+ - program: 'indices(", ")'
1264
+ input: '"a,b, cd, efg, hijk"'
1265
+ output: ['[3,7,12]']
1266
+ - program: 'indices(1)'
1267
+ input: '[0,1,2,1,3,1,4]'
1268
+ output: ['[1,3,5]']
1269
+ - program: 'indices([1,2])'
1270
+ input: '[0,1,2,3,1,4,2,5,1,2,6,7]'
1271
+ output: ['[1,8]']
1272
+
1273
+ - title: "`index(s)`, `rindex(s)`"
1274
+ body: |
1275
+
1276
+ Outputs the index of the first (`index`) or last (`rindex`)
1277
+ occurrence of `s` in the input.
1278
+
1279
+ examples:
1280
+ - program: 'index(", ")'
1281
+ input: '"a,b, cd, efg, hijk"'
1282
+ output: ['3']
1283
+ - program: 'rindex(", ")'
1284
+ input: '"a,b, cd, efg, hijk"'
1285
+ output: ['12']
1286
+
1287
+ - title: "`inside`"
1288
+ body: |
1289
+
1290
+ The filter `inside(b)` will produce true if the input is
1291
+ completely contained within b. It is, essentially, an
1292
+ inversed version of `contains`.
1293
+
1294
+ examples:
1295
+ - program: 'inside("foobar")'
1296
+ input: '"bar"'
1297
+ output: ['true']
1298
+ - program: 'inside(["foobar", "foobaz", "blarp"])'
1299
+ input: '["baz", "bar"]'
1300
+ output: ['true']
1301
+ - program: 'inside(["foobar", "foobaz", "blarp"])'
1302
+ input: '["bazzzzz", "bar"]'
1303
+ output: ['false']
1304
+ - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'
1305
+ input: '{"foo": 12, "bar": [{"barp": 12}]}'
1306
+ output: ['true']
1307
+ - program: 'inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})'
1308
+ input: '{"foo": 12, "bar": [{"barp": 15}]}'
1309
+ output: ['false']
1310
+
1311
+ - title: "`startswith(str)`"
1312
+ body: |
1313
+
1314
+ Outputs `true` if . starts with the given string argument.
1315
+
1316
+ examples:
1317
+ - program: '[.[]|startswith("foo")]'
1318
+ input: '["fo", "foo", "barfoo", "foobar", "barfoob"]'
1319
+ output: ['[false, true, false, true, false]']
1320
+
1321
+ - title: "`endswith(str)`"
1322
+ body: |
1323
+
1324
+ Outputs `true` if . ends with the given string argument.
1325
+
1326
+ examples:
1327
+ - program: '[.[]|endswith("foo")]'
1328
+ input: '["foobar", "barfoo"]'
1329
+ output: ['[false, true]']
1330
+
1331
+ - title: "`combinations`, `combinations(n)`"
1332
+ body: |
1333
+
1334
+ Outputs all combinations of the elements of the arrays in the
1335
+ input array. If given an argument `n`, it outputs all combinations
1336
+ of `n` repetitions of the input array.
1337
+
1338
+ examples:
1339
+ - program: 'combinations'
1340
+ input: '[[1,2], [3, 4]]'
1341
+ output: ['[1, 3]', '[1, 4]', '[2, 3]', '[2, 4]']
1342
+ - program: 'combinations(2)'
1343
+ input: '[0, 1]'
1344
+ output: ['[0, 0]', '[0, 1]', '[1, 0]', '[1, 1]']
1345
+
1346
+ - title: "`ltrimstr(str)`"
1347
+ body: |
1348
+
1349
+ Outputs its input with the given prefix string removed, if it
1350
+ starts with it.
1351
+
1352
+ examples:
1353
+ - program: '[.[]|ltrimstr("foo")]'
1354
+ input: '["fo", "foo", "barfoo", "foobar", "afoo"]'
1355
+ output: ['["fo","","barfoo","bar","afoo"]']
1356
+
1357
+ - title: "`rtrimstr(str)`"
1358
+ body: |
1359
+
1360
+ Outputs its input with the given suffix string removed, if it
1361
+ ends with it.
1362
+
1363
+ examples:
1364
+ - program: '[.[]|rtrimstr("foo")]'
1365
+ input: '["fo", "foo", "barfoo", "foobar", "foob"]'
1366
+ output: ['["fo","","bar","foobar","foob"]']
1367
+
1368
+ - title: "`explode`"
1369
+ body: |
1370
+
1371
+ Converts an input string into an array of the string's
1372
+ codepoint numbers.
1373
+
1374
+ examples:
1375
+ - program: 'explode'
1376
+ input: '"foobar"'
1377
+ output: ['[102,111,111,98,97,114]']
1378
+
1379
+ - title: "`implode`"
1380
+ body: |
1381
+
1382
+ The inverse of explode.
1383
+
1384
+ examples:
1385
+ - program: 'implode'
1386
+ input: '[65, 66, 67]'
1387
+ output: ['"ABC"']
1388
+
1389
+ - title: "`split`"
1390
+ body: |
1391
+
1392
+ Splits an input string on the separator argument.
1393
+
1394
+ examples:
1395
+ - program: 'split(", ")'
1396
+ input: '"a, b,c,d, e, "'
1397
+ output: ['["a","b,c,d","e",""]']
1398
+
1399
+ - title: "`join(str)`"
1400
+ body: |
1401
+
1402
+ Joins the array of elements given as input, using the
1403
+ argument as separator. It is the inverse of `split`: that is,
1404
+ running `split("foo") | join("foo")` over any input string
1405
+ returns said input string.
1406
+
1407
+ examples:
1408
+ - program: 'join(", ")'
1409
+ input: '["a","b,c,d","e"]'
1410
+ output: ['"a, b,c,d, e"']
1411
+
1412
+
1413
+ - title: "`ascii_downcase`, `ascii_upcase`"
1414
+ body: |
1415
+
1416
+ Emit a copy of the input string with its alphabetic characters (a-z and A-Z)
1417
+ converted to the specified case.
1418
+
1419
+ example:
1420
+ - program: 'ascii_upcase'
1421
+ input: '"useful but not for é"'
1422
+ output: '"USEFUL BUT NOT FOR é"'
1423
+
1424
+ - title: "`while(cond; update)`"
1425
+ body: |
1426
+
1427
+ The `while(cond; update)` function allows you to repeatedly
1428
+ apply an update to `.` until `cond` is false.
1429
+
1430
+ Note that `while(cond; update)` is internally defined as a
1431
+ recursive jq function. Recursive calls within `while` will
1432
+ not consume additional memory if `update` produces at most one
1433
+ output for each input. See advanced topics below.
1434
+
1435
+ examples:
1436
+ - program: '[while(.<100; .*2)]'
1437
+ input: '1'
1438
+ output: ['[1,2,4,8,16,32,64]']
1439
+
1440
+ - title: "`until(cond; next)`"
1441
+ body: |
1442
+
1443
+ The `until(cond; next)` function allows you to repeatedly
1444
+ apply the expression `next`, initially to `.` then to its own
1445
+ output, until `cond` is true. For example, this can be used
1446
+ to implement a factorial function (see below).
1447
+
1448
+ Note that `until(cond; next)` is internally defined as a
1449
+ recursive jq function. Recursive calls within `until()` will
1450
+ not consume additional memory if `next` produces at most one
1451
+ output for each input. See advanced topics below.
1452
+
1453
+ examples:
1454
+ - program: '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'
1455
+ input: '4'
1456
+ output: ['24']
1457
+
1458
+
1459
+ - title: "`recurse(f)`, `recurse`, `recurse(f; condition)`, `recurse_down`"
1460
+ body: |
1461
+
1462
+ The `recurse(f)` function allows you to search through a
1463
+ recursive structure, and extract interesting data from all
1464
+ levels. Suppose your input represents a filesystem:
1465
+
1466
+ {"name": "/", "children": [
1467
+ {"name": "/bin", "children": [
1468
+ {"name": "/bin/ls", "children": []},
1469
+ {"name": "/bin/sh", "children": []}]},
1470
+ {"name": "/home", "children": [
1471
+ {"name": "/home/stephen", "children": [
1472
+ {"name": "/home/stephen/jq", "children": []}]}]}]}
1473
+
1474
+ Now suppose you want to extract all of the filenames
1475
+ present. You need to retrieve `.name`, `.children[].name`,
1476
+ `.children[].children[].name`, and so on. You can do this
1477
+ with:
1478
+
1479
+ recurse(.children[]) | .name
1480
+
1481
+ When called without an argument, `recurse` is equivalent to
1482
+ `recurse(.[]?)`.
1483
+
1484
+ `recurse(f)` is identical to `recurse(f; . != null)` and can be
1485
+ used without concerns about recursion depth.
1486
+
1487
+ `recurse(f; condition)` is a generator which begins by
1488
+ emitting . and then emits in turn .|f, .|f|f, .|f|f|f, ... so long
1489
+ as the computed value satisfies the condition. For example,
1490
+ to generate all the integers, at least in principle, one
1491
+ could write `recurse(.+1; true)`.
1492
+
1493
+ For legacy reasons, `recurse_down` exists as an alias to
1494
+ calling `recurse` without arguments. This alias is considered
1495
+ *deprecated* and will be removed in the next major release.
1496
+
1497
+ The recursive calls in `recurse` will not consume additional
1498
+ memory whenever `f` produces at most a single output for each
1499
+ input.
1500
+
1501
+ examples:
1502
+ - program: 'recurse(.foo[])'
1503
+ input: '{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}'
1504
+ output:
1505
+ - '{"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}'
1506
+ - '{"foo":[]}'
1507
+ - '{"foo":[{"foo":[]}]}'
1508
+ - '{"foo":[]}'
1509
+
1510
+ - program: 'recurse'
1511
+ input: '{"a":0,"b":[1]}'
1512
+ output:
1513
+ - '{"a":0,"b":[1]}'
1514
+ - '0'
1515
+ - '[1]'
1516
+ - '1'
1517
+
1518
+ - program: 'recurse(. * .; . < 20)'
1519
+ input: 2
1520
+ output:
1521
+ - 2
1522
+ - 4
1523
+ - 16
1524
+
1525
+ - title: "`..`"
1526
+ body: |
1527
+
1528
+ Short-hand for `recurse` without arguments. This is intended
1529
+ to resemble the XPath `//` operator. Note that `..a` does not
1530
+ work; use `..|a` instead. In the example below we use
1531
+ `..|.a?` to find all the values of object keys "a" in any
1532
+ object found "below" `.`.
1533
+
1534
+ examples:
1535
+ - program: '..|.a?'
1536
+ input: '[[{"a":1}]]'
1537
+ output: ['1']
1538
+
1539
+ - title: "`env`"
1540
+ body: |
1541
+
1542
+ Outputs an object representing jq's environment.
1543
+
1544
+ examples:
1545
+ - program: 'env.PAGER'
1546
+ input: 'null'
1547
+ output: ['"less"']
1548
+
1549
+ - title: "`transpose`"
1550
+ body: |
1551
+
1552
+ Transpose a possibly jagged matrix (an array of arrays).
1553
+ Rows are padded with nulls so the result is always rectangular.
1554
+
1555
+ examples:
1556
+ - program: 'transpose'
1557
+ input: '[[1], [2,3]]'
1558
+ output: ['[[1,2],[null,3]]']
1559
+
1560
+ - title: "`bsearch(x)`"
1561
+ body: |
1562
+
1563
+ bsearch(x) conducts a binary search for x in the input
1564
+ array. If the input is sorted and contains x, then
1565
+ bsearch(x) will return its index in the array; otherwise, if
1566
+ the array is sorted, it will return (-1 - ix) where ix is an
1567
+ insertion point such that the array would still be sorted
1568
+ after the insertion of x at ix. If the array is not sorted,
1569
+ bsearch(x) will return an integer that is probably of no
1570
+ interest.
1571
+
1572
+ examples:
1573
+ - program: 'bsearch(0)'
1574
+ input: '[0,1]'
1575
+ output: ['0']
1576
+ - program: 'bsearch(0)'
1577
+ input: '[1,2,3]'
1578
+ output: ['-1']
1579
+ - program: 'bsearch(4) as $ix | if $ix < 0 then .[-(1+$ix)] = 4 else . end'
1580
+ input: '[1,2,3]'
1581
+ output: ['[1,2,3,4]']
1582
+
1583
+ - title: "String interpolation - `\\(foo)`"
1584
+ body: |
1585
+
1586
+ Inside a string, you can put an expression inside parens
1587
+ after a backslash. Whatever the expression returns will be
1588
+ interpolated into the string.
1589
+
1590
+ examples:
1591
+ - program: '"The input was \(.), which is one less than \(.+1)"'
1592
+ input: '42'
1593
+ output: ['"The input was 42, which is one less than 43"']
1594
+
1595
+ - title: "Convert to/from JSON"
1596
+ body: |
1597
+
1598
+ The `tojson` and `fromjson` builtins dump values as JSON texts
1599
+ or parse JSON texts into values, respectively. The tojson
1600
+ builtin differs from tostring in that tostring returns strings
1601
+ unmodified, while tojson encodes strings as JSON strings.
1602
+
1603
+ examples:
1604
+ - program: '[.[]|tostring]'
1605
+ input: '[1, "foo", ["foo"]]'
1606
+ output: ['["1","foo","[\"foo\"]"]']
1607
+ - program: '[.[]|tojson]'
1608
+ input: '[1, "foo", ["foo"]]'
1609
+ output: ['["1","\"foo\"","[\"foo\"]"]']
1610
+ - program: '[.[]|tojson|fromjson]'
1611
+ input: '[1, "foo", ["foo"]]'
1612
+ output: ['[1,"foo",["foo"]]']
1613
+
1614
+ - title: "Format strings and escaping"
1615
+ body: |
1616
+
1617
+ The `@foo` syntax is used to format and escape strings,
1618
+ which is useful for building URLs, documents in a language
1619
+ like HTML or XML, and so forth. `@foo` can be used as a
1620
+ filter on its own, the possible escapings are:
1621
+
1622
+ * `@text`:
1623
+
1624
+ Calls `tostring`, see that function for details.
1625
+
1626
+ * `@json`:
1627
+
1628
+ Serializes the input as JSON.
1629
+
1630
+ * `@html`:
1631
+
1632
+ Applies HTML/XML escaping, by mapping the characters
1633
+ `<>&'"` to their entity equivalents `&lt;`, `&gt;`,
1634
+ `&amp;`, `&apos;`, `&quot;`.
1635
+
1636
+ * `@uri`:
1637
+
1638
+ Applies percent-encoding, by mapping all reserved URI
1639
+ characters to a `%XX` sequence.
1640
+
1641
+ * `@csv`:
1642
+
1643
+ The input must be an array, and it is rendered as CSV
1644
+ with double quotes for strings, and quotes escaped by
1645
+ repetition.
1646
+
1647
+ * `@tsv`:
1648
+
1649
+ The input must be an array, and it is rendered as TSV
1650
+ (tab-separated values). Each input array will be printed as
1651
+ a single line. Fields are separated by a single
1652
+ tab (ascii `0x09`). Input characters line-feed (ascii `0x0a`),
1653
+ carriage-return (ascii `0x0d`), tab (ascii `0x09`) and
1654
+ backslash (ascii `0x5c`) will be output as escape sequences
1655
+ `\n`, `\r`, `\t`, `\\` respectively.
1656
+
1657
+ * `@sh`:
1658
+
1659
+ The input is escaped suitable for use in a command-line
1660
+ for a POSIX shell. If the input is an array, the output
1661
+ will be a series of space-separated strings.
1662
+
1663
+ * `@base64`:
1664
+
1665
+ The input is converted to base64 as specified by RFC 4648.
1666
+
1667
+ This syntax can be combined with string interpolation in a
1668
+ useful way. You can follow a `@foo` token with a string
1669
+ literal. The contents of the string literal will *not* be
1670
+ escaped. However, all interpolations made inside that string
1671
+ literal will be escaped. For instance,
1672
+
1673
+ @uri "https://www.google.com/search?q=\(.search)"
1674
+
1675
+ will produce the following output for the input
1676
+ `{"search":"what is jq?"}`:
1677
+
1678
+ "https://www.google.com/search?q=what%20is%20jq%3F"
1679
+
1680
+ Note that the slashes, question mark, etc. in the URL are
1681
+ not escaped, as they were part of the string literal.
1682
+
1683
+ examples:
1684
+ - program: '@html'
1685
+ input: '"This works if x < y"'
1686
+ output: ['"This works if x &lt; y"']
1687
+
1688
+ # - program: '@html "<span>Anonymous said: \(.)</span>"'
1689
+ # input: '"<script>alert(\"lol hax\");</script>"'
1690
+ # output: ["<span>Anonymous said: &lt;script&gt;alert(&quot;lol hax&quot;);&lt;/script&gt;</span>"]
1691
+
1692
+ - program: '@sh "echo \(.)"'
1693
+ input: "\"O'Hara's Ale\""
1694
+ output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]
1695
+
1696
+ - title: "Dates"
1697
+ body: |
1698
+
1699
+ jq provides some basic date handling functionality, with some
1700
+ high-level and low-level builtins. In all cases these
1701
+ builtins deal exclusively with time in UTC.
1702
+
1703
+ The `fromdateiso8601` builtin parses datetimes in the ISO 8601
1704
+ format to a number of seconds since the Unix epoch
1705
+ (1970-01-01T00:00:00Z). The `todateiso8601` builtin does the
1706
+ inverse.
1707
+
1708
+ The `fromdate` builtin parses datetime strings. Currently
1709
+ `fromdate` only supports ISO 8601 datetime strings, but in the
1710
+ future it will attempt to parse datetime strings in more
1711
+ formats.
1712
+
1713
+ The `todate` builtin is an alias for `todateiso8601`.
1714
+
1715
+ The `now` builtin outputs the current time, in seconds since
1716
+ the Unix epoch.
1717
+
1718
+ Low-level jq interfaces to the C-library time functions are
1719
+ also provided: `strptime`, `strftime`, `mktime`, and `gmtime`.
1720
+ Refer to your host operating system's documentation for the
1721
+ format strings used by `strptime` and `strftime`. Note: these
1722
+ are not necessarily stable interfaces in jq, particularly as
1723
+ to their localization functionality.
1724
+
1725
+ The `gmtime` builtin consumes a number of seconds since the
1726
+ Unix epoch and outputs a "broken down time" representation of
1727
+ time as an array of numbers representing (in this order): the
1728
+ year, the month (zero-based), the day of the month, the hour
1729
+ of the day, the minute of the hour, the second of the minute,
1730
+ the day of the week, and the day of the year -- all one-based
1731
+ unless otherwise stated.
1732
+
1733
+ The `mktime` builtin consumes "broken down time"
1734
+ representations of time output by `gmtime` and `strptime`.
1735
+
1736
+ The `strptime(fmt)` builtin parses input strings matching the
1737
+ `fmt` argument. The output is in the "broken down time"
1738
+ representation consumed by `gmtime` and output by `mktime`.
1739
+
1740
+ The `strftime(fmt)` builtin formats a time with the given
1741
+ format.
1742
+
1743
+ The format strings for `strptime` and `strftime` are described
1744
+ in typical C library documentation. The format string for ISO
1745
+ 8601 datetime is `"%Y-%m-%dT%H:%M:%SZ"`.
1746
+
1747
+ jq may not support some or all of this date functionality on
1748
+ some systems.
1749
+
1750
+ examples:
1751
+ - program: 'fromdate'
1752
+ input: '"2015-03-05T23:51:47Z"'
1753
+ output: ['1425599507']
1754
+
1755
+ - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")'
1756
+ input: '"2015-03-05T23:51:47Z"'
1757
+ output: ['[2015,2,5,23,51,47,4,63]']
1758
+
1759
+ - program: 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'
1760
+ input: '"2015-03-05T23:51:47Z"'
1761
+ output: ['1425599507']
1762
+
1763
+ - title: Conditionals and Comparisons
1764
+ entries:
1765
+ - title: "`==`, `!=`"
1766
+ body: |
1767
+
1768
+ The expression 'a == b' will produce 'true' if the result of a and b
1769
+ are equal (that is, if they represent equivalent JSON documents) and
1770
+ 'false' otherwise. In particular, strings are never considered equal
1771
+ to numbers. If you're coming from Javascript, jq's == is like
1772
+ Javascript's === - considering values equal only when they have the
1773
+ same type as well as the same value.
1774
+
1775
+ != is "not equal", and 'a != b' returns the opposite value of 'a == b'
1776
+
1777
+ examples:
1778
+ - program: '.[] == 1'
1779
+ input: '[1, 1.0, "1", "banana"]'
1780
+ output: ['true', 'true', 'false', 'false']
1781
+
1782
+ - title: if-then-else
1783
+ body: |
1784
+
1785
+ `if A then B else C end` will act the same as `B` if `A`
1786
+ produces a value other than false or null, but act the same
1787
+ as `C` otherwise.
1788
+
1789
+ Checking for false or null is a simpler notion of
1790
+ "truthiness" than is found in Javascript or Python, but it
1791
+ means that you'll sometimes have to be more explicit about
1792
+ the condition you want: you can't test whether, e.g. a
1793
+ string is empty using `if .name then A else B end`, you'll
1794
+ need something more like `if (.name | length) > 0 then A else
1795
+ B end` instead.
1796
+
1797
+ If the condition A produces multiple results, it is
1798
+ considered "true" if any of those results is not false or
1799
+ null. If it produces zero results, it's considered false.
1800
+
1801
+ More cases can be added to an if using `elif A then B` syntax.
1802
+
1803
+ examples:
1804
+ - program: |-
1805
+ if . == 0 then
1806
+ "zero"
1807
+ elif . == 1 then
1808
+ "one"
1809
+ else
1810
+ "many"
1811
+ end
1812
+ input: 2
1813
+ output: ['"many"']
1814
+
1815
+ - title: "`>, >=, <=, <`"
1816
+ body: |
1817
+
1818
+ The comparison operators `>`, `>=`, `<=`, `<` return whether
1819
+ their left argument is greater than, greater than or equal
1820
+ to, less than or equal to or less than their right argument
1821
+ (respectively).
1822
+
1823
+ The ordering is the same as that described for `sort`, above.
1824
+
1825
+ examples:
1826
+ - program: '. < 5'
1827
+ input: 2
1828
+ output: ['true']
1829
+
1830
+ - title: and/or/not
1831
+ body: |
1832
+
1833
+ jq supports the normal Boolean operators and/or/not. They have the
1834
+ same standard of truth as if expressions - false and null are
1835
+ considered "false values", and anything else is a "true value".
1836
+
1837
+ If an operand of one of these operators produces multiple
1838
+ results, the operator itself will produce a result for each input.
1839
+
1840
+ `not` is in fact a builtin function rather than an operator,
1841
+ so it is called as a filter to which things can be piped
1842
+ rather than with special syntax, as in `.foo and .bar |
1843
+ not`.
1844
+
1845
+ These three only produce the values "true" and "false", and
1846
+ so are only useful for genuine Boolean operations, rather
1847
+ than the common Perl/Python/Ruby idiom of
1848
+ "value_that_may_be_null or default". If you want to use this
1849
+ form of "or", picking between two values rather than
1850
+ evaluating a condition, see the "//" operator below.
1851
+
1852
+ examples:
1853
+ - program: '42 and "a string"'
1854
+ input: 'null'
1855
+ output: ['true']
1856
+ - program: '(true, false) or false'
1857
+ input: 'null'
1858
+ output: ['true', 'false']
1859
+ # - program: '(true, false) and (true, false)'
1860
+ # input: 'null'
1861
+ # output: ['true', 'false', 'false', 'false']
1862
+ - program: '(true, true) and (true, false)'
1863
+ input: 'null'
1864
+ output: ['true', 'false', 'true', 'false']
1865
+ - program: '[true, false | not]'
1866
+ input: 'null'
1867
+ output: ['[false, true]']
1868
+
1869
+ - title: Alternative operator - `//`
1870
+ body: |
1871
+
1872
+ A filter of the form `a // b` produces the same
1873
+ results as `a`, if `a` produces results other than `false`
1874
+ and `null`. Otherwise, `a // b` produces the same results as `b`.
1875
+
1876
+ This is useful for providing defaults: `.foo // 1` will
1877
+ evaluate to `1` if there's no `.foo` element in the
1878
+ input. It's similar to how `or` is sometimes used in Python
1879
+ (jq's `or` operator is reserved for strictly Boolean
1880
+ operations).
1881
+
1882
+ examples:
1883
+ - program: '.foo // 42'
1884
+ input: '{"foo": 19}'
1885
+ output: [19]
1886
+ - program: '.foo // 42'
1887
+ input: '{}'
1888
+ output: [42]
1889
+
1890
+ - title: try-catch
1891
+ body: |
1892
+
1893
+ Errors can be caught by using `try EXP catch EXP`. The first
1894
+ expression is executed, and if it fails then the second is
1895
+ executed with the error message. The output of the handler,
1896
+ if any, is output as if it had been the output of the
1897
+ expression to try.
1898
+
1899
+ The `try EXP` form uses `empty` as the exception handler.
1900
+
1901
+ examples:
1902
+ - program: 'try .a catch ". is not an object"'
1903
+ input: 'true'
1904
+ output: ['". is not an object"']
1905
+ - program: '[.[]|try .a]'
1906
+ input: '[{}, true, {"a":1}]'
1907
+ output: ['[null, 1]']
1908
+ - program: 'try error("some exception") catch .'
1909
+ input: 'true'
1910
+ output: ['"some exception"']
1911
+
1912
+ - title: Breaking out of control structures
1913
+ body: |
1914
+
1915
+ A convenient use of try/catch is to break out of control
1916
+ structures like `reduce`, `foreach`, `while`, and so on.
1917
+
1918
+ For example:
1919
+
1920
+ # Repeat an expression until it raises "break" as an
1921
+ # error, then stop repeating without re-raising the error.
1922
+ # But if the error caught is not "break" then re-raise it.
1923
+ try repeat(exp) catch .=="break" then empty else error;
1924
+
1925
+ jq has a syntax for named lexical labels to "break" or "go (back) to":
1926
+
1927
+ label $out | ... break $out ...
1928
+
1929
+ The `break $label_name` expression will cause the program to
1930
+ to act as though the nearest (to the left) `label $label_name`
1931
+ produced `empty`.
1932
+
1933
+ The relationship between the `break` and corresponding `label`
1934
+ is lexical: the label has to be "visible" from the break.
1935
+
1936
+ To break out of a `reduce`, for example:
1937
+
1938
+ label $out | reduce .[] as $item (null; if .==false then break $out else ... end)
1939
+
1940
+ The following jq program produces a syntax error:
1941
+
1942
+ break $out
1943
+
1944
+ because no label `$out` is visible.
1945
+
1946
+ - title: "`?` operator"
1947
+ body: |
1948
+
1949
+ The `?` operator, used as `EXP?`, is shorthand for `try EXP`.
1950
+
1951
+ examples:
1952
+ - program: '[.[]|(.a)?]'
1953
+ input: '[{}, true, {"a":1}]'
1954
+ output: ['[null, 1]']
1955
+
1956
+
1957
+ - title: Regular expressions (PCRE)
1958
+ body: |
1959
+
1960
+ jq uses the Oniguruma regular expression library, as do php,
1961
+ ruby, TextMate, Sublime Text, etc, so the description here
1962
+ will focus on jq specifics.
1963
+
1964
+ The jq regex filters are defined so that they can be used using
1965
+ one of these patterns:
1966
+
1967
+ STRING | FILTER( REGEX )
1968
+ STRING | FILTER( REGEX; FLAGS )
1969
+ STRING | FILTER( [REGEX] )
1970
+ STRING | FILTER( [REGEX, FLAGS] )
1971
+
1972
+ where:
1973
+ * STRING, REGEX and FLAGS are jq strings and subject to jq string interpolation;
1974
+ * REGEX, after string interpolation, should be a valid PCRE regex;
1975
+ * FILTER is one of `test`, `match`, or `capture`, as described below.
1976
+
1977
+ FLAGS is a string consisting of one of more of the supported flags:
1978
+
1979
+ * `g` - Global search (find all matches, not just the first)
1980
+ * `i` - Case insensitive search
1981
+ * `m` - Multi line mode ('.' will match newlines)
1982
+ * `n` - Ignore empty matches
1983
+ * `p` - Both s and m modes are enabled
1984
+ * `s` - Single line mode ('^' -> '\A', '$' -> '\Z')
1985
+ * `l` - Find longest possible matches
1986
+ * `x` - Extended regex format (ignore whitespace and comments)
1987
+
1988
+ To match whitespace in an x pattern use an escape such as \s, e.g.
1989
+
1990
+ * test( "a\\sb", "x" ).
1991
+
1992
+ Note that certain flags may also be specified within REGEX, e.g.
1993
+
1994
+ * jq -n '("test", "TEst", "teST", "TEST") | test( "(?i)te(?-i)st" )'
1995
+
1996
+ evaluates to: true, true, false, false.
1997
+
1998
+ entries:
1999
+ - title: "\\[Requires 1.5\\] `test(val)`, `test(regex; flags)`"
2000
+ body: |
2001
+
2002
+ Like `match`, but does not return match objects, only `true` or `false`
2003
+ for whether or not the regex matches the input.
2004
+
2005
+ examples:
2006
+ - program: 'test("foo")'
2007
+ input: '"foo"'
2008
+ output: ['true']
2009
+ - program: '.[] | test("a b c # spaces are ignored"; "ix")'
2010
+ input: '["xabcd", "ABC"]'
2011
+ output: ['true', 'true']
2012
+
2013
+ - title: "\\[Requires 1.5\\] `match(val)`, `match(regex; flags)`"
2014
+ body: |
2015
+
2016
+ **match** outputs an object for each match it finds. Matches have
2017
+ the following fields:
2018
+
2019
+ * `offset` - offset in UTF-8 codepoints from the beginning of the input
2020
+ * `length` - length in UTF-8 codepoints of the match
2021
+ * `string` - the string that it matched
2022
+ * `captures` - an array of objects representing capturing groups.
2023
+
2024
+ Capturing group objects have the following fields:
2025
+
2026
+ * `offset` - offset in UTF-8 codepoints from the beginning of the input
2027
+ * `length` - length in UTF-8 codepoints of this capturing group
2028
+ * `string` - the string that was captured
2029
+ * `name` - the name of the capturing group (or `null` if it was unnamed)
2030
+
2031
+ Capturing groups that did not match anything return an offset of -1
2032
+
2033
+ examples:
2034
+ - program: 'match("(abc)+"; "g")'
2035
+ input: '"abc abc"'
2036
+ output:
2037
+ - '{"offset": 0, "length": 3, "string": "abc", "captures": [{"offset": 0, "length": 3, "string": "abc", "name": null}]}'
2038
+ - '{"offset": 4, "length": 3, "string": "abc", "captures": [{"offset": 4, "length": 3, "string": "abc", "name": null}]}'
2039
+ - program: 'match("foo")'
2040
+ input: '"foo bar foo"'
2041
+ output: ['{"offset": 0, "length": 3, "string": "foo", "captures": []}']
2042
+ - program: 'match(["foo", "ig"])'
2043
+ input: '"foo bar FOO"'
2044
+ output:
2045
+ - '{"offset": 0, "length": 3, "string": "foo", "captures": []}'
2046
+ - '{"offset": 8, "length": 3, "string": "FOO", "captures": []}'
2047
+ - program: 'match("foo (?<bar123>bar)? foo"; "ig")'
2048
+ input: '"foo bar foo foo foo"'
2049
+ output:
2050
+ - '{"offset": 0, "length": 11, "string": "foo bar foo", "captures": [{"offset": 4, "length": 3, "string": "bar", "name": "bar123"}]}'
2051
+ - '{"offset": 12, "length": 8, "string": "foo foo", "captures": [{"offset": -1, "length": 0, "string": null, "name": "bar123"}]}'
2052
+
2053
+ - program: '[ match("."; "g")] | length'
2054
+ input: '"abc"'
2055
+ output: [3]
2056
+
2057
+
2058
+ - title: "\\[Requires 1.5\\] `capture(val)`, `capture(regex; flags)`"
2059
+ body: |
2060
+
2061
+ Collects the named captures in a JSON object, with the name
2062
+ of each capture as the key, and the matched string as the
2063
+ corresponding value.
2064
+
2065
+ examples:
2066
+ - program: 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'
2067
+ input: '"xyzzy-14"'
2068
+ output: ['{ "a": "xyzzy", "n": "14" }']
2069
+
2070
+ - title: "\\[Requires 1.5\\] `scan(regex)`, `scan(regex; flags)`"
2071
+ body: |
2072
+
2073
+ Emit a stream of the non-overlapping substrings of the input
2074
+ that match the regex in accordance with the flags, if any
2075
+ have been specified. If there is no match, the stream is empty.
2076
+ To capture all the matches for each input string, use the idiom
2077
+ `[ expr ]`, e.g. `[ scan(regex) ]`.
2078
+
2079
+ example:
2080
+ - program: 'scan("c")'
2081
+ input: '"abcdefabc"'
2082
+ output: ['"c"', '"c"']
2083
+
2084
+ - program: 'scan("b")'
2085
+ input: ("", "")
2086
+ output: ['[]', '[]']
2087
+
2088
+ - title: "`split(regex; flags)`"
2089
+ body: |
2090
+
2091
+ For backwards compatibility, `split` splits on a string, not a regex.
2092
+
2093
+ example:
2094
+ - program: 'split(", *"; null)'
2095
+ input: '"ab,cd, ef"'
2096
+ output: ['"ab","cd","ef"']
2097
+
2098
+
2099
+ - title: "\\[Requires 1.5\\] `splits(regex)`, `splits(regex; flags)`"
2100
+ body: |
2101
+
2102
+ These provide the same results as their `split` counterparts,
2103
+ but as a stream instead of an array.
2104
+
2105
+ example:
2106
+ - program: 'splits(", *")'
2107
+ input: '("ab,cd", "ef, gh")'
2108
+ output: ['"ab"', '"cd"', '"ef"', '"gh"']
2109
+
2110
+ - title: "\\[Requires 1.5\\] `sub(regex; tostring)` `sub(regex; string; flags)`"
2111
+ body: |
2112
+
2113
+ Emit the string obtained by replacing the first match of regex in the
2114
+ input string with `tostring`, after interpolation. `tostring` should
2115
+ be a jq string, and may contain references to named captures. The
2116
+ named captures are, in effect, presented as a JSON object (as
2117
+ constructed by `capture`) to `tostring`, so a reference to a captured
2118
+ variable named "x" would take the form: "\(.x)".
2119
+
2120
+ example:
2121
+ - program: 'sub("^[^a-z]*(?<x>[a-z]*).*")'
2122
+ input: '"123abc456"'
2123
+ output: '"ZabcZabc"'
2124
+
2125
+
2126
+ - title: "\\[Requires 1.5\\] `gsub(regex; string)`, `gsub(regex; string; flags)`"
2127
+ body: |
2128
+
2129
+ `gsub` is like `sub` but all the non-overlapping occurrences of the regex are
2130
+ replaced by the string, after interpolation.
2131
+
2132
+ example:
2133
+ - program: 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'
2134
+ input: '"Abcabc"'
2135
+ output: '"+A-+a-"'
2136
+
2137
+
2138
+ - title: Advanced features
2139
+ body: |
2140
+ Variables are an absolute necessity in most programming languages, but
2141
+ they're relegated to an "advanced feature" in jq.
2142
+
2143
+ In most languages, variables are the only means of passing around
2144
+ data. If you calculate a value, and you want to use it more than once,
2145
+ you'll need to store it in a variable. To pass a value to another part
2146
+ of the program, you'll need that part of the program to define a
2147
+ variable (as a function parameter, object member, or whatever) in
2148
+ which to place the data.
2149
+
2150
+ It is also possible to define functions in jq, although this is
2151
+ is a feature whose biggest use is defining jq's standard library
2152
+ (many jq functions such as `map` and `find` are in fact written
2153
+ in jq).
2154
+
2155
+ jq has reduction operators, which are very powerful but a bit
2156
+ tricky. Again, these are mostly used internally, to define some
2157
+ useful bits of jq's standard library.
2158
+
2159
+ It may not be obvious at first, but jq is all about generators
2160
+ (yes, as often found in other languages). Some utilities are
2161
+ provided to help deal with generators.
2162
+
2163
+ Some minimal I/O support (besides reading JSON from standard
2164
+ input, and writing JSON to standard output) is available.
2165
+
2166
+ Finally, there is a module/library system.
2167
+
2168
+ entries:
2169
+ - title: Variables
2170
+ body: |
2171
+
2172
+ In jq, all filters have an input and an output, so manual
2173
+ plumbing is not necessary to pass a value from one part of a program
2174
+ to the next. Many expressions, for instance `a + b`, pass their input
2175
+ to two distinct subexpressions (here `a` and `b` are both passed the
2176
+ same input), so variables aren't usually necessary in order to use a
2177
+ value twice.
2178
+
2179
+ For instance, calculating the average value of an array of numbers
2180
+ requires a few variables in most languages - at least one to hold the
2181
+ array, perhaps one for each element or for a loop counter. In jq, it's
2182
+ simply `add / length` - the `add` expression is given the array and
2183
+ produces its sum, and the `length` expression is given the array and
2184
+ produces its length.
2185
+
2186
+ So, there's generally a cleaner way to solve most problems in jq than
2187
+ defining variables. Still, sometimes they do make things easier, so jq
2188
+ lets you define variables using `expression as $variable`. All
2189
+ variable names start with `$`. Here's a slightly uglier version of the
2190
+ array-averaging example:
2191
+
2192
+ length as $array_length | add / $array_length
2193
+
2194
+ We'll need a more complicated problem to find a situation where using
2195
+ variables actually makes our lives easier.
2196
+
2197
+
2198
+ Suppose we have an array of blog posts, with "author" and "title"
2199
+ fields, and another object which is used to map author usernames to
2200
+ real names. Our input looks like:
2201
+
2202
+ {"posts": [{"title": "Frist psot", "author": "anon"},
2203
+ {"title": "A well-written article", "author": "person1"}],
2204
+ "realnames": {"anon": "Anonymous Coward",
2205
+ "person1": "Person McPherson"}}
2206
+
2207
+ We want to produce the posts with the author field containing a real
2208
+ name, as in:
2209
+
2210
+ {"title": "Frist psot", "author": "Anonymous Coward"}
2211
+ {"title": "A well-written article", "author": "Person McPherson"}
2212
+
2213
+ We use a variable, $names, to store the realnames object, so that we
2214
+ can refer to it later when looking up author usernames:
2215
+
2216
+ .realnames as $names | .posts[] | {title, author: $names[.author]}
2217
+
2218
+ The expression `exp as $x | ...` means: for each value of expression
2219
+ `exp`, run the rest of the pipeline with the entire original input, and
2220
+ with `$x` set to that value. Thus `as` functions as something of a
2221
+ foreach loop.
2222
+
2223
+ Just as `{foo}` is a handy way of writing `{foo: .foo}`, so
2224
+ `{$foo}` is a handy way of writing `{foo:$foo}`.
2225
+
2226
+ Multiple variables may be declared using a single `as` expression by
2227
+ providing a pattern that matches the structure of the input
2228
+ (this is known as "destructuring"):
2229
+
2230
+ . as {realnames: $names, posts: [$first, $second]} | ...
2231
+
2232
+ The variable declarations in array patterns (e.g., `. as
2233
+ [$first, $second]`) bind to the elements of the array in from
2234
+ the element at index zero on up, in order. When there is no
2235
+ value at the index for an array pattern element, `null` is
2236
+ bound to that variable.
2237
+
2238
+ Variables are scoped over the rest of the expression that defines
2239
+ them, so
2240
+
2241
+ .realnames as $names | (.posts[] | {title, author: $names[.author]})
2242
+
2243
+ will work, but
2244
+
2245
+ (.realnames as $names | .posts[]) | {title, author: $names[.author]}
2246
+
2247
+ won't.
2248
+
2249
+ For programming language theorists, it's more accurate to
2250
+ say that jq variables are lexically-scoped bindings. In
2251
+ particular there's no way to change the value of a binding;
2252
+ one can only setup a new binding with the same name, but which
2253
+ will not be visible where the old one was.
2254
+
2255
+ examples:
2256
+ - program: '.bar as $x | .foo | . + $x'
2257
+ input: '{"foo":10, "bar":200}'
2258
+ output: ['210']
2259
+ - program: '. as $i|[(.*2|. as $i| $i), $i]'
2260
+ input: '5'
2261
+ output: ['[10,5]']
2262
+ - program: '. as [$a, $b, {c: $c}] | $a + $b + $c'
2263
+ input: '[2, 3, {"c": 4, "d": 5}]'
2264
+ output: ['9']
2265
+ - program: '.[] as [$a, $b] | {a: $a, b: $b}'
2266
+ input: '[[0], [0, 1], [2, 1, 0]]'
2267
+ output: ['{"a":0,"b":null}', '{"a":0,"b":1}', '{"a":2,"b":1}']
2268
+
2269
+ - title: 'Defining Functions'
2270
+ body: |
2271
+
2272
+ You can give a filter a name using "def" syntax:
2273
+
2274
+ def increment: . + 1;
2275
+
2276
+ From then on, `increment` is usable as a filter just like a
2277
+ builtin function (in fact, this is how some of the builtins
2278
+ are defined). A function may take arguments:
2279
+
2280
+ def map(f): [.[] | f];
2281
+
2282
+ Arguments are passed as filters, not as values. The
2283
+ same argument may be referenced multiple times with
2284
+ different inputs (here `f` is run for each element of the
2285
+ input array). Arguments to a function work more like
2286
+ callbacks than like value arguments. This is important to
2287
+ understand. Consider:
2288
+
2289
+ def foo(f): f|f;
2290
+ 5|foo(.*2)
2291
+
2292
+ The result will be 20 because `f` is `.*2`, and during the
2293
+ first invocation of `f` `.` will be 5, and the second time it
2294
+ will be 10 (5 * 2), so the result will be 20. Function
2295
+ arguments are filters, and filters expect an input when
2296
+ invoked.
2297
+
2298
+ If you want the value-argument behaviour for defining simple
2299
+ functions, you can just use a variable:
2300
+
2301
+ def addvalue(f): f as $f | map(. + $f);
2302
+
2303
+ Or use the short-hand:
2304
+
2305
+ def addvalue($f): ...;
2306
+
2307
+ With either definition, `addvalue(.foo)` will add the current
2308
+ input's `.foo` field to each element of the array.
2309
+
2310
+ Multiple definitions using the same function name are allowed.
2311
+ Each re-definition replaces the previous one for the same
2312
+ number of function arguments, but only for references from
2313
+ functions (or main program) subsequent to the re-definition.
2314
+
2315
+ examples:
2316
+ - program: 'def addvalue(f): . + [f]; map(addvalue(.[0]))'
2317
+ input: '[[1,2],[10,20]]'
2318
+ output: ['[[1,2,1], [10,20,10]]']
2319
+ - program: 'def addvalue(f): f as $x | map(. + $x); addvalue(.[0])'
2320
+ input: '[[1,2],[10,20]]'
2321
+ output: ['[[1,2,1,2], [10,20,1,2]]']
2322
+
2323
+ - title: Reduce
2324
+ body: |
2325
+
2326
+ The `reduce` syntax in jq allows you to combine all of the
2327
+ results of an expression by accumulating them into a single
2328
+ answer. As an example, we'll pass `[3,2,1]` to this expression:
2329
+
2330
+ reduce .[] as $item (0; . + $item)
2331
+
2332
+ For each result that `.[]` produces, `. + $item` is run to
2333
+ accumulate a running total, starting from 0. In this
2334
+ example, `.[]` produces the results 3, 2, and 1, so the
2335
+ effect is similar to running something like this:
2336
+
2337
+ 0 | (3 as $item | . + $item) |
2338
+ (2 as $item | . + $item) |
2339
+ (1 as $item | . + $item)
2340
+
2341
+ examples:
2342
+ - program: 'reduce .[] as $item (0; . + $item)'
2343
+ input: '[10,2,5,3]'
2344
+ output: ['20']
2345
+
2346
+ - title: "`limit(n; exp)`"
2347
+ body: |
2348
+
2349
+ The `limit` function extracts up to `n` outputs from `exp`.
2350
+
2351
+ examples:
2352
+ - program: '[limit(3;.[])]'
2353
+ input: '[0,1,2,3,4,5,6,7,8,9]'
2354
+ output: ['[0,1,2]']
2355
+
2356
+ - title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"
2357
+ body: |
2358
+
2359
+ The `first(expr)` and `last(expr)` functions extract the first
2360
+ and last values from `expr`, respectively.
2361
+
2362
+ The `nth(n; expr)` function extracts the nth value output by
2363
+ `expr`. This can be defined as `def nth(n; expr):
2364
+ last(limit(n + 1; expr));`. Note that `nth(n; expr)` doesn't
2365
+ support negative values of `n`.
2366
+
2367
+ examples:
2368
+ - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'
2369
+ input: '10'
2370
+ output: ['[0,9,5]']
2371
+
2372
+ - title: "`first`, `last`, `nth(n)`"
2373
+ body: |
2374
+
2375
+ The `first` and `last` functions extract the first
2376
+ and last values from any array at `.`.
2377
+
2378
+ The `nth(n)` function extracts the nth value of any array at `.`.
2379
+
2380
+ examples:
2381
+ - program: '[range(.)]|[first, last, nth(5)]'
2382
+ input: '10'
2383
+ output: ['[0,9,5]']
2384
+
2385
+ - title: "`foreach`"
2386
+ body: |
2387
+
2388
+ The `foreach` syntax is similar to `reduce`, but intended to
2389
+ allow the construction of `limit` and reducers that produce
2390
+ intermediate results (see example).
2391
+
2392
+ The form is `foreach EXP as $var (INIT; UPDATE; EXTRACT)`.
2393
+ Like `reduce`, `INIT` is evaluated once to produce a state
2394
+ value, then each output of `EXP` is bound to `$var`, `UPDATE`
2395
+ is evaluated for each output of `EXP` with the current state
2396
+ and with `$var` visible. Each value output by `UPDATE`
2397
+ replaces the previous state. Finally, `EXTRACT` is evaluated
2398
+ for each new state to extract an output of `foreach`.
2399
+
2400
+ This is mostly useful only for constructing `reduce`- and
2401
+ `limit`-like functions. But it is much more general, as it
2402
+ allows for partial reductions (see the example below).
2403
+
2404
+ examples:
2405
+ - program: '[foreach .[] as $item
2406
+ ([[],[]];
2407
+ if $item == null then [[],.[0]] else [(.[0] + [$item]),[]] end;
2408
+ if $item == null then .[1] else empty end)]'
2409
+ input: '[1,2,3,4,null,"a","b",null]'
2410
+ output: ['[[1,2,3,4],["a","b"]]']
2411
+
2412
+ - title: Recursion
2413
+ body: |
2414
+
2415
+ As described above, `recurse` uses recursion, and any jq
2416
+ function can be recursive. The `while` builtin is also
2417
+ implemented in terms of recursion.
2418
+
2419
+ Tail calls are optimized whenever the expression to the left of
2420
+ the recursive call outputs its last value. In practice this
2421
+ means that the expression to the left of the recursive call
2422
+ should not produce more than one output for each input.
2423
+
2424
+ For example:
2425
+
2426
+ def recurse(f): def r: ., (f | select(. != null) | r); r;
2427
+
2428
+ def while(cond; update):
2429
+ def _while:
2430
+ if cond then ., (update | _while) else empty end;
2431
+ _while;
2432
+
2433
+ def repeat(exp):
2434
+ def _repeat:
2435
+ exp, _repeat;
2436
+ _repeat;
2437
+
2438
+ - title: Generators and iterators
2439
+ body: |
2440
+
2441
+ Some jq operators and functions are actually generators in
2442
+ that they can produce zero, one, or more values for each
2443
+ input, just as one might expect in other programming
2444
+ languages that have generators. For example, `.[]`
2445
+ generates all the values in its input (which must be an
2446
+ array or an object), `range(0; 10)` generates the integers
2447
+ between 0 and 10, and so on.
2448
+
2449
+ Even the comma operator is a generator, generating first the
2450
+ values generated by the expression to the left of the comma,
2451
+ then for each of those, the values generate by the
2452
+ expression on the right of the comma.
2453
+
2454
+ The `empty` builtin is the generator that produces zero
2455
+ outputs. The `empty` builtin backtracks to the preceding
2456
+ generator expression.
2457
+
2458
+ All jq functions can be generators just by using builtin
2459
+ generators. It is also possible to define new generators
2460
+ using only recursion and the comma operator. If the
2461
+ recursive call(s) is(are) "in tail position" then the
2462
+ generator will be efficient. In the example below the
2463
+ recursive call by `_range` to itself is in tail position.
2464
+ The example shows off three advanced topics: tail recursion,
2465
+ generator construction, and sub-functions.
2466
+
2467
+ examples:
2468
+ - program: 'def range(init; upto; by):
2469
+ def _range:
2470
+ if (by > 0 and . < upto) or (by < 0 and . > upto)
2471
+ then ., ((.+by)|_range)
2472
+ else . end;
2473
+ if by == 0 then init else init|_range end |
2474
+ select((by > 0 and . < upto) or (by < 0 and . > upto));
2475
+ range(0; 10; 3)'
2476
+ input: 'null'
2477
+ output: ['0', '3', '6', '9']
2478
+ - program: 'def while(cond; update):
2479
+ def _while:
2480
+ if cond then ., (update | _while) else empty end;
2481
+ _while;
2482
+ [while(.<100; .*2)]'
2483
+ input: '1'
2484
+ output: ['[1,2,4,8,16,32,64]']
2485
+
2486
+ - title: 'Math'
2487
+ body: |
2488
+
2489
+ jq currently only has IEEE754 double-precision (64-bit) floating
2490
+ point number support.
2491
+
2492
+ Besides simple arithmetic operators such as `+`, jq also has most
2493
+ standard math functions from the C math library. C math functions
2494
+ that take a single input argument (e.g., `sin()`) are available as
2495
+ zero-argument jq functions. C math functions that take two input
2496
+ arguments (e.g., `pow()`) are available as two-argument jq
2497
+ functions that ignore `.`.
2498
+
2499
+ Availability of standard math functions depends on the
2500
+ availability of the corresponding math functions in your operating
2501
+ system and C math library. Unavailable math functions will be
2502
+ defined but will raise an error.
2503
+
2504
+ - title: 'I/O'
2505
+ body: |
2506
+
2507
+ At this time jq has minimal support for I/O, mostly in the
2508
+ form of control over when inputs are read. Two builtins functions
2509
+ are provided for this, `input` and `inputs`, that read from the
2510
+ same sources (e.g., `stdin`, files named on the command-line) as
2511
+ jq itself. These two builtins, and jq's own reading actions, can
2512
+ be interleaved with each other.
2513
+
2514
+ One builtin provides minimal output capabilities, `debug`.
2515
+ (Recall that a jq program's output values are always output as
2516
+ JSON texts on `stdout`.) The `debug` builtin can have
2517
+ application-specific behavior, such as for executables that use
2518
+ the libjq C API but aren't the jq executable itself.
2519
+
2520
+ entries:
2521
+ - title: "`input`"
2522
+ body: |
2523
+
2524
+ Outputs one new input.
2525
+
2526
+ - title: "`inputs`"
2527
+ body: |
2528
+
2529
+ Outputs all remaining inputs, one by one.
2530
+
2531
+ This is primarily useful for reductions over a program's
2532
+ inputs.
2533
+
2534
+ - title: "`debug`"
2535
+ body: |
2536
+
2537
+ Causes a debug message based on the input value to be
2538
+ produced. The jq executable wraps the input value with
2539
+ `["DEBUG:", <input-value>]` and prints that and a newline on
2540
+ stderr, compactly. This may change in the future.
2541
+
2542
+ - title: "`input_filename`"
2543
+ body: |
2544
+
2545
+ Returns the name of the file whose input is currently being
2546
+ filtered. Note that this will not work well unless jq is
2547
+ running in a UTF-8 locale.
2548
+
2549
+ - title: "`input_line_number`"
2550
+ body: |
2551
+
2552
+ Returns the line number of the input currently being filtered.
2553
+
2554
+ - title: 'Streaming'
2555
+ body: |
2556
+
2557
+ With the `--stream` option jq can parse input texts in a streaming
2558
+ fashion, allowing jq programs to start processing large JSON texts
2559
+ immediately rather than after the parse completes. If you have a
2560
+ single JSON text that is 1GB in size, streaming it will allow you
2561
+ to process it much more quickly.
2562
+
2563
+ However, streaming isn't easy to deal with as the jq program will
2564
+ have `[<path>, <leaf-value>]` (and a few other forms) as inputs.
2565
+
2566
+ Several builtins are provided to make handling streams easier.
2567
+
2568
+ The examples below use the the streamed form of `[0,[1]]`, which
2569
+ is `[[0],0],[[1,0],1],[[1,0]],[[1]]`.
2570
+
2571
+ Streaming forms include `[<path>, <leaf-value>]` (to indicate any
2572
+ scalar value, empty array, or empty object), and `[<path>]` (to
2573
+ indicate the end of an array or object). Future versions of jq
2574
+ run with `--stream` and `-seq` may output additional forms such as
2575
+ `["error message"]` when an input text fails to parse.
2576
+
2577
+ entries:
2578
+ - title: "`truncate_stream(stream_expression)`"
2579
+ body: |
2580
+
2581
+ Consumes a number as input and truncates the corresponding
2582
+ number of path elements from the left of the outputs of the
2583
+ given streaming expression.
2584
+
2585
+ examples:
2586
+ - program: '[1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]'
2587
+ input: '1'
2588
+ output: ['[[[0],2],[[0]]]']
2589
+
2590
+ - title: "`fromstream(stream_expression)`"
2591
+ body: |
2592
+
2593
+ Outputs values corresponding to the stream expression's
2594
+ outputs.
2595
+
2596
+ examples:
2597
+ - program: 'fromstream(1|truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]]))'
2598
+ input: 'null'
2599
+ output: ['[2]']
2600
+
2601
+ - title: "`tostream`"
2602
+ body: |
2603
+
2604
+ The `tostream` builtin outputs the streamed form of its input.
2605
+
2606
+ examples:
2607
+ - program: '. as $dot|fromstream($dot|tostream)|.==$dot'
2608
+ input: '[0,[1,{"a":1},{"b":2}]]'
2609
+ output: ['true']
2610
+
2611
+ - title: Assignment
2612
+ body: |
2613
+
2614
+ Assignment works a little differently in jq than in most
2615
+ programming languages. jq doesn't distinguish between references
2616
+ to and copies of something - two objects or arrays are either
2617
+ equal or not equal, without any further notion of being "the
2618
+ same object" or "not the same object".
2619
+
2620
+ If an object has two fields which are arrays, `.foo` and `.bar`,
2621
+ and you append something to `.foo`, then `.bar` will not get
2622
+ bigger. Even if you've just set `.bar = .foo`. If you're used to
2623
+ programming in languages like Python, Java, Ruby, Javascript,
2624
+ etc. then you can think of it as though jq does a full deep copy
2625
+ of every object before it does the assignment (for performance,
2626
+ it doesn't actually do that, but that's the general idea).
2627
+
2628
+ All the assignment operators in jq have path expressions on the
2629
+ left-hand side.
2630
+
2631
+ entries:
2632
+ - title: "`=`"
2633
+ body: |
2634
+
2635
+ The filter `.foo = 1` will take as input an object
2636
+ and produce as output an object with the "foo" field set to
2637
+ 1. There is no notion of "modifying" or "changing" something
2638
+ in jq - all jq values are immutable. For instance,
2639
+
2640
+ .foo = .bar | .foo.baz = 1
2641
+
2642
+ will not have the side-effect of setting .bar.baz to be set
2643
+ to 1, as the similar-looking program in Javascript, Python,
2644
+ Ruby or other languages would. Unlike these languages (but
2645
+ like Haskell and some other functional languages), there is
2646
+ no notion of two arrays or objects being "the same array" or
2647
+ "the same object". They can be equal, or not equal, but if
2648
+ we change one of them in no circumstances will the other
2649
+ change behind our backs.
2650
+
2651
+ This means that it's impossible to build circular values in
2652
+ jq (such as an array whose first element is itself). This is
2653
+ quite intentional, and ensures that anything a jq program
2654
+ can produce can be represented in JSON.
2655
+
2656
+ Note that the left-hand side of '=' refers to a value in `.`.
2657
+ Thus `$var.foo = 1` won't work as expected (`$var.foo` is not
2658
+ a valid or useful path expression in `.`); use `$var | .foo =
2659
+ 1` instead.
2660
+
2661
+ If the right-hand side of '=' produces multiple values, then
2662
+ for each such value jq will set the paths on the left-hand
2663
+ side to the value and then it will output the modified `.`.
2664
+ For example, `(.a,.b)=range(2)` outputs `{"a":0,"b":0}`, then
2665
+ `{"a":1,"b":1}`. The "update" assignment forms (see below) do
2666
+ not do this.
2667
+
2668
+ Note too that `.a,.b=0` does not set `.a` and `.b`, but
2669
+ `(.a,.b)=0` sets both.
2670
+
2671
+ - title: "`|=`"
2672
+ body: |
2673
+ As well as the assignment operator '=', jq provides the "update"
2674
+ operator '|=', which takes a filter on the right-hand side and
2675
+ works out the new value for the property of `.` being assigned
2676
+ to by running the old value through this expression. For
2677
+ instance, .foo |= .+1 will build an object with the "foo"
2678
+ field set to the input's "foo" plus 1.
2679
+
2680
+ This example should show the difference between '=' and '|=':
2681
+
2682
+ Provide input '{"a": {"b": 10}, "b": 20}' to the programs:
2683
+
2684
+ .a = .b
2685
+ .a |= .b
2686
+
2687
+ The former will set the "a" field of the input to the "b" field of the
2688
+ input, and produce the output {"a": 20}. The latter will set the "a"
2689
+ field of the input to the "a" field's "b" field, producing {"a": 10}.
2690
+
2691
+ The left-hand side can be any general path expression; see `path()`.
2692
+
2693
+ Note that the left-hand side of '|=' refers to a value in `.`.
2694
+ Thus `$var.foo |= . + 1` won't work as expected (`$var.foo` is
2695
+ not a valid or useful path expression in `.`); use `$var |
2696
+ .foo |= . + 1` instead.
2697
+
2698
+ If the right-hand side outputs multiple values, only the last
2699
+ one will be used.
2700
+
2701
+ examples:
2702
+
2703
+ - program: '(..|select(type=="boolean")) |= if . then 1 else 0 end'
2704
+ input: '[true,false,[5,true,[true,[false]],false]]'
2705
+ output: ['[1,0,[5,1,[1,[0]],0]]']
2706
+
2707
+ - title: "`+=`, `-=`, `*=`, `/=`, `%=`, `//=`"
2708
+ body: |
2709
+
2710
+ jq has a few operators of the form `a op= b`, which are all
2711
+ equivalent to `a |= . op b`. So, `+= 1` can be used to increment values.
2712
+
2713
+ examples:
2714
+ - program: .foo += 1
2715
+ input: '{"foo": 42}'
2716
+ output: ['{"foo": 43}']
2717
+
2718
+ - title: Complex assignments
2719
+ body: |
2720
+ Lots more things are allowed on the left-hand side of a jq assignment
2721
+ than in most languages. We've already seen simple field accesses on
2722
+ the left hand side, and it's no surprise that array accesses work just
2723
+ as well:
2724
+
2725
+ .posts[0].title = "JQ Manual"
2726
+
2727
+ What may come as a surprise is that the expression on the left may
2728
+ produce multiple results, referring to different points in the input
2729
+ document:
2730
+
2731
+ .posts[].comments |= . + ["this is great"]
2732
+
2733
+ That example appends the string "this is great" to the "comments"
2734
+ array of each post in the input (where the input is an object with a
2735
+ field "posts" which is an array of posts).
2736
+
2737
+ When jq encounters an assignment like 'a = b', it records the "path"
2738
+ taken to select a part of the input document while executing a. This
2739
+ path is then used to find which part of the input to change while
2740
+ executing the assignment. Any filter may be used on the
2741
+ left-hand side of an equals - whichever paths it selects from the
2742
+ input will be where the assignment is performed.
2743
+
2744
+ This is a very powerful operation. Suppose we wanted to add a comment
2745
+ to blog posts, using the same "blog" input above. This time, we only
2746
+ want to comment on the posts written by "stedolan". We can find those
2747
+ posts using the "select" function described earlier:
2748
+
2749
+ .posts[] | select(.author == "stedolan")
2750
+
2751
+ The paths provided by this operation point to each of the posts that
2752
+ "stedolan" wrote, and we can comment on each of them in the same way
2753
+ that we did before:
2754
+
2755
+ (.posts[] | select(.author == "stedolan") | .comments) |=
2756
+ . + ["terrible."]
2757
+
2758
+ - title: Modules
2759
+ body: |
2760
+
2761
+ jq has a library/module system. Modules are files whose names end
2762
+ in `.jq`.
2763
+
2764
+ Modules imported by a program are searched for in a default search
2765
+ path (see below). The `import` and `include` directives allow the
2766
+ importer to alter this path.
2767
+
2768
+ Paths in the a search path are subject to various substitutions.
2769
+
2770
+ For paths starting with "~/", the user's home directory is
2771
+ substituted for "~".
2772
+
2773
+ For paths starting with "$ORIGIN/", the path of the jq executable
2774
+ is substituted for "$ORIGIN".
2775
+
2776
+ For paths starting with "./" or paths that are ".", the path of
2777
+ the including file is substituted for ".". For top-level programs
2778
+ given on the command-line, the current directory is used.
2779
+
2780
+ Import directives can optionally specify a search path to which
2781
+ the default is appended.
2782
+
2783
+ The default search path is the search path given to the `-L`
2784
+ command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",
2785
+ "$ORIGIN/../lib"]`.
2786
+
2787
+ Null and empty string path elements terminate search path
2788
+ processing.
2789
+
2790
+ A dependency with relative path "foo/bar" would be searched for in
2791
+ "foo/bar.jq" and "foo/bar/bar.jq" in the given search path. This
2792
+ is intended to allow modules to be placed in a directory along
2793
+ with, for example, version control files, README files, and so on,
2794
+ but also to allow for single-file modules.
2795
+
2796
+ Consecutive components with the same name are not allowed to avoid
2797
+ ambiguities (e.g., "foo/foo").
2798
+
2799
+ For example, with `-L$HOME/.jq` a module `foo` can be found in
2800
+ `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.
2801
+
2802
+ If "$HOME/.jq" is a file, it is sourced into the main program.
2803
+
2804
+ entries:
2805
+ - title: "`import RelativePathString as NAME [<metadata>];`"
2806
+ body: |
2807
+
2808
+ Imports a module found at the given path relative to a
2809
+ directory in a search path. A ".jq" suffix will be added to
2810
+ the relative path string. The module's symbols are prefixed
2811
+ with "NAME::".
2812
+
2813
+ The optional metadata must be a constant jq expression. It
2814
+ should be an object with keys like "homepage" and so on. At
2815
+ this time jq only uses the "search" key/value of the metadata.
2816
+ The metadata is also made available to users via the
2817
+ `modulemeta` builtin.
2818
+
2819
+ The "search" key in the metadata, if present, should have a
2820
+ string or array value (array of strings); this is the search
2821
+ path to be prefixed to the top-level search path.
2822
+
2823
+ - title: "`include RelativePathString [<metadata>];`"
2824
+ body: |
2825
+
2826
+ Imports a module found at the given path relative to a
2827
+ directory in a search path as if it were included in place. A
2828
+ ".jq" suffix will be added to the relative path string. The
2829
+ module's symbols are imported into the caller's namespace as
2830
+ if the module's content had been included directly.
2831
+
2832
+ The optional metadata must be a constant jq expression. It
2833
+ should be an object with keys like "homepage" and so on. At
2834
+ this time jq only uses the "search" key/value of the metadata.
2835
+ The metadata is also made available to users via the
2836
+ `modulemeta` builtin.
2837
+
2838
+ - title: "`import RelativePathString as $NAME [<metadata>];`"
2839
+ body: |
2840
+
2841
+ Imports a JSON file found at the given path relative to a
2842
+ directory in a search path. A ".json" suffix will be added to
2843
+ the relative path string. The file's data will be available
2844
+ as `$NAME::NAME`.
2845
+
2846
+ The optional metadata must be a constant jq expression. It
2847
+ should be an object with keys like "homepage" and so on. At
2848
+ this time jq only uses the "search" key/value of the metadata.
2849
+ The metadata is also made available to users via the
2850
+ `modulemeta` builtin.
2851
+
2852
+ The "search" key in the metadata, if present, should have a
2853
+ string or array value (array of strings); this is the search
2854
+ path to be prefixed to the top-level search path.
2855
+
2856
+ - title: "`module <metadata>;`"
2857
+ body: |
2858
+
2859
+ This directive is entirely optional. It's not required for
2860
+ proper operation. It serves only the purpose of providing
2861
+ metadata that can be read with the `modulemeta` builtin.
2862
+
2863
+ The metadata must be a constant jq expression. It should be
2864
+ an object with keys like "homepage". At this time jq doesn't
2865
+ use this metadata, but it is made available to users via the
2866
+ `modulemeta` builtin.
2867
+
2868
+ - title: "`modulemeta`"
2869
+ body: |
2870
+
2871
+ Takes a module name as input and outputs the module's metadata
2872
+ as an object, with the module's imports (including metadata)
2873
+ as an array value for the "deps" key.
2874
+
2875
+ Programs can use this to query a module's metadata, which they
2876
+ could then use to, for example, search for, download, and
2877
+ install missing dependencies.
2878
+