JQ(1)
okay bestie, welcome to jq(1) ๐
this is the command-line JSON processor and it is iconic, no cap. let's get into it โจ
๐ NAME ๐
jq - Command-line JSON processor ๐ซถ
๐ธ SYNOPSIS ๐ธ
jq [options...] filter [files...]
so like, jq can transform JSON in so many ways โ selecting, iterating, reducing, and otherwise just straight-up mangling JSON documents. it's giving full-on glow-up for your data ๐
for instance, running the command jq ยดmap(.price) | addยด will take an array of JSON objects as input and return the sum of their "price" fields. math but make it cute ๐งฎโจ
jq can accept text input as well, bestie, but by default it reads a stream of JSON entities (including numbers and other literals) from stdin. whitespace is only needed to separate entities such as 1 and 2, and true and false โ they just gotta not touch, iykyk. one or more files may be specified, in which case jq will read input from those instead. ur choice, main character ๐ซถ
the options are described in the [INVOKING JQ] section โ they mostly concern input and output formatting. the filter is written in the jq language and specifies how to transform the input file or document. slay.
๐ฆ FILTERS ๐ฆ
a jq program is a "filter": it takes an input, and produces an output. that's it, that's the whole personality. there are a lot of builtin filters for extracting a particular field of an object, or converting a number to a string, or various other standard tasks. the toolbox is huge, we love her ๐
filters can be combined in various ways โ you can pipe the output of one filter into another filter, or collect the output of a filter into an array. gluing filters together is the whole hobby tbh ๐
some filters produce multiple results. for instance, there's one that produces all the elements of its input array. piping that filter into a second runs the second filter for each element of the array. so generally, things that would be done with loops and iteration in other languages are just done by gluing filters together in jq. no for loops, no crying, just vibes โจ
it's important to remember that every filter has an input and an output. even literals like "hello" or 42 are filters โ they take an input but always produce the same literal as output. yes, 42 is a filter, she's doing her best ๐
operations that combine two filters, like addition, generally feed the same input to both and combine the results. so, you can implement an averaging filter as add / length โ feeding the input array both to the add filter and the length filter and then performing the division. both filters get the same snack, then the answer gets divided. periodt ๐
not me building a whole average out of two filters like it's nothing ๐ญ
but that's getting ahead of ourselves. :) let's start with something simpler:
๐ INVOKING JQ ๐
okay so here's the whole vibe, bestie: jq filters run on a stream of JSON data. The input to jq gets parsed as a sequence of whitespace-separated JSON values, and those get passed through the filter you gave it, one at a time. Then the output(s) of the filter get written to standard output as a sequence of newline-separated JSON data. That's the whole loop. ๐
The simplest and most common filter (or jq program) is ., which is the identity operator โ it literally just copies the inputs of the jq processor to the output stream. And because jq's default behavior is to read JSON texts from the input stream and pretty-print the outputs, the main use of the . program is to validate and pretty-print your inputs. But the jq programming language is quite rich, so it does way more than just validation and pretty-printing. trust.
Note: it is important to mind the shell's quoting rules. As a general rule it's best to always quote (with single-quote characters on Unix shells) the jq program, because too many characters with special meaning to jq are also shell meta-characters. For example,jq "foo"will fail on most Unix shells because that will be the same asjq foo, which will generally fail becausefoois not defined. When using the Windows command shell (cmd.exe) it's best to use double quotes around your jq program when given on the command-line (instead of the-fprogram-file option), but then double-quotes in the jq program need backslash escaping. When using the Powershell (powershell.exe) or the Powershell Core (pwsh/pwsh.exe), use single-quote characters around the jq program and backslash-escaped double-quotes (\") inside the jq program.
so like, per shell:
- Unix shells:
jq '.["foo"]' - Powershell:
jq '.[\"foo\"]' - Windows command shell:
jq ".[\"foo\"]"
Note: jq allows user-defined functions, but every jq program must have a top-level expression. no exceptions, babe ๐
You can affect how jq reads and writes its input and output using some command-line options:
--null-input/-nโ Don't read any input at all. Instead, the filter is run once usingnullas the input. This is useful when using jq as a simple calculator or to construct JSON data from scratch. slay, blank canvas energy โจ--raw-input/-Rโ Don't parse the input as JSON. Instead, each line of text is passed to the filter as a string. If combined with--slurp, then the entire input is passed to the filter as a single long string.--slurp/-sโ Instead of running the filter for each JSON object in the input, read the entire input stream into a large array and run the filter just once. one big group chat instead of separate DMs ๐ซถ--compact-output/-cโ By default, jq pretty-prints JSON output. Using this option will result in more compact output by instead putting each JSON object on a single line.--raw-output/-rโ With this option, if the filter's result is a string then it will be written directly to standard output rather than being formatted as a JSON string with quotes. This can be useful for making jq filters talk to non-JSON-based systems.--raw-output0โ Like-rbut jq will printNULinstead of newline after each output. This can be useful when the values being output can contain newlines. When the output value contains NUL, jq exits with non-zero code.--join-output/-jโ Like-rbut jq won't print a newline after each output.--ascii-output/-aโ jq usually outputs non-ASCII Unicode codepoints as UTF-8, even if the input specified them as escape sequences (like"\u03bc"). Using this option, you can force jq to produce pure ASCII output with every non-ASCII character replaced with the equivalent escape sequence.--sort-keys/-Sโ Output the fields of each object with the keys in sorted order. alphabetically organized queen ๐--color-output/-Cand--monochrome-output/-Mโ By default, jq outputs colored JSON if writing to a terminal. You can force it to produce color even if writing to a pipe or a file using-C, and disable color with-M. When theNO_COLORenvironment variable is not empty, jq disables colored output by default, but you can enable it by-C.
Colors can be configured with the JQ_COLORS environment variable (see below).
--tabโ Use a tab for each indentation level instead of two spaces.--indent nโ Use the given number of spaces (no more than7) for indentation. seven is the ceiling, bestie, don't push it.--unbufferedโ Flush the output after each JSON object is printed (useful if you're piping a slow data source into jq and piping jq's output elsewhere).--streamโ Parse the input in streaming fashion, outputting arrays of path and leaf values (scalars and empty arrays or empty objects). For example,"a"becomes[[],"a"], and[[],"a",["b"]]becomes[[0],[]],[[1],"a"], and[[2,0],"b"].
This is useful for processing very large inputs. Use this in conjunction with filtering and the reduce and foreach syntax to reduce large inputs incrementally.
--stream-errorsโ Like--stream, but invalid JSON inputs yield array values where the first element is the error and the second is a path. For example,["a",n]produces["Invalid literal at line 1, column 7",[1]].
Implies --stream. Invalid JSON inputs produce no error values when --stream without --stream-errors.
--seqโ Use theapplication/json-seqMIME type scheme for separating JSON texts in jq's input and output. This means that an ASCII RS (record separator) character is printed before each value on output and an ASCII LF (line feed) is printed after every output. Input JSON texts that fail to parse are ignored (but warned about), discarding all subsequent input until the next RS. This mode also parses the output of jq without the--seqoption.-f/--from-fileโ Read the filter from a file rather than from a command line, like awk's-foption. This changes the filter argument to be interpreted as a filename, instead of the source of a program.-L directory/--library-path directoryโ Prepend directory to the search list for modules. If this option is used then no builtin search list is used. See the section on modules below.--arg name valueโ This option passes a value to the jq program as a predefined variable. If you run jq with--arg foo bar, then$foois available in the program and has the value"bar". Note that value will be treated as a string, so--arg foo 123will bind$footo"123".
Named arguments are also available to the jq program as $ARGS.named. When the name is not a valid identifier, this is the only way to access it.
--argjson name JSON-textโ This option passes a JSON-encoded value to the jq program as a predefined variable. If you run jq with--argjson foo 123, then$foois available in the program and has the value123.--slurpfile variable-name filenameโ This option reads all the JSON texts in the named file and binds an array of the parsed JSON values to the given global variable. If you run jq with--slurpfile foo bar, then$foois available in the program and has an array whose elements correspond to the texts in the file namedbar.--rawfile variable-name filenameโ This option reads in the named file and binds its content to the given global variable. If you run jq with--rawfile foo bar, then$foois available in the program and has a string whose content is set to the text in the file namedbar.--argsโ Remaining arguments are positional string arguments. These are available to the jq program as$ARGS.positional[].--jsonargsโ Remaining arguments are positional JSON text arguments. These are available to the jq program as$ARGS.positional[].--exit-status/-eโ Sets the exit status of jq to0if the last output value was neitherfalsenornull,1if the last output value was eitherfalseornull, or4if no valid result was ever produced. Normally jq exits with2if there was any usage problem or system error,3if there was a jq program compile error, or0if the jq program ran.
Another way to set the exit status is with the halt_error builtin function.
--binary/-bโ Windows users using WSL, MSYS2, or Cygwin, should use this option when using a nativejq.exe, otherwise jq will turn newlines (LFs) into carriage-return-then-newline (CRLF).--version/-Vโ Output the jq version and exit with zero.--build-configurationโ Output the build configuration of jq and exit with zero. This output has no supported format or structure and may change without notice in future releases. so don't go parsing it, bestie ๐--help/-hโ Output the jq help and exit with zero.--โ Terminates argument processing. Remaining arguments are not interpreted as options.--run-tests [filename]โ Runs the tests in the given file or standard input. This must be the last option given and does not honor all preceding options. The input consists of comment lines, empty lines, and program lines followed by one input line, as many lines of output as are expected (one per output), and a terminating empty line. Compilation failure tests start with a line containing only%%FAIL, then a line containing the program to compile, then a line containing an error message to compare to the actual.
Be warned that this option can change backwards-incompatibly. ๐
๐ฆ BASIC FILTERS ๐ฆ
okay bestie, this is the part where it gets FUN. these are the little building blocks you'll use every single day, no cap. ๐
Identity: .
the absolute simplest filter is just .. like, that's it. that's the whole filter. it takes whatever you feed it and spits the exact same value back out. it's the identity operator, the "no thoughts, head empty, just vibes" filter. โจ
and because jq by default pretty-prints literally all of its output, a whole program that's nothing but . is genuinely useful โ it'll format JSON output from, say, curl. iconic behavior honestly.
now, plot twist: even though the identity filter never changes your value, jq's processing can sometimes make it look like it did. ๐ญ like, with the current implementation of jq, we'd see that this expression:
1E1234567890 | .
produces 1.7976931348623157e+308 on at least one platform. why? because while parsing the number, this particular version of jq converted it into an IEEE754 double-precision representation and lost precision. she's doing her best!! ๐
the way jq handles numbers has changed over time and more changes are likely within the parameters set by the relevant JSON standards. on top of that, build configuration options can alter how jq processes numbers.
so the following remarks are offered with the understanding that they're meant to describe the current version of jq, and should not be read as prescriptive:
- any arithmetic operation on a number that hasn't already been converted to an IEEE754 double precision representation will trigger a conversion to the IEEE754 representation.
jqwill attempt to maintain the original decimal precision of number literals (as long as the--disable-decnumbuild configuration option wasn't used), but in expressions such as1E1234567890, precision will be lost if the exponent is too large.- comparisons are carried out using the untruncated big decimal representation of numbers if it's available, as illustrated in one of the following examples. ๐
the examples below use the builtin function have_decnum to show off the expected effects of using / not using the --disable-decnum build configuration option โ and also so that automated tests derived from these examples pass no matter whether that option was used. smart, right? ๐ง
jq ยด.ยด
"Hello, world!"
=> "Hello, world!"
jq ยด.ยด
0.12345678901234567890123456789
=> 0.12345678901234567890123456789
jq ยด[., tojson] == if have_decnum then [12345678909876543212345,"12345678909876543212345"] else [12345678909876543000000,"12345678909876543000000"] endยด
12345678909876543212345
=> true
jq ยด[1234567890987654321,-1234567890987654321 | tojson] == if have_decnum then ["1234567890987654321","-1234567890987654321"] else ["1234567890987654400","-1234567890987654400"] endยด
null
=> true
jq ยด. < 0.12345678901234567890123456788ยด
0.12345678901234567890123456789
=> false
jq ยดmap([., . == 1]) | tojson == if have_decnum then "[[1,true],[1.000,true],[1.0,true],[1.00,true]]" else "[[1,true],[1,true],[1,true],[1,true]]" endยด
[1, 1.000, 1.0, 100e-2]
=> true
jq ยด. as $big | [$big, $big + 1] | map(. > 10000000000000000000000000000000) | . == if have_decnum then [true, false] else [false, false] endยด
10000000000000000000000000000001
=> true
Object Identifier-Index: .foo, .foo.bar
now THIS is where it starts being useful, fr fr. the simplest useful filter looks like .foo. hand it a JSON object (aka dictionary, aka hash, whatever you call it) and .foo hands you back the value at the key "foo" if that key exists โ or null if it doesn't. chill. ๐คท
a filter shaped like .foo.bar is exactly equivalent to .foo | .bar.
the .foo syntax only works for simple, identifier-like keys. that means keys made entirely of alphanumeric characters and underscore, and which do not start with a digit. sorry bestie, those are the rules. ๐
if your key has special characters in it, or starts with a digit, you gotta wrap it in double quotes like . "foo$"-style: ."foo$", or else .["foo$"].
for example, .["foo::bar"] and .["foo.bar"] work, while .foo::bar does not. ๐
jq ยด.fooยด
{"foo": 42, "bar": "less interesting data"}
=> 42
jq ยด.fooยด
{"notfoo": true, "alsonotfoo": false}
=> null
jq ยด.["foo"]ยด
{"foo": 42}
=> 42
Optional Object Identifier-Index: .foo?
literally just like .foo, except it does not throw an error when . isn't an object. she's unbothered, moisturized, in her lane. ๐ซถ
jq ยด.foo?ยด
{"foo": 42, "bar": "less interesting data"}
=> 42
jq ยด.foo?ยด
{"notfoo": true, "alsonotfoo": false}
=> null
jq ยด.["foo"]?ยด
{"foo": 42}
=> 42
jq ยด[.foo?]ยด
[1,2]
=> []
Object Index: .[<string>]
you can also look up fields of an object with syntax like .["foo"] โ and yes, .foo up there is just a shorthand version of this, but only for identifier-like strings. same energy, fewer keystrokes. โจ
Array Index: .[<number>]
when the index value is an integer, .[<number>] can index into arrays. arrays are zero-based, so .[2] gives you the third element. (yes, counting from zero, we all agreed to this, it's fine. ๐ธ)
negative indices are allowed too! -1 refers to the last element, -2 to the next-to-last element, and so on down the line. ๐
jq ยด.[0]ยด
[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]
=> {"name":"JSON", "good":true}
jq ยด.[2]ยด
[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]
=> null
jq ยด.[-2]ยด
[1,2,3]
=> 2
Array/String Slice: .[<number>:<number>]
the .[<number>:<number>] syntax returns a subarray of an array, or a substring of a string. so the array returned by .[10:15] will have length 5, containing the elements from index 10 (inclusive) to index 15 (exclusive). either index can be negative (which means it counts backwards from the end of the array), or omitted (which means it refers to the start or end of the array). indices are zero-based, obviously. ๐
jq ยด.[2:4]ยด
["a","b","c","d","e"]
=> ["c", "d"]
jq ยด.[2:4]ยด
"abcdefghi"
=> "cd"
jq ยด.[:3]ยด
["a","b","c","d","e"]
=> ["a", "b", "c"]
jq ยด.[-2:]ยด
["a","b","c","d","e"]
=> ["d", "e"]
Array/Object Value Iterator: .[]
if you use the .[index] syntax but leave the index out entirely, it returns all the elements of an array. running .[] on the input [1,2,3] produces those numbers as three separate results, not as one single array. a filter shaped like .foo[] is equivalent to .foo | .[].
you can use this on an object too, and it'll hand you all the values of the object. ๐
note that the iterator operator is a generator of values. she contains multitudes. ๐
jq ยด.[]ยด
[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]
=> {"name":"JSON", "good":true}, {"name":"XML", "good":false}
jq ยด.[]ยด
[]
=>
jq ยด.foo[]ยด
{"foo":[1,2,3]}
=> 1, 2, 3
jq ยด.[]ยด
{"a": 1, "b": 1}
=> 1, 1
.[]?
like .[], but no errors will be output if . isn't an array or object. a filter shaped like .foo[]? is equivalent to .foo | .[]?. ๐ฆ
Comma: ,
if two filters get separated by a comma, the same input gets fed into both of them, and the two filters' output value streams get concatenated in order: first, all the outputs from the left expression, then all the outputs from the right one. so for instance, the filter .foo, .bar produces both the "foo" fields and the "bar" fields as separate outputs. two things can be true at once, bestie. ๐
the , operator is one way to construct generators. โญ
jq ยด.foo, .barยด
{"foo": 42, "bar": "something else", "baz": true}
=> 42, "something else"
jq ยด.user, .projects[]ยด
{"user":"stedolan", "projects": ["jq", "wikiflow"]}
=> "stedolan", "jq", "wikiflow"
jq ยด.[4,2]ยด
["a","b","c","d","e"]
=> "e", "c"
Pipe: |
the | operator combines two filters by feeding the output(s) of the one on the left into the input of the one on the right. it's similar to the Unix shell's pipe, if you're used to that. classic, timeless. ๐
if the one on the left produces multiple results, the one on the right gets run for each of those results. so the expression .[] | .foo retrieves the "foo" field of every element of the input array. heads up though: this is a cartesian product, which can be surprising. ๐ญ
note that .a.b.c is the same as .a | .b | .c.
and note too that . is the input value at that particular stage in a "pipeline" โ specifically, wherever the . expression shows up. so .a | . | .b is the same as .a.b, because that . in the middle refers to whatever value .a produced. she's contextual like that. โจ
jq ยด.[] | .nameยด
[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]
=> "JSON", "XML"
Parenthesis
parenthesis work as a grouping operator, just like in any typical programming language. no notes. ๐ซถ
jq ยด(. + 2) * 5ยด
1
=> 15
โจ TYPES AND VALUES โจ
okay bestie, here's the tea on types ๐ซ jq speaks the same datatype language as JSON โ numbers, strings, booleans, arrays, objects (which in JSON-speak are hashes with only string keys, no cap), and "null". iconic lineup fr ๐
Booleans, null, strings and numbers get written exactly the same way they are in JSON. And just like literally everything else in jq, these simple values take an input and produce an output โ 42 is a totally valid jq expression that takes an input, ignores it completely (main character energy, honestly), and returns 42 instead. ๐
Numbers in jq are internally represented by their IEEE754 double precision approximation. Any arithmetic operation with numbers, whether they're literals or results of previous filters, will produce a double precision floating point result. that's just how she is.
BUT here's the plot twist ๐ when parsing a literal, jq will store the original literal string. If no mutation is applied to this value, then it will make it to the output in its original form โ even if conversion to double would result in a loss. she remembers where she came from. periodt. ๐
๐งบ Array construction: []
As in JSON, [] is used to construct arrays, like [1,2,3]. The elements of the arrays can be any jq expression, including a pipeline. All of the results produced by all of the expressions are collected into one big array. You can use it to construct an array out of a known quantity of values (as in [.foo, .bar, .baz]) or to "collect" all the results of a filter into an array (as in [.items[].name]) ๐
Once you understand the , operator, you can look at jq's array syntax in a whole new light: the expression [1,2,3] is not using a built-in syntax for comma-separated arrays โ it's instead applying the [] operator (collect results) to the expression 1,2,3 (which produces three different results). the way that [] is just vibing on top of ,โฆ obsessed ๐ญ
If you have a filter X that produces four results, then the expression [X] will produce a single result, an array of four elements. slay ๐
jq '[.user, .projects[]]'
{"user":"stedolan", "projects": ["jq", "wikiflow"]}
=> ["stedolan", "jq", "wikiflow"]
jq '[ .[] | . * 2]'
[1, 2, 3]
=> [2, 4, 6]
๐ Object Construction: {}
Like JSON, {} is for constructing objects (aka dictionaries or hashes), as in: {"a": 42, "b": 17}.
If the keys are "identifier-like", then the quotes can be left off, as in {a:42, b:17} โจ Variable references as key expressions use the value of the variable as the key. Key expressions other than constant literals, identifiers, or variable references, need to be parenthesized, e.g., {("a"+"b"):59}. (yes bestie, parentheses are the moment ๐
)
The value can be any expression (although you may need to wrap it in parentheses if, for example, it contains colons), which gets applied to the {} expression's input (remember, all filters have an input and an output ๐ซถ).
{foo: .bar}
will produce the JSON object {"foo": 42} if given the JSON object {"bar":42, "baz":43} as its input. You can use this to select particular fields of an object: if the input is an object with "user", "title", "id", and "content" fields and you just want "user" and "title", you can write
{user: .user, title: .title}
Because that is so common, there's a shortcut syntax for it: {user, title}. lowkey genius ๐ธ
If one of the expressions produces multiple results, multiple dictionaries will be produced. If the input's
{"user":"stedolan","titles":["JQ Primer", "More JQ"]}
then the expression
{user, title: .titles[]}
will produce two outputs:
{"user":"stedolan", "title": "JQ Primer"}
{"user":"stedolan", "title": "More JQ"}
Putting parentheses around the key means it will be evaluated as an expression. With the same input as above,
{(.user): .titles}
produces
{"stedolan": ["JQ Primer", "More JQ"]}
Variable references as keys use the value of the variable as the key. Without a value then the variable's name becomes the key and its value becomes the value,
"f o o" as $foo | "b a r" as $bar | {$foo, $bar:$foo}
produces
{"foo":"f o o","b a r":"f o o"}
jq '{user, title: .titles[]}'
{"user":"stedolan","titles":["JQ Primer", "More JQ"]}
=> {"user":"stedolan", "title": "JQ Primer"}, {"user":"stedolan", "title": "More JQ"}
jq '{(.user): .titles}'
{"user":"stedolan","titles":["JQ Primer", "More JQ"]}
=> {"stedolan": ["JQ Primer", "More JQ"]}
๐ Recursive Descent: ..
Recursively descends ., producing every value. This is the same as the zero-argument recurse builtin (see below). This is intended to resemble the XPath // operator. Note that ..a does not work; use .. | .a instead โ ๏ธ In the example below we use .. | .a? to find all the values of object keys "a" in any object found "below" ...
This is particularly useful in conjunction with path(EXP) (also see below) and the ? operator. dynamic duo energy fr fr ๐
jq '.. | .a?'
[[{"a":1}]]
=> 1
๐ฅ BUILTIN OPERATORS AND FUNCTIONS ๐ฅ
Some jq operators (for instance, +) do different things depending on the type of their arguments (arrays, numbers, etc.). However, jq never does implicit type conversions. If you try to add a string to an object you'll get an error message and no result. no sneaky little conversions here bestie ๐ญ
Please note that all numbers are converted to IEEE754 double precision floating point representation. Arithmetic and logical operators are working with these converted doubles. Results of all such operations are also limited to the double precision.
The only exception to this behaviour of number is a snapshot of original number literal. When a number which originally was provided as a literal is never mutated until the end of the program then it is printed to the output in its original literal form. This also includes cases when the original literal would be truncated when converted to the IEEE754 double precision floating point number. she kept the receipt ๐งพ๐
โ Addition: +
The operator + takes two filters, applies them both to the same input, and adds the results together. What "adding" means depends on the types involved:
- Numbers are added by normal arithmetic.
- Arrays are added by being concatenated into a larger array.
- Strings are added by being joined into a larger string.
- Objects are added by merging, that is, inserting all the key-value pairs from both objects into a single combined object. If both objects contain a value for the same key, the object on the right of the
+wins. (For recursive merge use the*operator.) ๐
null can be added to any value, and returns the other value unchanged. she's flexible like that ๐
jq '.a + 1'
{"a": 7}
=> 8
jq '.a + .b'
{"a": [1,2], "b": [3,4]}
=> [1,2,3,4]
jq '.a + null'
{"a": 1}
=> 1
jq '.a + 1'
{}
=> 1
jq '{a: 1} + {b: 2} + {c: 3} + {a: 42}'
null
=> {"a": 42, "b": 2, "c": 3}
โ Subtraction: -
As well as normal arithmetic subtraction on numbers, the - operator can be used on arrays to remove all occurrences of the second array's elements from the first array. bye felicia ๐
jq '4 - .a'
{"a":3}
=> 1
jq '. - ["xml", "yaml"]'
["xml", "yaml", "json"]
=> ["json"]
โ๏ธโ Multiplication, division, modulo: *, /, %
These infix operators behave as expected when given two numbers. Division by zero raises an error. x % y computes x modulo y.
Multiplying a string by a number produces the concatenation of that string that many times. "x" * 0 produces "". โจ
Dividing a string by another splits the first using the second as separators.
Multiplying two objects will merge them recursively: this works like addition but if both objects contain a value for the same key, and the values are objects, the two are merged with the same strategy. layers on layers, it's giving recursive ๐
jq '10 / . * 3'
5
=> 6
jq '. / ", "'
"a, b,c,d, e"
=> ["a","b,c,d","e"]
jq '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}'
null
=> {"k": {"a": 0, "b": 2, "c": 3}}
jq '.[] | (1 / .)?'
[1,0,-1]
=> 1, -1
abs
The builtin function abs is defined naively as: if . < 0 then - . else . end.
For numeric input, this is the absolute value. See the section on the identity filter for the implications of this definition for numeric input. ๐
To compute the absolute value of a number as a floating point number, you may wish use fabs.
jq 'map(abs)'
[-10, -1.1, -1e-1]
=> [10,1.1,1e-1]
length
The builtin function length gets the length of various different types of value:
- The length of a string is the number of Unicode codepoints it contains (which will be the same as its JSON-encoded length in bytes if it's pure ASCII).
- The length of a number is its absolute value.
- The length of an array is the number of elements.
- The length of an object is the number of key-value pairs.
- The length of
nullis zero. - It is an error to use
lengthon a boolean. ๐
jq '.[] | length'
[[1,2], "string", {"a":2}, null, -5]
=> 2, 6, 1, 0, 5
utf8bytelength
The builtin function utf8bytelength outputs the number of bytes used to encode a string in UTF-8. counting them bytes fr fr ๐ฆ
jq 'utf8bytelength'
"\u03bc"
=> 2
๐ keys, keys_unsorted
The builtin function keys, when given an object, returns its keys in an array.
The keys are sorted "alphabetically", by unicode codepoint order. This is not an order that makes particular sense in any particular language, but you can count on it being the same for any two objects with the same set of keys, regardless of locale settings. consistent queen ๐
When keys is given an array, it returns the valid indices for that array: the integers from 0 to length-1.
The keys_unsorted function is just like keys, but if the input is an object then the keys will not be sorted, instead the keys will roughly be in insertion order.
jq 'keys'
{"abc": 1, "abcd": 2, "Foo": 3}
=> ["Foo", "abc", "abcd"]
jq 'keys'
[42,3,35]
=> [0,1,2]
has(key)
The builtin function has returns whether the input object has the given key, or the input array has an element at the given index. does she have it?? find out ๐
has($key) has the same effect as checking whether $key is a member of the array returned by keys, although has will be faster.
jq 'map(has("foo"))'
[{"foo": 42}, {}]
=> [true, false]
jq 'map(has(2))'
[[0,1], ["a","b","c"]]
=> [false, true]
in
The builtin function in returns whether or not the input key is in the given object, or the input index corresponds to an element in the given array. It is, essentially, an inversed version of has. the reverse uno card of the situation ๐
jq '.[] | in({"foo": 42})'
["foo", "bar"]
=> true, false
jq 'map(in([0,1]))'
[2, 0]
=> [false, true]
map(f), map_values(f) ๐
okay so for ANY filter f, map(f) and map_values(f) both go apply f to every single value inside the input array or object โ like, to the values of .[]. bestie.
And when nothing blows up (no errors, no drama), map(f) ALWAYS hands you back an array ๐. map_values(f) is more โจsituationalโจ: array in โ array out, object in โ object out.
When the input to map_values(f) is an object, the output object keeps the same keys as the input object... EXCEPT for those keys whose values, when piped to f, produce literally no values at all. those keys get dropped. bye ๐
The key difference between map(f) and map_values(f): the former just forms an array from ALL the values of ($x|f) for each value $x in the input array or object. But map_values(f) only uses first($x|f). only the first one!! ๐
Specifically, for object inputs, map_values(f) builds the output object by looking in turn at the value of first(.[$k]|f) for each key $k of the input. If that expression produces no values, the corresponding key gets dropped ๐ซก. Otherwise, the output object gets that value at the key $k.
Here are some examples to make the behavior of map and map_values on arrays crystal clear. These examples all assume the input is [1] in every case:
map(.+1) #=> [2]
map(., .) #=> [1,1]
map(empty) #=> []
map_values(.+1) #=> [2]
map_values(., .) #=> [1]
map_values(empty) #=> []
map(f) is equivalent to [.[] | f] and map_values(f) is equivalent to .[] |= f. โจ
And fr fr, those ARE their implementations. no cap.
jq ยดmap(.+1)ยด
[1,2,3]
=> [2,3,4]
jq ยดmap_values(.+1)ยด
{"a": 1, "b": 2, "c": 3}
=> {"a": 2, "b": 3, "c": 4}
jq ยดmap(., .)ยด
[1,2]
=> [1,1,2,2]
jq ยดmap_values(. // empty)ยด
{"a": null, "b": true, "c": false}
=> {"b":true}
pick(pathexps) ๐
Emit the projection of the input object or array defined by the specified sequence of path expressions โ such that if p is any one of these specifications, then (. | p) evaluates to the same value as (. | pick(pathexps) | p). yes bestie, it's a whole little self-consistency thing, iconic.
๐จ For arrays, negative indices and .[m:n] specifications should NOT be used. don't do it. i'm serious.
jq ยดpick(.a, .b.c, .x)ยด
{"a": 1, "b": {"c": 2, "d": 3}, "e": 4}
=> {"a":1,"b":{"c":2},"x":null}
jq ยดpick(.[2], .[0], .[0])ยด
[1,2,3,4]
=> [1,null,3]
path(path_expression) ๐ฆ
Outputs array representations of the given path expression in .. The outputs are arrays of strings (object keys) and/or numbers (array indices).
Path expressions are jq expressions like .a, but also .[]. There are two types of path expressions: ones that can match exactly, and ones that cannot. For example, .a.b.c is an exact match path expression, while .a[].b is not. ๐
path(exact_path_expression) will produce the array representation of the path expression even if it does not exist in . โ like, if . is null or an array or an object, doesn't matter, it still shows up.
path(pattern) will produce array representations of the paths matching pattern if the paths exist in ..
Note that the path expressions are not different from normal expressions. The expression path(..|select(type=="boolean")) outputs all the paths to boolean values in ., and only those paths. ๐ฏ
jq ยดpath(.a[0].b)ยด
null
=> ["a",0,"b"]
jq ยด[path(..)]ยด
{"a":[{"b":1}]}
=> [[],["a"],["a",0],["a",0,"b"]]
del(path_expression) ๐
The builtin function del removes a key and its corresponding value from an object. gone. deleted. not invited back.
jq ยดdel(.foo)ยด
{"foo": 42, "bar": 9001, "baz": 42}
=> {"bar": 9001, "baz": 42}
jq ยดdel(.[1, 2])ยด
["foo", "bar", "baz"]
=> ["foo"]
getpath(PATHS) ๐ธ
The builtin function getpath outputs the values in . found at each path in PATHS. very "go fetch my stuff" of it.
jq ยดgetpath(["a","b"])ยด
null
=> null
jq ยด[getpath(["a","b"], ["a","c"])]ยด
{"a":{"b":0, "c":1}}
=> [0, 1]
setpath(PATHS; VALUE) โจ
The builtin function setpath sets the PATHS in . to VALUE. putting things where they belong ๐
jq ยดsetpath(["a","b"]; 1)ยด
null
=> {"a": {"b": 1}}
jq ยดsetpath(["a","b"]; 1)ยด
{"a":{"b":0}}
=> {"a": {"b": 1}}
jq ยดsetpath([0,"a"]; 1)ยด
null
=> [{"a":1}]
delpaths(PATHS) ๐ฅ
The builtin function delpaths deletes the PATHS in .. PATHS must be an array of paths, where each path is an array of strings and numbers. yes, arrays of arrays. keep up bestie.
jq ยดdelpaths([["a","b"]])ยด
{"a":{"b":1},"x":{"y":2}}
=> {"a":{},"x":{"y":2}}
to_entries, from_entries, with_entries(f) ๐ง
These functions convert between an object and an array of key-value pairs. If to_entries is passed an object, then for each k: v entry in the input, the output array includes {"key": k, "value": v}.
from_entries does the exact opposite conversion, and with_entries(f) is a shorthand for to_entries | map(f) | from_entries โ super useful for doing some operation to all keys and values of an object. from_entries accepts "key", "Key", "name", "Name", "value", and "Value" as keys. yeah, all six. it's flexible like that ๐ซถ
jq ยดto_entriesยด
{"a": 1, "b": 2}
=> [{"key":"a", "value":1}, {"key":"b", "value":2}]
jq ยดfrom_entriesยด
[{"key":"a", "value":1}, {"key":"b", "value":2}]
=> {"a": 1, "b": 2}
jq ยดwith_entries(.key |= "KEY_" + .)ยด
{"a": 1, "b": 2}
=> {"KEY_a": 1, "KEY_b": 2}
select(boolean_expression) ๐
The function select(f) produces its input unchanged if f returns true for that input, and produces no output otherwise. it's giving bouncer at the club.
It's useful for filtering lists: [1,2,3] | map(select(. >= 2)) will give you [2,3]. periodt.
jq ยดmap(select(. >= 2))ยด
[1,5,3,0,7]
=> [5,3,7]
jq ยด.[] | select(.id == "second")ยด
[{"id": "first", "val": 1}, {"id": "second", "val": 2}]
=> {"id": "second", "val": 2}
arrays, objects, iterables, booleans, numbers, normals, finites, strings, nulls, values, scalars ๐
These built-ins select only inputs that are arrays, objects, iterables (arrays or objects), booleans, numbers, normal numbers, finite numbers, strings, null, non-null values, and non-iterables โ respectively. yes, in that exact order. a whole vibe check lineup ๐
jq ยด.[]|numbersยด
[[],{},1,"foo",null,true,false]
=> 1
empty ๐
empty returns no results. None at all. Not even null. literally nothing, the silence is deafening.
It's useful on occasion. You'll know if you need it :) ๐
jq ยด1, empty, 2ยด
null
=> 1, 2
jq ยด[1,2,empty,3]ยด
null
=> [1,2,3]
error, error(message) ๐ญ
Produces an error with the input value, or with the message given as the argument. Errors can be caught with try/catch; see below. ๐
jq ยดtry error catch .ยด
"error message"
=> "error message"
jq ยดtry error("invalid value: \(.)") catch .ยด
42
=> "invalid value: 42"
halt ๐
Stops the jq program with no further outputs. jq will exit with exit status 0. clean exit, no drama, we love a graceful departure.
halt_error, halt_error(exit_code) ๐จ
Stops the jq program with no further outputs. The input will be printed on stderr as raw output (i.e., strings will not have double quotes) with no decoration, not even a newline. bare. raw. unhinged formatting-wise.
The given exit_code (defaulting to 5) will be jq's exit status.
For example, "Error: something went wrong\n"|halt_error(1).
$__loc__ โญ
Produces an object with a "file" key and a "line" key, with the filename and line number where $__loc__ occurs, as values. so you always know where you are bestie ๐ซถ
jq ยดtry error("\($__loc__)") catch .ยด
null
=> "{\"file\":\"<top-level>\",\"line\":1}"
paths, paths(node_filter) ๐ธ
paths outputs the paths to all the elements in its input โ except it does not output the empty list, which would represent . itself. it skips the selfie.
paths(f) outputs the paths to any values for which f is true. That is, paths(type == "number") outputs the paths to all numeric values. ๐ข
jq ยด[paths]ยด
[1,[[],{"a":2}]]
=> [[0],[1],[1,0],[1,1],[1,1,"a"]]
jq ยด[paths(type == "number")]ยด
[1,[[],{"a":2}]]
=> [[0],[1,1,"a"]]
add, add(generator) โจ
The filter add takes as input an array, and produces as output the elements of the array added together. "Added" might mean summed, concatenated, or merged depending on the types of the elements of the input array โ the rules are exactly the same as those for the + operator (described above). ๐
If the input is an empty array, add returns null. (not zero! null! don't get it twisted)
add(generator) operates on the given generator rather than the input.
jq ยดaddยด
["a","b","c"]
=> "abc"
jq ยดaddยด
[1, 2, 3]
=> 6
jq ยดaddยด
[]
=> null
jq ยดadd(.[].a)ยด
[{"a":3}, {"a":5}, {"b":6}]
=> 8
any, any(condition), any(generator; condition) ๐ฅ
The filter any takes as input an array of boolean values, and produces true as output if any of the elements of the array are true.
If the input is an empty array, any returns false.
The any(condition) form applies the given condition to the elements of the input array.
The any(generator; condition) form applies the given condition to all the outputs of the given generator.
jq ยดanyยด
[true, false]
=> true
jq ยดanyยด
[false, false]
=> false
jq ยดanyยด
[]
=> false
all, all(condition), all(generator; condition) ๐
The filter all takes as input an array of boolean values, and produces true as output if all of the elements of the array are true.
The all(condition) form applies the given condition to the elements of the input array.
The all(generator; condition) form applies the given condition to all the outputs of the given generator.
If the input is an empty array, all returns true. (yes, vacuously true. it ate logic class ๐
)
jq ยดallยด
[true, false]
=> false
jq ยดallยด
[true, true]
=> true
jq ยดallยด
[]
=> true
flatten, flatten(depth) ๐ฆ
The filter flatten takes as input an array of nested arrays, and produces a flat array in which all arrays inside the original array have been recursively replaced by their values. You can pass an argument to it to specify how many levels of nesting to flatten.
flatten(2) is like flatten, but going only up to two levels deep. so it's a partial flatten, a lowkey flatten if you will.
jq ยดflattenยด
[1, [2], [[3]]]
=> [1, 2, 3]
jq ยดflatten(1)ยด
[1, [2], [[3]]]
=> [1, 2, [3]]
jq ยดflattenยด
[[]]
=> []
jq ยดflattenยด
[{"foo": "bar"}, [{"foo": "baz"}]]
=> [{"foo": "bar"}, {"foo": "baz"}]
๐ธ range(upto), range(from; upto), range(from; upto; by)
okay bestie, range is the function that justโฆ produces numbers for you. range(4; 10) gives you 6 numbers, from 4 (inclusive, she's invited) up to 10 (exclusive, she's not). And here's the thing โ the numbers come out as separate outputs, one by one. If you want them all wrapped up in an array instead, you go [range(4; 10)]. periodt.
- The one argument form generates numbers from 0 up to the number you gave, stepping by 1.
- The two argument form generates numbers from from to upto, stepping by 1.
- The three argument form generates numbers from from to upto, stepping by by.
jq `range(2; 4)`
null
=> 2, 3
jq `[range(2; 4)]`
null
=> [2,3]
jq `[range(4)]`
null
=> [0,1,2,3]
jq `[range(0; 10; 3)]`
null
=> [0,3,6,9]
jq `[range(0; 10; -1)]`
null
=> []
jq `[range(0; -5; -1)]`
null
=> [0,-1,-2,-3,-4]
โจ floor
floor returns the floor of its numeric input. like, the number rounded down to the nearest whole vibe. ๐
jq `floor`
3.14159
=> 3
๐ง sqrt
sqrt returns the square root of its numeric input. math queen behaviour.
jq `sqrt`
9
=> 3
๐ tonumber
tonumber parses its input as a number. It converts correctly-formatted strings into their numeric equivalent, leaves numbers alone (respectfully), and gives an error on everything else. no cap.
jq `.[] | tonumber`
[1, "1"]
=> 1, 1
๐ toboolean
toboolean parses its input as a boolean. Correctly-formatted strings get converted to their boolean equivalent, booleans get left alone, and anything else? error. that's it, that's the whole thing.
jq `.[] | toboolean`
["true", "false", true, false]
=> true, false, true, false
๐ tostring
tostring prints its input as a string. Strings are left unchanged, and every other value gets JSON-encoded.
jq `.[] | tostring`
[1, "1", [1]]
=> "1", "1", "[1]"
๐ type
type returns the type of its argument as a string โ and it's one of null, boolean, number, string, array or object.
jq `map(type)`
[0, false, [], {}, null, "hello"]
=> ["number", "boolean", "array", "object", "null", "string"]
๐ infinite, nan, isinfinite, isnan, isfinite, isnormal
so some arithmetic operations can yield infinities and "not a number" (NaN) values. here's the roster:
isinfinitereturnstrueif its input is infinite.isnanreturnstrueif its input is a NaN.infinitereturns a positive infinite value.nanreturns a NaN.isnormalreturnstrueif its input is a normal number.
โ ๏ธ heads up bestie: division by zero raises an error. Also โ currently most arithmetic operations operating on infinities, NaNs, and sub-normals do not raise errors.
jq `.[] | (infinite * .) < 0`
[-1, 1]
=> true, false
jq `infinite, nan | type`
null
=> "number", "number"
๐ sort, sort_by(path_expression)
The sort functions sort their input, which must be an array. Values are sorted in this exact order:
nullfalsetrue- numbers
- strings, in alphabetical order (by unicode codepoint value)
- arrays, in lexical order
- objects
The ordering for objects is a little complex: first they're compared by comparing their sets of keys (as arrays in sorted order), and if their keys are equal then the values are compared key by key.
sort_by lets you sort by a particular field of an object, or by applying any jq filter. sort_by(f) compares two elements by comparing the result of f on each element. When f produces multiple values, it firstly compares the first values, and the second values if the first values are equal, and so on โ lowkey thorough of her.
jq `sort`
[8,3,null,6]
=> [null,3,6,8]
jq `sort_by(.foo)`
[{"foo":4, "bar":10}, {"foo":3, "bar":10}, {"foo":2, "bar":1}]
=> [{"foo":2, "bar":1}, {"foo":3, "bar":10}, {"foo":4, "bar":10}]
jq `sort_by(.foo, .bar)`
[{"foo":4, "bar":10}, {"foo":3, "bar":20}, {"foo":2, "bar":1}, {"foo":3, "bar":10}]
=> [{"foo":2, "bar":1}, {"foo":3, "bar":10}, {"foo":3, "bar":20}, {"foo":4, "bar":10}]
๐ฆ group_by(path_expression)
group_by(.foo) takes an array as input, groups the elements that have the same .foo field into separate arrays, and produces all of those arrays as elements of one bigger array โ sorted by the value of the .foo field. it's giving organised.
Any jq expression works here, not just a field access โ swap .foo for whatever you want. The sorting order is the same as the one described in sort above.
jq `group_by(.foo)`
[{"foo":1, "bar":10}, {"foo":3, "bar":100}, {"foo":1, "bar":1}]
=> [[{"foo":1, "bar":10}, {"foo":1, "bar":1}], [{"foo":3, "bar":100}]]
๐ min, max, min_by(path_exp), max_by(path_exp)
Find the minimum or maximum element of the input array. simple as.
min_by(path_exp) and max_by(path_exp) let you specify a particular field or property to examine โ like, min_by(.foo) finds the object with the smallest foo field. main character detection, honestly.
jq `min`
[5,4,2,7]
=> 2
jq `max_by(.foo)`
[{"foo":1, "bar":14}, {"foo":2, "bar":3}]
=> {"foo":2, "bar":3}
๐ซถ unique, unique_by(path_exp)
unique takes an array as input and produces an array of the same elements, in sorted order, with the duplicates removed.
unique_by(path_exp) keeps only one element for each value obtained by applying the argument. think of it as making an array by taking one element out of every group that group produces. she's efficient. ๐
jq `unique`
[1,2,5,3,5,3,1,3]
=> [1,2,3,5]
jq `unique_by(.foo)`
[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3}, {"foo": 4, "bar": 5}]
=> [{"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]
jq `unique_by(length)`
["chunky", "bacon", "kitten", "cicada", "asparagus"]
=> ["bacon", "chunky", "asparagus"]
๐ฅ reverse
This function reverses an array. flip era. โจ
jq `reverse`
[1,2,3,4]
=> [4,3,2,1]
๐ contains(element)
The filter contains(b) produces true if b is completely contained within the input. here's the fine print:
- A string B is contained in a string A if B is a substring of A.
- An array B is contained in an array A if all elements in B are contained in any element in A.
- An object B is contained in object A if all of the values in B are contained in the value in A with the same key.
- All other types are assumed to be contained in each other if they are equal.
jq `contains("bar")`
"foobar"
=> true
jq `contains(["baz", "bar"])`
["foobar", "foobaz", "blarp"]
=> true
jq `contains(["bazzzzz", "bar"])`
["foobar", "foobaz", "blarp"]
=> false
jq `contains({foo: 12, bar: [{barp: 12}]})`
{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}
=> true
jq `contains({foo: 12, bar: [{barp: 15}]})`
{"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]}
=> false
๐ธ indices(s)
Outputs an array containing the indices in . where s occurs. The input may be an array โ in which case, if s is an array, the indices output will be those where all elements in . match those of s.
jq `indices(", ")`
"a,b, cd, efg, hijk"
=> [3,7,12]
jq `indices(1)`
[0,1,2,1,3,1,4]
=> [1,3,5]
jq `indices([1,2])`
[0,1,2,3,1,4,2,5,1,2,6,7]
=> [1,8]
๐ index(s), rindex(s)
Outputs the index of the first (index) or last (rindex) occurrence of s in the input.
jq `index(", ")`
"a,b, cd, efg, hijk"
=> 3
jq `index(1)`
[0,1,2,1,3,1,4]
=> 1
jq `index([1,2])`
[0,1,2,3,1,4,2,5,1,2,6,7]
=> 1
jq `rindex(", ")`
"a,b, cd, efg, hijk"
=> 12
jq `rindex(1)`
[0,1,2,1,3,1,4]
=> 5
jq `rindex([1,2])`
[0,1,2,3,1,4,2,5,1,2,6,7]
=> 8
๐ง inside
The filter inside(b) produces true if the input is completely contained within b. it's, essentially, an inversed version of contains. the plot twist. ๐ญ
jq `inside("foobar")`
"bar"
=> true
jq `inside(["foobar", "foobaz", "blarp"])`
["baz", "bar"]
=> true
jq `inside(["foobar", "foobaz", "blarp"])`
["bazzzzz", "bar"]
=> false
jq `inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})`
{"foo": 12, "bar": [{"barp": 12}]}
=> true
jq `inside({"foo": 12, "bar":[1,2,{"barp":12, "blip":13}]})`
{"foo": 12, "bar": [{"barp": 15}]}
=> false
โญ startswith(str)
Outputs true if . starts with the given string argument.
jq `[.[]|startswith("foo")]`
["fo", "foo", "barfoo", "foobar", "barfoob"]
=> [false, true, false, true, false]
โญ endswith(str)
Outputs true if . ends with the given string argument.
jq `[.[]|endswith("foo")]`
["foobar", "barfoo"]
=> [false, true]
๐ combinations, combinations(n)
Outputs all combinations of the elements of the arrays in the input array. If you give it an argument n, it outputs all combinations of n repetitions of the input array.
jq `combinations`
[[1,2], [3, 4]]
=> [1, 3], [1, 4], [2, 3], [2, 4]
jq `combinations(2)`
[0, 1]
=> [0, 0], [0, 1], [1, 0], [1, 1]
๐ ltrimstr(str)
Outputs its input with the given prefix string removed, if it starts with it.
jq `[.[]|ltrimstr("foo")]`
["fo", "foo", "barfoo", "foobar", "afoo"]
=> ["fo","","barfoo","bar","afoo"]
๐ rtrimstr(str)
Outputs its input with the given suffix string removed, if it ends with it.
jq `[.[]|rtrimstr("foo")]`
["fo", "foo", "barfoo", "foobar", "foob"]
=> ["fo","","bar","foobar","foob"]
๐ trimstr(str)
Outputs its input with the given string removed at both ends, if it starts or ends with it.
jq `[.[]|trimstr("foo")]`
["fo", "foo", "barfoo", "foobarfoo", "foob"]
=> ["fo","","bar","bar","b"]
๐ trim, ltrim, rtrim
trimtrims both leading and trailing whitespace.ltrimtrims only leading (left side) whitespace.rtrimtrims only trailing (right side) whitespace.
Whitespace characters are the usual " ", "\n" "\t", "\r" and also all characters in the Unicode character database with the whitespace property. note that what counts as whitespace might change in the future. ๐
jq `trim, ltrim, rtrim`
" abc "
=> "abc", "abc ", " abc"
๐ฆ explode
Converts an input string into an array of the string's codepoint numbers.
jq 'explode'
"foobar"
=> [102,111,111,98,97,114]
โจ implode โจ
Bestie it's literally the inverse of explode. That's it, that's the whole thing ๐ซถ
jq 'implode'
[65, 66, 67]
=> "ABC"
๐ธ split(str) ๐ธ
Splits an input string on the separator argument you give it. Simple. Clean. Iconic.
Heads up though โ split can also split on regex matches when you call it with two arguments (that's a whole thing, peep the regular expressions section below ๐).
jq 'split(", ")'
"a, b,c,d, e, "
=> ["a","b,c,d","e",""]
๐ join(str) ๐
Joins the array of elements you feed it as input, using the argument as the separator. It's the inverse of split โ like, fr fr: running split("foo") | join("foo") over any input string hands you back that exact same input string. Balance. ๐
Some deets you're gonna wanna know:
- Numbers and booleans in the input get converted to strings.
nullvalues are treated as empty strings.- Arrays and objects in the input are not supported. Not today, not ever ๐
jq 'join(", ")'
["a","b,c,d","e"]
=> "a, b,c,d, e"
jq 'join(" ")'
["a",1,2.3,true,null,false]
=> "a 1 2.3 true false"
(spot the double space โ that's the null chilling as an empty string ๐)
๐ ascii_downcase, ascii_upcase ๐
Emit a copy of the input string with its alphabetic characters (just a-z and A-Z) converted to the case you asked for.
jq 'ascii_upcase'
"useful but not for รฉ"
=> "USEFUL BUT NOT FOR รฉ"
Note that รฉ is out here living its best untouched life, because this is ascii case conversion, not the full Unicode situation โจ
๐ฆ while(cond; update) ๐ฆ
The while(cond; update) function lets you repeatedly apply update to . until cond is false. Keep going, keep going, stop when the vibes say stop.
Heads up:while(cond; update)is internally defined as a recursive jq function. Recursive calls withinwhilewill not consume additional memory ifupdateproduces at most one output for each input. See advanced topics below.
jq '[while(.<100; .*2)]'
1
=> [1,2,4,8,16,32,64]
๐
repeat(exp) ๐
repeat(exp) lets you repeatedly apply expression exp to . until an error is raised. Basically "keep doing it until it breaks" energy, which honestly? Same.
Heads up again:repeat(exp)is internally defined as a recursive jq function. Recursive calls withinrepeatwill not consume additional memory ifexpproduces at most one output for each input. See advanced topics below.
jq '[repeat(.*2, error)?]'
1
=> [2]
๐ until(cond; next) ๐
The until(cond; next) function allows you to repeatedly apply the expression next โ first to ., then to its own output โ until cond is true. For example, this can be used to implement a factorial function (see below ๐).
And yes, the third one:until(cond; next)is internally defined as a recursive jq function. Recursive calls withinuntil()will not consume additional memory ifnextproduces at most one output for each input. See advanced topics below.
jq '[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]'
4
=> 24
๐ฅ recurse(f), recurse, recurse(f; condition) ๐ฅ
OK so recurse(f) lets you search through a recursive structure and extract the interesting data from all the levels. Picture this: your input represents a filesystem.
{"name": "/", "children": [
{"name": "/bin", "children": [
{"name": "/bin/ls", "children": []},
{"name": "/bin/sh", "children": []}]},
{"name": "/home", "children": [
{"name": "/home/stephen", "children": [
{"name": "/home/stephen/jq", "children": []}]}]}]}
Now say you want to extract all the filenames in there. You'd need .name, .children[].name, .children[].children[].name, and so on forever. Instead of typing that nightmare, you do this:
recurse(.children[]) | .name
- When called without an argument,
recurseis equivalent torecurse(.[]?). recurse(f)is identical torecurse(f; true)and can be used without concerns about recursion depth. ๐recurse(f; condition)is a generator which begins by emitting.and then emits in turn.|f,.|f|f,.|f|f|f, ... so long as the computed value satisfies the condition. Like, to generate all the integers, at least in principle, you could writerecurse(.+1; true).
The recursive calls in recurse will not consume additional memory whenever f produces at most a single output for each input.
jq 'recurse(.foo[])'
{"foo":[{"foo": []}, {"foo":[{"foo":[]}]}]}
=> {"foo":[{"foo":[]},{"foo":[{"foo":[]}]}]}, {"foo":[]}, {"foo":[{"foo":[]}]}, {"foo":[]}
jq 'recurse'
{"a":0,"b":[1]}
=> {"a":0,"b":[1]}, 0, [1], 1
jq 'recurse(. * .; . < 20)'
2
=> 2, 4, 16
๐ walk(f) ๐
The walk(f) function applies f recursively to every component of the input entity. The order is the whole point, so listen up:
- When an array is encountered,
fis first applied to its elements and then to the array itself. - When an object is encountered,
fis first applied to all the values and then to the object.
In practice, f will usually test the type of its input, as illustrated below. The first example highlights how useful it is to process the elements of an array of arrays before processing the array itself. The second example shows how all the keys of all the objects within the input can be considered for alteration.
jq 'walk(if type == "array" then sort else . end)'
[[4, 1, 7], [8, 5, 2], [3, 6, 9]]
=> [[1,4,7],[2,5,8],[3,6,9]]
jq 'walk( if type == "object" then with_entries( .key |= sub( "^_+"; "") ) else . end )'
[ { "_a": { "__b": 2 } } ]
=> [{"a":{"b":2}}]
๐ have_literal_numbers ๐
This builtin returns true if jq's build configuration includes support for preservation of input number literals. It's giving "do I have this feature or not, bestie."
๐ have_decnum ๐
This builtin returns true if jq was built with "decnum", which is the current literal number preserving numeric backend implementation for jq.
๐ $JQ_BUILD_CONFIGURATION ๐
This builtin binding shows the jq executable's build configuration. Its value has no particular format, but it can be expected to be at least the ./configure command-line arguments, and may be enriched in the future to include the version strings for the build tooling used.
Note that this can be overridden in the command-line with --arg and related options. ๐
๐ธ $ENV, env ๐ธ
$ENV is an object representing the environment variables as set when the jq program started.
env outputs an object representing jq's current environment.
At the moment there is no builtin for setting environment variables. No setting, only reading ๐ญ
jq '$ENV.PAGER'
null
=> "less"
jq 'env.PAGER'
null
=> "less"
๐ง transpose ๐ง
Transpose a possibly jagged matrix (an array of arrays). Rows are padded with nulls so the result is always rectangular. No jagged edges left, we love a clean rectangle ๐
jq 'transpose'
[[1], [2,3]]
=> [[1,2],[null,3]]
โญ bsearch(x) โญ
bsearch(x) conducts a binary search for x in the input array.
- If the input is sorted and contains
x, thenbsearch(x)will return its index in the array. - Otherwise, if the array is sorted, it will return
(-1 - ix)whereixis an insertion point such that the array would still be sorted after the insertion ofxatix. - If the array is not sorted,
bsearch(x)will return an integer that is probably of no interest. ๐ Garbage in, garbage out, no cap.
jq 'bsearch(0)'
[0,1]
=> 0
jq 'bsearch(0)'
[1,2,3]
=> -1
jq 'bsearch(4) as $ix | if $ix < 0 then .[-(1+$ix)] = 4 else . end'
[1,2,3]
=> [1,2,3,4]
๐ซถ String interpolation: \(exp) ๐ซถ
Inside a string, you can put an expression inside parens after a backslash. Whatever the expression returns will be interpolated into the string. It's like mad libs but make it functional โจ
jq '"The input was \(.), which is one less than \(.+1)"'
42
=> "The input was 42, which is one less than 43"
๐ Convert to/from JSON ๐
The tojson and fromjson builtins dump values as JSON texts or parse JSON texts into values, respectively. The tojson builtin differs from tostring in that tostring returns strings unmodified, while tojson encodes strings as JSON strings.
jq '[.[]|tostring]'
[1, "foo", ["foo"]]
=> ["1","foo","[\"foo\"]"]
jq '[.[]|tojson]'
[1, "foo", ["foo"]]
=> ["1","\"foo\"","[\"foo\"]"]
jq '[.[]|tojson|fromjson]'
[1, "foo", ["foo"]]
=> [1,"foo",["foo"]]
๐ Format strings and escaping ๐
The @foo syntax is used to format and escape strings, which is useful for building URLs, documents in a language like HTML or XML, and so forth. @foo can be used as a filter on its own. Here are the possible escapings, bestie:
@textโ Callstostring, see that function for details.@jsonโ Serializes the input as JSON.@htmlโ Applies HTML/XML escaping, by mapping the characters<>&'"to their entity equivalents<,>,&,',".@uriโ Applies percent-encoding, by mapping all reserved URI characters to a%XXsequence.@uridโ The inverse of@uri, applies percent-decoding, by mapping all%XXsequences to their corresponding URI characters.@csvโ The input must be an array, and it is rendered as CSV with double quotes for strings, and quotes escaped by repetition.@tsvโ The input must be an array, and it is rendered as TSV (tab-separated values). Each input array will be printed as a single line. Fields are separated by a single tab (ascii0x09). Input characters line-feed (ascii0x0a), carriage-return (ascii0x0d), tab (ascii0x09) and backslash (ascii0x5c) will be output as escape sequences\n,\r,\t,\\respectively.@shโ The input is escaped suitable for use in a command-line for a POSIX shell. If the input is an array, the output will be a series of space-separated strings.@base64โ The input is converted to base64 as specified by RFC 4648.@base64dโ The inverse of@base64, input is decoded as specified by RFC 4648.
โ ๏ธ Note: for @base64d, if the decoded string is not UTF-8, the results are undefined. So like, don't come crying to me, it's literally undefined ๐
This syntax can be combined with string interpolation in a useful way. You can follow a @foo token with a string literal. The contents of the string literal will not be escaped. However, all interpolations made inside that string literal will be escaped. For instance,
@uri "https://www.google.com/search?q=\(.search)"
will produce the following output for the input {"search":"what is jq?"}:
"https://www.google.com/search?q=what%20is%20jq%3F"
Note that the slashes, question mark, etc. in the URL are not escaped, as they were part of the string literal. Only the interpolated bit got the glow-up ๐
jq '@html'
"This works if x < y"
=> "This works if x < y"
jq '@sh "echo \(.)"'
"O'Hara's Ale"
=> "echo 'O'\''Hara'\''s Ale'"
jq '@base64'
"This is a message"
=> "VGhpcyBpcyBhIG1lc3NhZ2U="
jq '@base64d'
"VGhpcyBpcyBhIG1lc3NhZ2U="
=> "This is a message"
โจ Dates โจ
okay so time stuff ๐ฐ๏ธ โ jq has your back with some basic date handling, both the high-level glow-up versions AND the low-level gremlin versions. and hear me loud: every single one of these deals exclusively with time in UTC. no cap. ๐
fromdateiso8601โ parses datetimes in the ISO 8601 format into a number of seconds since the Unix epoch (1970-01-01T00:00:00Z). that's the origin story right there.todateiso8601โ does the exact inverse. round trip, slay. ๐fromdateโ parses datetime strings. rn it only supports ISO 8601 datetime strings, but bestie, in the future it's gonna attempt to parse datetime strings in more formats. growth era. ๐ฑtodateโ literally just an alias fortodateiso8601. same energy.nowโ outputs the current time, in seconds since the Unix epoch. it's giving "what time is it" but make it Unix. โฐ
also there's the low-level crew โ jq's direct interfaces to the C-library time functions: strptime, strftime, strflocaltime, mktime, gmtime, and localtime. for the format strings that strptime and strftime use, go check your host operating system's documentation, bestie, that's a you-and-your-OS moment. ๐
ngl these are not necessarily stable interfaces in jq, especially when it comes to their localization functionality. proceed with cute caution. ๐ซถ
gmtimeโ consumes a number of seconds since the Unix epoch and outputs a "broken down time" representation of Greenwich Mean Time as an array of numbers representing, in this exact order: the year, the month (zero-based, yes i know ๐ญ), the day of the month (one-based), the hour of the day, the minute of the hour, the second of the minute, the day of the week, and the day of the year โ all one-based unless otherwise stated. also heads up: the day of the week number may be wrong on some systems for dates before March 1st 1900, or after December 31 2099. archaic behavior fr. ๐localtimeโ works just likegmtime, but using the local timezone setting. home turf edition. ๐mktimeโ consumes "broken down time" representations of time output bygmtimeandstrptime. it's the reverse-direction bestie.strptime(fmt)โ parses input strings matching the fmt argument. the output is in the "broken down time" representation consumed bymktimeand output bygmtime. ๐คstrftime(fmt)โ formats a time (GMT) with the given format. andstrflocaltimedoes the same thing, but using the local timezone setting.- the format strings for
strptimeandstrftimeare described in typical C library documentation. the format string for ISO 8601 datetime is"%Y-%m-%dT%H:%M:%SZ". ๐
aaaand one more warning because it matters: jq may not support some or all of this date functionality on some systems. in particular, the %u and %j specifiers for strptime(fmt) are not supported on macOS. ๐
jq 'fromdate'
"2015-03-05T23:51:47Z"
=> 1425599507
jq 'strptime("%Y-%m-%dT%H:%M:%SZ")'
"2015-03-05T23:51:47Z"
=> [2015,2,5,23,51,47,4,63]
jq 'strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'
"2015-03-05T23:51:47Z"
=> 1425599507
๐๏ธ SQL-Style Operators ๐๏ธ
bestie, jq also serves up a few SQL-style operators. database girlies, this one's for you. ๐
INDEX(stream; index_expression):
this builtin produces an object whose keys are computed by the given index expression applied to each value from the given stream. key vibes computed on the fly. โจ
JOIN($idx; stream; idx_expr; join_expr):
this builtin joins the values from the given stream to the given index. the index's keys are computed by applying the given index expression to each value from the given stream. then an array of the value in the stream and the corresponding value from the index gets fed to the given join expression to produce each result. two worlds, one array, one result. ๐
JOIN($idx; stream; idx_expr):
same as JOIN($idx; stream; idx_expr; .). shorthand era, we love a default.
JOIN($idx; idx_expr):
this builtin joins the input . to the given index, applying the given index expression to . to compute the index key. the join operation is as described above. ๐
IN(s):
this builtin outputs true if . appears in the given stream, otherwise it outputs false. simple. iconic. factual. โ
IN(source; s):
this builtin outputs true if any value in the source stream appears in the second stream, otherwise it outputs false. two streams walk into a bar... ๐ธ
๐งฐ builtins ๐งฐ
returns a list of all builtin functions, in the format name/arity. and here's the thing that trips people up: since functions with the same name but different arities are considered separate functions, all/0, all/1, and all/2 would all be present in the list. three whole entries for one name. that's not a bug, that's just arity being arity. ๐
so when you run it, expect a whole crowd. ๐
โจ CONDITIONALS AND COMPARISONS โจ
ok bestie this is where jq gets โจopinionatedโจ and honestly? valid of it.
๐ ==, !=
The expression a == b will produce true if the results of evaluating a and b are equal (meaning they represent equivalent JSON values), and false otherwise. And like, strings are never considered equal to numbers, no matter how much they wanna be. When jq checks if two JSON objects are equal, the ordering of keys does not matter โ it's the vibes, not the layout. ๐ซถ
If you're coming from JavaScript, pls note: jq's == is doing the JavaScript === thing, the "strict equality" operator. no type-coercion games here, we don't do that. ๐
!= is "not equal", and a != b returns the exact opposite value of a == b.
jq '. == false'
null
=> false
jq '. == {"b": {"d": (4 + 1e-20), "c": 3}, "a":1}'
{"a":1, "b": {"c": 3, "d": 4}}
=> true
jq '.[] == 1'
[1, 1.0, "1", "banana"]
=> true, true, false, false
๐ธ if-then-else-end
if A then B else C end acts the same as B if A produces a value other than false or null, but acts the same as C otherwise. simple as that, no cap.
if A then B end is the same as if A then B else . end. Meaning: the else branch is optional, and if it's absent it's the same as .. This also applies to elif with an absent ending else branch.
So checking for false or null is a way simpler notion of "truthiness" than what JavaScript or Python do, and that means sometimes you gotta be more explicit about the condition you actually want. For example, you can't test whether a string is empty using if .name then A else B end โ you'll need something like if .name == "" then A else B end instead. yeah. it's giving "be specific". ๐
If the condition A produces multiple results, then B is evaluated once for each result that is not false or null, and C is evaluated once for each false or null. so many branches, so little time.
More cases can be added to an if using elif A then B syntax.
jq 'if . == 0 then
"zero"
elif . == 1 then
"one"
else
"many"
end'
2
=> "many"
๐ซ >, >=, <=, <
The comparison operators >, >=, <=, < return whether their left argument is greater than, greater than or equal to, less than or equal to, or less than their right argument (respectively). yes this is just math class but cute. ๐
The ordering is the same as the one described for sort, above. ๐
jq '. < 5'
2
=> true
๐ and, or, not
jq supports the normal Boolean operators and, or, not. They have the same standard of truth as if expressions โ false and null are considered "false values", and anything else is a "true value". iconic tbh.
If an operand of one of these operators produces multiple results, the operator itself will produce a result for each input. yeah it multiplies. it's built different.
not is actually a builtin function rather than an operator, so it's called as a filter you can pipe stuff into, not with special syntax โ like .foo and .bar | not. iykyk.
These three only produce the values true and false, and so they're only useful for genuine Boolean operations, not the common Perl/Python/Ruby idiom of "value_that_may_be_null or default". If you want that flavor of "or" โ picking between two values instead of evaluating a condition โ see the // operator below. โฌ๏ธ
jq '42 and "a string"'
null
=> true
jq '(true, false) or false'
null
=> true, false
jq '(true, true) and (true, false)'
null
=> true, false, true, false
jq '[true, false | not]'
null
=> [false, true]
๐ Alternative operator: //
The // operator produces all the values of its left-hand side that are neither false nor null. If the left-hand side produces no values other than false or null, then // produces all the values of its right-hand side.
A filter of the form a // b produces all the results of a that are not false or null. If a produces no results, or no results other than false or null, then a // b produces the results of b.
This is so useful for providing defaults: .foo // 1 will evaluate to 1 if there's no .foo element in the input. It's similar to how or is sometimes used in Python (except jq's or operator is reserved for strictly Boolean operations, so no crossover episodes ๐).
Note:some_generator // defaults_hereis not the same assome_generator | . // defaults_here. The latter will produce default values for all non-false, non-null values of the left-hand side, while the former will not. Precedence rules can make this confusing, bestie. For example, infalse, 1 // 2the left-hand side of//is1, notfalse, 1โfalse, 1 // 2parses the same way asfalse, (1 // 2). And in(false, null, 1) | . // 42the left-hand side of//is., which always produces just one value, while in(false, null, 1) // 42the left-hand side is a generator of three values, and since it produces a value other thanfalseandnull, the default42is not produced.
jq 'empty // 42'
null
=> 42
jq '.foo // 42'
{"foo": 19}
=> 19
jq '.foo // 42'
{}
=> 42
jq '(false, null, 1) // 42'
null
=> 1
jq '(false, null, 1) | . // 42'
null
=> 42, 42, 1
๐ฆ try-catch
Errors can be caught using try EXP catch EXP. The first expression is executed, and if it fails then the second is executed with the error message. The output of the handler, if any, is output as if it had been the output of the expression to try. so like a little safety net, a blankie for your filters ๐ซถ
The try EXP form uses empty as the exception handler.
jq 'try .a catch ". is not an object"'
true
=> ". is not an object"
jq '[.[]|try .a]'
[{}, true, {"a":1}]
=> [null, 1]
jq 'try error("some exception") catch .'
true
=> "some exception"
๐ง Breaking out of control structures
A convenient use of try/catch is to break out of control structures like reduce, foreach, while, and so on. escape hatch energy. ๐ชโจ
For example:
# Repeat an expression until it raises "break" as an
# error, then stop repeating without re-raising the error.
# But if the error caught is not "break" then re-raise it.
try repeat(exp) catch if .=="break" then empty else error
jq has a syntax for named lexical labels to "break" or "go (back) to":
label $out | ... break $out ...
The break $label_name expression will cause the program to act as though the nearest (to the left) label $label_name produced empty.
The relationship between the break and the corresponding label is lexical: the label has to be "visible" from the break.
To break out of a reduce, for example:
label $out | reduce .[] as $item (null; if .==false then break $out else ... end)
heads up: the following jq program produces a syntax error:break $outbecause no label$outis visible. it's just out there alone in the world, no label to come home to. ๐ญ
๐
Error Suppression / Optional Operator: ?
The ? operator, used as EXP?, is shorthand for try EXP. that's it. that's the whole thing. lowkey the easiest glow-up in the whole language.
jq '[.[] | .a?]'
[{}, true, {"a":1}]
=> [null, 1]
jq '[.[] | tonumber?]'
["1", "invalid", "3", 4]
=> [1, 3, 4]
๐ REGULAR EXPRESSIONS ๐
okay bestie, regex time, and yes it's giving โจmain characterโจ energy. jq uses the Oniguruma regular expression library โ same one PHP, TextMate, Sublime Text, etc. run with โ so this whole writeup is gonna focus on the jq-specific stuff, not a general regex crash course ๐ซถ.
Oniguruma supports several flavors of regular expression, so like, super important to know: jq uses the "Perl NG" (Perl with named groups) flavor. no cap.
The jq regex filters are defined so you can use them with one of these patterns:
STRING | FILTER(REGEX)
STRING | FILTER(REGEX; FLAGS)
STRING | FILTER([REGEX])
STRING | FILTER([REGEX, FLAGS])
where, bestie, let's break it down:
STRING,REGEX, andFLAGSare jq strings and they're subject to jq string interpolation ๐REGEX, after string interpolation, should be a valid regular expressionFILTERis one oftest,match, orcapture, as described below โจ
Since REGEX must evaluate to a JSON string, some characters you need to form a regular expression have to be escaped. for example, the regular expression \s (which means "a whitespace character") would be written as "\\s". iconic, honestly.
FLAGS is a string made up of one or more of the supported flags:
gโ Global search (find all matches, not just the first) ๐ฅiโ Case insensitive searchmโ Multi line mode (.will match newlines)nโ Ignore empty matchespโ Bothsandmmodes are enabledsโ Single line mode (^->\A,$->\Z)lโ Find longest possible matchesxโ Extended regex format (ignore whitespace and comments)
to match a whitespace with the x flag, use \s, like:
jq -n '"a b" | test("a\\sb"; "x")'
ngl, certain flags may also be specified inside REGEX, e.g.
jq -n '("test", "TEst", "teST", "TEST") | test("(?i)te(?-i)st")'
evaluates to: true, true, false, false. the way it groups... obsessed ๐
test(val), test(regex; flags)
Like match, but it does not return match objects โ only true or false for whether or not the regex matches the input. so basically a vibe check โ
.
jq 'test("foo")'
"foo"
=> true
jq '.[] | test("a b c # spaces are ignored"; "ix")'
["xabcd", "ABC"]
=> true, true
match(val), match(regex; flags)
match outputs an object for each match it finds ๐. Matches have the following fields:
offsetโ offset in UTF-8 codepoints from the beginning of the inputlengthโ length in UTF-8 codepoints of the matchstringโ the string that it matchedcapturesโ an array of objects representing capturing groups
Capturing group objects have the following fields:
offsetโ offset in UTF-8 codepoints from the beginning of the inputlengthโ length in UTF-8 codepoints of this capturing groupstringโ the string that was capturednameโ the name of the capturing group (ornullif it was unnamed)
Capturing groups that did not match anything return an offset of -1.
jq 'match("(abc)+"; "g")'
"abc abc"
=> {"offset": 0, "length": 3, "string": "abc", "captures": [{"offset": 0, "length": 3, "string": "abc", "name": null}]}, {"offset": 4, "length": 3, "string": "abc", "captures": [{"offset": 4, "length": 3, "string": "abc", "name": null}]}
jq 'match("foo")'
"foo bar foo"
=> {"offset": 0, "length": 3, "string": "foo", "captures": []}
jq 'match(["foo", "ig"])'
"foo bar FOO"
=> {"offset": 0, "length": 3, "string": "foo", "captures": []}, {"offset": 8, "length": 3, "string": "FOO", "captures": []}
jq 'match("foo (?<bar123>bar)? foo"; "ig")'
"foo bar foo foo foo"
=> {"offset": 0, "length": 11, "string": "foo bar foo", "captures": [{"offset": 4, "length": 3, "string": "bar", "name": "bar123"}]}, {"offset": 12, "length": 8, "string": "foo foo", "captures": [{"offset": -1, "length": 0, "string": null, "name": "bar123"}]}
jq '[ match("."; "g")] | length'
"abc"
=> 3
capture(val), capture(regex; flags)
Collects the named captures into a JSON object, with the name of each capture as the key, and the matched string as the corresponding value. a little keyโvalue moment ๐
jq 'capture("(?<a>[a-z]+)-(?<n>[0-9]+)")'
"xyzzy-14"
=> { "a": "xyzzy", "n": "14" }
scan(regex), scan(regex; flags)
Emit a stream of the non-overlapping substrings of the input that match the regex, in accordance with the flags, if any have been specified. if there's no match, the stream is empty ๐ญ. To capture all the matches for each input string, use the idiom [ expr ], e.g. [ scan(regex) ]. If the regex contains capturing groups, the filter emits a stream of arrays, each of which contains the captured strings.
jq 'scan("c")'
"abcdefabc"
=> "c", "c"
jq 'scan("(a+)(b+)")'
"abaabbaaabbb"
=> ["a","b"], ["aa","bb"], ["aaa","bbb"]
split(regex; flags)
Splits an input string on each regex match โ๏ธ.
For backwards compatibility, when called with a single argument, split splits on a string, not a regex. (iykyk โ don't get caught out by that one.)
jq 'split(", *"; null)'
"ab,cd, ef"
=> ["ab","cd","ef"]
splits(regex), splits(regex; flags)
These give you the same results as their split counterparts, but as a stream instead of an array ๐.
jq 'splits(", *")'
"ab,cd, ef, gh"
=> "ab", "cd", "ef", "gh"
jq 'splits(",? *"; "n")'
"ab,cd ef, gh"
=> "ab", "cd", "ef", "gh"
sub(regex; tostring), sub(regex; tostring; flags)
Emit the string you get by replacing the first match of regex in the input string with tostring, after interpolation. tostring should be a jq string or a stream of such strings, each of which may contain references to named captures. The named captures are, in effect, presented as a JSON object (as constructed by capture) to tostring, so a reference to a captured variable named "x" would take the form: "\(.x)". slay ๐
jq 'sub("[^a-z]*(?<x>[a-z]+)"; "Z\(.x)"; "g")'
"123abc456def"
=> "ZabcZdef"
jq '[sub("(?<a>.)"; "\(.a|ascii_upcase)", "\(.a|ascii_downcase)")]'
"aB"
=> ["AB","aB"]
gsub(regex; tostring), gsub(regex; tostring; flags)
gsub is like sub but all the non-overlapping occurrences of the regex get replaced by tostring, after interpolation ๐ฅ. If the second argument is a stream of jq strings, then gsub will produce a corresponding stream of JSON strings.
jq 'gsub("(?<x>.)[^a]*"; "+\(.x)-")'
"Abcabc"
=> "+A-+a-"
jq '[gsub("p"; "a", "b")]'
"p"
=> ["a","b"]
๐ ADVANCED FEATURES ๐
Variables are an absolute necessity in most programming languages, but in jq they're relegated to an "advanced feature". bestie. the disrespect honestly ๐.
In most languages, variables are the only means of passing around data. If you calculate a value, and you want to use it more than once, you'll need to store it in a variable. To pass a value to another part of the program, you'll need that part of the program to define a variable (as a function parameter, object member, or whatever) in which to place the data.
It's also possible to define functions in jq, although this is a feature whose biggest use is defining jq's standard library (many jq functions such as map and select are in fact written in jq ๐ธ).
jq has reduction operators, which are very powerful but a bit tricky ๐ . Again, these are mostly used internally, to define some useful bits of jq's standard library.
It may not be obvious at first, but jq is all about generators (yes, as often found in other languages). Some utilities are provided to help deal with generators.
Some minimal I/O support (besides reading JSON from standard input, and writing JSON to standard output) is available.
Finally, there is a module/library system โจ.
Variable / Symbolic Binding Operator: ... as $identifier | ...
In jq, all filters have an input and an output, so manual plumbing is not necessary to pass a value from one part of a program to the next ๐. Many expressions, for instance a + b, pass their input to two distinct subexpressions (here a and b are both passed the same input), so variables aren't usually necessary in order to use a value twice.
For instance, calculating the average value of an array of numbers requires a few variables in most languages โ at least one to hold the array, maybe one for each element or for a loop counter. In jq, it's simply add / length โ the add expression is given the array and produces its sum, and the length expression is given the array and produces its length. look ma, no variables ๐
.
So, there's generally a cleaner way to solve most problems in jq than defining variables. Still, sometimes they do make things easier, so jq lets you define variables using expression as $variable. All variable names start with $. Here's a slightly uglier version of the array-averaging example:
length as $array_length | add / $array_length
We'll need a more complicated problem to find a situation where using variables actually makes our lives easier ๐.
Suppose we have an array of blog posts, with "author" and "title" fields, and another object which is used to map author usernames to real names. Our input looks like:
{"posts": [{"title": "First post", "author": "anon"},
{"title": "A well-written article", "author": "person1"}],
"realnames": {"anon": "Anonymous Coward",
"person1": "Person McPherson"}}
We want to produce the posts with the author field containing a real name, as in:
{"title": "First post", "author": "Anonymous Coward"}
{"title": "A well-written article", "author": "Person McPherson"}
We use a variable, $names, to store the realnames object, so that we can refer to it later when looking up author usernames:
.realnames as $names | .posts[] | {title, author: $names[.author]}
The expression exp as $x | ... means: for each value of expression exp, run the rest of the pipeline with the entire original input, and with $x set to that value. So as functions as something of a foreach loop ๐.
Just as {foo} is a handy way of writing {foo: .foo}, so {$foo} is a handy way of writing {foo: $foo} ๐.
Multiple variables may be declared using a single as expression by providing a pattern that matches the structure of the input (this is known as "destructuring"):
. as {realnames: $names, posts: [$first, $second]} | ...
The variable declarations in array patterns (e.g., . as [$first, $second]) bind to the elements of the array in from the element at index zero on up, in order. When there is no value at the index for an array pattern element, null is bound to that variable.
Variables are scoped over the rest of the expression that defines them, so
.realnames as $names | (.posts[] | {title, author: $names[.author]})
will work, but
(.realnames as $names | .posts[]) | {title, author: $names[.author]}
won't ๐. scope is real, bestie.
Okay so for the programming-language-theory girlies specifically, the โจaccurateโจ way to say it is that jq variables are lexically-scoped bindings. And here's the part that matters, bestie: there is literally no way to change the value of a binding. The only move you have is setting up a brand new binding with the same name โ and that new one will not be visible anywhere the old one was. It's giving "new era, same name" ๐ . Anyway, look:
jq ยด.bar as $x | .foo | . + $xยด
{"foo":10, "bar":200}
=> 210
jq ยด. as $i|[(.*2|. as $i| $i), $i]ยด
5
=> [10,5]
jq ยด. as [$a, $b, {c: $c}] | $a + $b + $cยด
[2, 3, {"c": 4, "d": 5}]
=> 9
jq ยด.[] as [$a, $b] | {a: $a, b: $b}ยด
[[0], [0, 1], [2, 1, 0]]
=> {"a":0,"b":null}, {"a":0,"b":1}, {"a":2,"b":1}
๐ฆ Destructuring Alternative Operator: ?// ๐ฆ
The destructuring alternative operator is your little shortcut for destructuring an input that could show up in one of several forms. Very "same energy, different fits" ๐.
So picture this: we've got an API that hands back a list of resources plus the events tied to them, and we want the user_id and timestamp of the first event for every resource. Plot twist โ this API got clumsily converted from XML, so it will only wrap the events in an array when a resource has multiple events:
{"resources": [{"id": 1, "kind": "widget", "events": {"action": "create", "user_id": 1, "ts": 13}},
{"id": 2, "kind": "widget", "events": [{"action": "create", "user_id": 1, "ts": 14}, {"action": "destroy", "user_id": 1, "ts": 15}]}]}
And with the destructuring alternative operator we can handle that whole structural glow-up super simply:
.resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$user_id, $ts}]} | {$user_id, $kind, $id, $ts}
Or, if we're not sure whether the input is an array of values or an object:
.[] as [$id, $kind, $user_id, $ts] ?// {$id, $kind, $user_id, $ts} | ...
Not every alternative has to define the same variables, and that's the beauty of it โ but every named variable will be available to whatever expression comes next. Any variable that didn't get matched by the alternative that succeeded will be null:
.resources[] as {$id, $kind, events: {$user_id, $ts}} ?// {$id, $kind, events: [{$first_user_id, $first_ts}]} | {$user_id, $first_user_id, $kind, $id, $ts, $first_ts}
<b>And here's the extra layer:</b> if the subsequent expression returns an error, the alternative operator will try to try the next binding. Errors that happen during the final alternative get passed straight through, no save. ๐ญ
[[3]] | .[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} end
jq ยด.[] as {$a, $b, c: {$d, $e}} ?// {$a, $b, c: [{$d, $e}]} | {$a, $b, $d, $e}ยด
[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]
=> {"a":1,"b":2,"d":3,"e":4}, {"a":1,"b":2,"d":3,"e":4}
jq ยด.[] as {$a, $b, c: {$d}} ?// {$a, $b, c: [{$e}]} | {$a, $b, $d, $e}ยด
[{"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 1, "b": 2, "c": [{"d": 3, "e": 4}]}]
=> {"a":1,"b":2,"d":3,"e":null}, {"a":1,"b":2,"d":null,"e":4}
jq ยด.[] as [$a] ?// [$b] | if $a != null then error("err: \($a)") else {$a,$b} endยด
[[3]]
=> {"a":null,"b":3}
๐ Defining Functions ๐
You can give a filter a name using the def syntax:
def increment: . + 1;
And from that moment on, increment is usable as a filter exactly like a builtin function (fr fr โ that is literally how a bunch of the builtins are defined ๐ซถ). A function can also take arguments:
def map(f): [.[] | f];
Now the important bit, and I need you to really absorb this one: arguments get passed as filters (functions with no arguments), not as values. The same argument can be referenced multiple times with different inputs (here f gets run once per element of the input array). Arguments to a function work more like callbacks than like value arguments. Consider:
def foo(f): f|f;
5|foo(.*2)
The result will be 20, and here's why: f is .*2, and during the first invocation of f the . is 5, and the second time it's 10 (5 * 2), so the result lands at 20. Function arguments are filters, and filters expect an input when they're invoked. Periodt. โจ
If you do want that value-argument behaviour for defining simple functions, you can just use a variable:
def addvalue(f): f as $f | map(. + $f);
Or use the short-hand:
def addvalue($f): ...;
Either definition, same vibe: addvalue(.foo) will add the current input's .foo field to each element of the array. Do note though โ calling addvalue(.[]) will cause the map(. + $f) part to be evaluated once per value in the value of . at the call site. ๐
Multiple definitions using the same function name are totally allowed. Each re-definition replaces the previous one for the same number of function arguments, but only for references from functions (or the main program) that come subsequent to the re-definition. See also the section below on scoping, bestie.
jq ยดdef addvalue(f): . + [f]; map(addvalue(.[0]))ยด
[[1,2],[10,20]]
=> [[1,2,1], [10,20,10]]
jq ยดdef addvalue(f): f as $x | map(. + $x); addvalue(.[0])ยด
[[1,2],[10,20]]
=> [[1,2,1,2], [10,20,1,2]]
๐ธ Scoping ๐ธ
There are two types of symbols in jq: value bindings (a.k.a., "variables"), and functions. Both of them are scoped lexically, with expressions only being able to refer to symbols that have been defined "to the left" of them. The one single exception to this rule is that functions can refer to themselves, so that recursive functions are a thing. ๐
For example, in the following expression there's a binding which is visible "to the right" of it, ... | .*3 as $times_three | [. + $times_three] | ..., but not "to the left". Now consider this one: ... | (.*3 as $times_three | [. + $times_three]) | ... โ here the binding $times_three is not visible past the closing parenthesis. Sneaky little parentheses keeping secrets ๐.
โญ isempty(exp) โญ
Returns true if exp produces no outputs, false otherwise.
jq ยดisempty(empty)ยด
null
=> true
jq ยดisempty(.[])ยด
[]
=> true
jq ยดisempty(.[])ยด
[1,2,3]
=> false
๐ limit(n; expr) ๐
The limit function extracts up to n outputs from expr.
jq ยด[limit(3; .[])]ยด
[0,1,2,3,4,5,6,7,8,9]
=> [0,1,2]
๐ฆ skip(n; expr) ๐ฆ
The skip function skips the first n outputs from expr.
jq ยด[skip(3; .[])]ยด
[0,1,2,3,4,5,6,7,8,9]
=> [3,4,5,6,7,8,9]
๐ first(expr), last(expr), nth(n; expr) ๐
The first(expr) and last(expr) functions extract the first and last values from expr, respectively.
The nth(n; expr) function extracts the nth value output by expr. Note that nth(n; expr) doesn't support negative values of n. F in the chat. ๐ญ
jq ยด[first(range(.)), last(range(.)), nth(5; range(.))]ยด
10
=> [0,9,5]
jq ยด[first(empty), last(empty), nth(5; empty)]ยด
null
=> []
๐ first, last, nth(n) ๐
The first and last functions extract the first and last values from any array at ..
The nth(n) function extracts the nth value of any array at ..
jq ยด[range(.)]|[first, last, nth(5)]ยด
10
=> [0,9,5]
๐ reduce ๐
The reduce syntax lets you combine all of the results of an expression by accumulating them into a single answer โ main character energy, everything comes together in the end. ๐
The form is reduce EXP as $var (INIT; UPDATE). As an example, we'll pass [1,2,3] to this expression:
reduce .[] as $item (0; . + $item)
For each result that .[] produces, . + $item is run to accumulate a running total, starting from 0 as the input value. In this example, .[] produces the results 1, 2, and 3, so the effect is similar to running something like this:
0 | 1 as $item | . + $item |
2 as $item | . + $item |
3 as $item | . + $item
jq ยดreduce .[] as $item (0; . + $item)ยด
[1,2,3,4,5]
=> 15
jq ยดreduce .[] as [$i,$j] (0; . + $i * $j)ยด
[[1,2],[3,4],[5,6]]
=> 44
jq ยดreduce .[] as {$x,$y} (null; .x += $x | .y += [$y])ยด
[{"x":"a","y":1},{"x":"b","y":2},{"x":"c","y":3}]
=> {"x":"abc","y":[1,2,3]}
๐ง foreach ๐ง
The foreach syntax is similar to reduce, but it's designed to let you build limiters and reducers that produce intermediate results. Very "show your work" of it, honestly.
The form is foreach EXP as $var (INIT; UPDATE; EXTRACT). As an example, we'll pass [1,2,3] to this expression:
foreach .[] as $item (0; . + $item; [$item, . * 2])
Just like the reduce syntax, . + $item is run for each result that .[] produces, but [$item, . * 2] is run for each of the intermediate values. In this example, since the intermediate values are 1, 3, and 6, the foreach expression produces [1,2], [2,6], and [3,12]. So the effect is similar to running something like this:
0 | 1 as $item | . + $item | [$item, . * 2],
2 as $item | . + $item | [$item, . * 2],
3 as $item | . + $item | [$item, . * 2]
When EXTRACT is omitted, the identity filter is used. That is, it outputs the intermediate values as they are. ๐ซถ
jq ยดforeach .[] as $item (0; . + $item)ยด
[1,2,3,4,5]
=> 1, 3, 6, 10, 15
jq ยดforeach .[] as $item (0; . + $item; [$item, . * 2])ยด
[1,2,3,4,5]
=> [1,2], [2,6], [3,12], [4,20], [5,30]
jq ยดforeach .[] as $item (0; . + 1; {index: ., $item})ยด
["foo", "bar", "baz"]
=> {"index":1,"item":"foo"}, {"index":2,"item":"bar"}, {"index":3,"item":"baz"}
๐ Recursion ๐
Like we said up above, recurse uses recursion, and literally any jq function can be recursive. The while builtin is also implemented in terms of recursion. It's giving infinite loop but make it fashion.
Tail calls are optimized whenever the expression to the left of the recursive call outputs its last value. In practice, what that means is the expression to the left of the recursive call should not produce more than one output for each input.
For example:
def recurse(f): def r: ., (f | select(. != null) | r); r;
def while(cond; update):
def _while:
if cond then ., (update | _while) else empty end;
_while;
def repeat(exp):
def _repeat:
exp, _repeat;
_repeat;
โจ Generators and iterators โจ
Some jq operators and functions are actually generators, in that they can produce zero, one, or more values for each input โ just like you'd expect in other programming languages that have generators. For example, .[] generates all the values in its input (which must be an array or an object), range(0; 10) generates the integers between 0 and 10, and so on. ๐
Even the comma operator is a generator, generating first the values generated by the expression to the left of the comma, then the values generated by the expression on the right of the comma.
The empty builtin is the generator that produces zero outputs. The empty builtin backtracks to the preceding generator expression. Iconic, honestly. ๐
All jq functions can be generators just by using builtin generators. And like โ you can also build brand new generators out of nothing but recursion and the comma operator. Wild, I know. If the recursive calls are "in tail position" then the generator stays efficient (no stack explosion, no crying). In the example below, the recursive call by _range to itself is in tail position. Bestie, this one example flexes three advanced topics at once: tail recursion, generator construction, and sub-functions. Iconic behaviour honestly.
jq 'def range(init; upto; by): def _range: if (by > 0 and . < upto) or (by < 0 and . > upto) then ., ((.+by)|_range) else empty end; if init == upto then empty elif by == 0 then init else init|_range end; range(0; 10; 3)'
null
=> 0, 3, 6, 9
jq 'def while(cond; update): def _while: if cond then ., (update | _while) else empty end; _while; [while(.<100; .*2)]'
1
=> [1,2,4,8,16,32,64]
๐งฎ MATH ๐งฎ
Okay so, numbers. Right now jq only supports IEEE754 double-precision (64-bit) floating point numbers. That's it. That's the whole numeric buffet. ๐
Besides the simple arithmetic operators like +, jq also has most of the standard math functions from the C math library. Here's the whole translation sitch:
- C math functions that take one input argument (like
sin()) show up as zero-argument jq functions. - C math functions that take two input arguments (like
pow()) show up as two-argument jq functions that ignore.โ yes, they just ignore the input entirely, no thoughts, head empty. ๐ - C math functions that take three input arguments show up as three-argument jq functions that also ignore
..
Whether you actually get these standard math functions depends on whether the corresponding math functions exist in your operating system and C math library. Unavailable math functions will still be defined, but they'll raise an error when you call them. So like, they're there, they're just not gonna work. ๐
One-input C math functions: acos acosh asin asinh atan atanh cbrt ceil cos cosh erf erfc exp exp10 exp2 expm1 fabs floor gamma j0 j1 lgamma log log10 log1p log2 logb nearbyint rint round significand sin sinh sqrt tan tanh tgamma trunc y0 y1.
Two-input C math functions: atan2 copysign drem fdim fmax fmin fmod frexp hypot jn ldexp modf nextafter nexttoward pow remainder scalb scalbln yn.
Three-input C math functions: fma.
Hit up your system's manual for the tea on each one of these. ๐
๐ฅ๐ค I/O ๐ฅ๐ค
Right now jq has minimal support for I/O, mostly just in the form of control over when inputs get read. Two builtin functions handle this โ input and inputs โ and they read from the same sources as jq itself does (like stdin, or files named on the command-line). These two builtins, and jq's own reading actions, can be interleaved with each other like a lil dance. ๐ฉฐ They're commonly used together with the null input option -n, so that one input doesn't get read implicitly without you asking.
Two builtins give you minimal output capabilities: debug and stderr. (Quick reminder bestie: a jq program's output values are always output as JSON texts on stdout. Always.) The debug builtin can have application-specific behaviour โ like for executables that use the libjq C API but aren't the jq executable itself. The stderr builtin outputs its input in raw mode to stderr with no additional decoration, not even a newline. Not a single one. โจ
Most jq builtins are referentially transparent, and give you constant and repeatable value streams when you apply them to constant inputs. The I/O builtins? Yeah no, not that. ๐
input
Outputs one new input.
Heads up: when you useinputit's generally necessary to invoke jq with the-ncommand-line option, otherwise the first entity will be lost. ๐ญ
echo 1 2 3 4 | jq '[., input]' # [1,2] [3,4]
inputs
Outputs all remaining inputs, one by one.
This is mostly useful for reductions over a program's inputs. And same warning as above: when you use inputs it's generally necessary to invoke jq with the -n command-line option, otherwise the first entity will be lost.
echo 1 2 3 | jq -n 'reduce inputs as $i (0; . + $i)' # 6
debug, debug(msgs)
These two filters are like . but they have a side-effect: they produce one or more messages on stderr.
The message produced by the debug filter has this form:
["DEBUG:",<input-value>]
where <input-value> is a compact rendition of the input value. And listen โ this format may change in the future. Don't get attached. ๐ฆ
The debug(msgs) filter is defined as (msgs | debug | empty), . โ which means you get great flexibility in the content of the message, and you can even build multi-line debugging statements. Obsessed.
For example, this expression:
1 as $x | 2 | debug("Entering function foo with $x == \($x)", .) | (.+1)
would produce the value 3, but with the following two lines being written to stderr:
["DEBUG:","Entering function foo with $x == 1"]
["DEBUG:",2]
stderr
Prints its input in raw and compact mode to stderr with no additional decoration, not even a newline.
input_filename
Returns the name of the file whose input is currently being filtered.
Note: this will not work well unless jq is running in a UTF-8 locale. Just so you know. ๐ธ
input_line_number
Returns the line number of the input currently being filtered.
๐ STREAMING ๐
With the --stream option, jq can parse input texts in a streaming fashion, which lets jq programs start processing large JSON texts immediately instead of waiting around for the parse to finish. If you've got a single JSON text that's 1GB in size, streaming it will let you process it much more quickly. Main character energy from your JSON. ๐
But plot twist โ streaming isn't easy to deal with, because the jq program will have [<path>, <leaf-value>] (and a few other forms) as inputs. ๐ฌ
So, several builtins are provided to make handling streams easier.
The examples below use the streamed form of ["a",["b"]], which is:
[[0],"a"],[[1,0],"b"],[[1,0]],[[1]]
Streaming forms include [<path>, <leaf-value>] (which indicates any scalar value, empty array, or empty object), and [<path>] (which indicates the end of an array or object). Future versions of jq run with --stream and --seq may output additional forms such as ["error message"] when an input text fails to parse. Foreshadowing. ๐
truncate_stream(stream_expression)
Consumes a number as input and truncates the corresponding number of path elements from the left of the outputs of the given streaming expression.
jq 'truncate_stream([[0],"a"],[[1,0],"b"],[[1,0]],[[1]])'
1
=> [[0],"b"], [[0]]
fromstream(stream_expression)
Outputs values corresponding to the stream expression's outputs.
jq 'fromstream(1|truncate_stream([[0],"a"],[[1,0],"b"],[[1,0]],[[1]]))'
null
=> ["b"]
tostream
The tostream builtin outputs the streamed form of its input.
jq '. as $dot|fromstream($dot|tostream)|.==$dot'
[0,[1,{"a":1},{"b":2}]]
=> true
๐ ASSIGNMENT ๐
okay bestie, listen up, because assignment in jq is not like assignment in basically any other language you've ever met. sit down. hydrate. ๐
jq does not do that whole "references vs. copies" thing. two objects or arrays are either equal or not equal, and that's it โ there's no extra concept of "this is the same object" or "this is a different object". no identity crisis. no twin telepathy.
so picture this: an object with two fields that are both arrays, .foo and .bar. you append something to .foo. does .bar get bigger? no ๐ .bar does not budge, even if you literally did .bar = .foo two seconds earlier. and if you come from Python, Java, Ruby, JavaScript, etc., here's the mental model that saves you: pretend jq does a full deep copy of every object right before it does the assignment. (for performance it doesn't actually do that, but that's the general idea โ think of it as the vibe, not the implementation).
the consequence of all this is that you cannot build circular values in jq โ like, you can't make an array whose first element is itself. and that's quite intentional, because it guarantees that anything a jq program can produce can be represented in JSON. every output is a real, finite, JSON-able thing. slay. โจ
now: all the assignment operators in jq have path expressions on the left-hand side (the LHS). the right-hand side (RHS) is what hands over the values to set at the paths the LHS named.
also, values in jq are always immutable. internally, assignment works by using a reduction to compute new, replacement values for . that have had all the desired assignments applied to ., and then it outputs the modified value. here's the example that makes it click:
{a:{b:{c:1}}} | (.a.b|=3), .
this outputs {"a":{"b":3}} and {"a":{"b":{"c":1}}} โ because that last sub-expression, the plain ., sees the original value, not the modified one. the modification happened, sure, but . doesn't know her. ๐
most of you are gonna want the modification assignment operators, like |= or +=, way more than plain =.
heads up bestie: the LHS of assignment operators refers to a value in.. so$var.foo = 1won't work as expected โ$var.foois not a valid or useful path expression in.. write$var | .foo = 1instead. iykyk. ๐
and one more gotcha because jq is like that: .a,.b=0 does not set both .a and .b. but (.a,.b)=0 sets both. parentheses are doing the lord's work here. ๐
โจ Update-assignment: |= โจ
this is the "update" operator, |=. it takes a filter on the right-hand side and works out the new value for the property of . being assigned to by running the old value through that expression.
so for instance:
(.foo, .bar) |= .+1
will build an object with the foo field set to the input's foo plus 1, and the bar field set to the input's bar plus 1. both. at once. icon behavior. ๐
the left-hand side can be any general path expression โ go check path() for the details.
note that the left-hand side of|=refers to a value in.. so$var.foo |= . + 1won't work as expected ($var.foois not a valid or useful path expression in.). use$var | .foo |= . + 1instead.
if the right-hand side outputs no values (i.e., it's empty), then the left-hand side path will be deleted, exactly as with del(path).
if the right-hand side outputs multiple values, only the first one gets used.
COMPATIBILITY NOTE: in jq 1.5 and earlier releases, it used to be that only the last one was used. so if you're porting ancient code, that's your villain origin story.
jq '(..|select(type=="boolean")) |= if . then 1 else 0 end'
[true,false,[5,true,[true,[false]],false]]
=> [1,0,[5,1,[1,[0]],0]]
๐ Arithmetic update-assignment: +=, -=, *=, /=, %=, //= ๐
jq has a little family of operators shaped like a op= b, and every single one of them is equivalent to a |= . op b.
so += 1 can be used to increment values, and it's exactly the same as |= . + 1. no cap.
jq '.foo += 1'
{"foo": 42}
=> {"foo": 43}
๐ธ Plain assignment: = ๐ธ
this is the plain assignment operator. and unlike all her siblings, the input to the right-hand side (RHS) is the same as the input to the left-hand side (LHS) โ not the value sitting at the LHS path. plus, all the values output by the RHS get used (as shown below). she's generous like that.
if the RHS of = produces multiple values, then for each such value, jq will set the paths on the left-hand side to that value and then output the modified .. for example:
(.a,.b) = range(2)
outputs {"a":0,"b":0}, then {"a":1,"b":1}. the "update" assignment forms (see above) do not do this. main character difference, honestly.
this example should show you the difference between = and |=:
provide input {"a": {"b": 10}, "b": 20} to the programs
.a = .b
and
.a |= .b
the former will set the a field of the input to the b field of the input, and produce the output {"a": 20, "b": 20}. the latter will set the a field of the input to the a field's b field, producing {"a": 10, "b": 20}. subtle! gorgeous! dangerous if you're not paying attention! ๐ฆ
jq '.a = .b'
{"a": {"b": 10}, "b": 20}
=> {"a":20,"b":20}
jq '.a |= .b'
{"a": {"b": 10}, "b": 20}
=> {"a":10,"b":20}
jq '(.a, .b) = range(3)'
null
=> {"a":0,"b":0}, {"a":1,"b":1}, {"a":2,"b":2}
jq '(.a, .b) |= range(3)'
null
=> {"a":0,"b":0}
๐ฆ Complex assignments ๐ฆ
okay this is where it gets fun. way more things are allowed on the left-hand side of a jq assignment than in most languages. we've already seen plain field accesses on the left, and obviously array accesses work just as well:
.posts[0].title = "JQ Manual"
but here's the plot twist: the expression on the left may produce multiple results, pointing at different spots in the input document:
.posts[].comments |= . + ["this is great"]
that example appends the string "this is great" to the "comments" array of each post in the input (where the input is an object with a field "posts" which is an array of posts). every post. all of them. obsessed.
when jq runs into an assignment like a = b, it records the "path" taken to select a part of the input document while it was executing a. that path is then used to figure out which part of the input to change while executing the assignment. and literally any filter may be used on the left-hand side of an equals โ whichever paths it selects from the input will be exactly where the assignment gets performed. periodt.
this is a very powerful operation. so suppose we wanted to add a comment to blog posts, using that same "blog" input from before. this time we only want to comment on the posts written by "stedolan". we can find those posts using the select function described earlier:
.posts[] | select(.author == "stedolan")
the paths provided by this operation point to each of the posts that "stedolan" wrote, and we can comment on each of them the same way we did before:
(.posts[] | select(.author == "stedolan") | .comments) |=
. + ["terrible."]
๐ COMMENTS ๐
you can write comments in your jq filters using #. yes bestie, jq has comments. she contains multitudes. ๐
a # character (not part of a string) starts a comment. all characters from # to the end of the line are ignored. bye! โจ
and here's the spicy bit: if the end of the line is preceded by an odd number of backslash characters, the following line is also considered part of the comment and is ignored. odd. not even. odd. count them. ๐ง
for example, the following code outputs [1,3,4,7]:
[
1,
# foo \
2,
# bar \\
3,
4, # baz \\\
5, \
6,
7
# comment \
comment \
comment
]
backslash continuing the comment onto the next line can be super useful when you're writing the "shebang" for a jq script:
#!/bin/sh --
# total - Output the sum of the given arguments (or stdin)
# usage: total [numbers...]
# \
exec jq --args -MRnf -- "$0" "$@"
$ARGS.positional |
reduce (
if . == []
then inputs
else .[]
end |
. as $dot |
try tonumber catch false |
if not or isnan then
@json "total: Invalid number \($dot).\n" | halt_error(1)
end
) as $n (0; . + $n)
the exec line is considered a comment by jq, so jq ignores it. but it is not ignored by sh, because in sh a backslash at the end of the line does not continue the comment. sneaky. brilliant. ๐
with this trick, when the script is invoked as total 1 2, then /bin/sh -- /path/to/total 1 2 will be run, and sh will then run
exec jq --args -MRnf -- /path/to/total 1 2
replacing itself with a jq interpreter invoked with the specified options (-M, -R, -n, --args), which evaluates the current file ($0), with the arguments ($@) that were passed to sh. one file, two languages, zero regrets. ๐ฅ
๐ MODULES ๐
okay bestie, jq has a whole library/module system and it's giving very "let me organize my life" energy. Modules are files whose names end in .jq. periodt. โจ
Modules imported by a program get searched for in a default search path (more on that below, keep reading ๐). The import and include directives let the importer alter that path. main character behavior fr.
Paths in the search path get all kinds of substitutions done to them:
- Paths starting with
~/โ the user's home directory gets substituted for~. ๐ - Paths starting with
$ORIGIN/โ the directory where the jq executable lives gets substituted for$ORIGIN. ๐ - Paths starting with
./, or paths that are just.โ the path of the including file gets substituted for.. For top-level programs handed to jq on the command-line, the current directory is used instead.
Import directives can optionally specify their own search path, and the default one gets appended to it. no cap.
The default search path is whatever you passed to the -L command-line option โ and if you didn't, it's:
["~/.jq", "$ORIGIN/../lib/jq", "$ORIGIN/../lib"]
Null and empty string path elements terminate search path processing. like, they end it. done. bye. ๐
So a dependency with relative path foo/bar would be searched for in foo/bar.jq and foo/bar/bar.jq inside the given search path. The whole point is to let modules sit in a directory alongside stuff like version control files, README files, and so on โ but also to allow for single-file modules. both vibes, slay. ๐ฆ
Consecutive components with the same name are not allowed, and that's on purpose, to avoid ambiguities (e.g., foo/foo). we don't do that here. ๐
For example, with -L$HOME/.jq a module foo can be found in $HOME/.jq/foo.jq and $HOME/.jq/foo/foo.jq. ๐
And if .jq exists in the user's home directory and is a file (not a directory), it gets automatically sourced into the main program. surprise feature, iconic.
import RelativePathString as NAME [<metadata>];
Imports a module found at the given path, relative to a directory in a search path. A .jq suffix gets added to the relative path string, automatically, like a little accessory. The module's symbols get prefixed with NAME::. ๐
The optional metadata must be a constant jq expression. It should be an object with keys like homepage and so on. Right now jq only uses the search key/value of the metadata. The metadata is also made available to users via the modulemeta builtin. ๐ซถ
The search key in the metadata, if it's present, should have a string or array value (array of strings) โ that's the search path to be prefixed to the top-level search path.
include RelativePathString [<metadata>];
Imports a module found at the given path relative to a directory in a search path, as if it were included in place. A .jq suffix gets added to the relative path string. The module's symbols get imported into the caller's namespace as if the module's content had been included directly. no NAME:: prefix, we're all one big family here ๐ฅฐ
The optional metadata must be a constant jq expression. It should be an object with keys like homepage and so on. At this time jq only uses the search key/value of the metadata. The metadata is also made available to users via the modulemeta builtin.
import RelativePathString as $NAME [<metadata>];
Ooh this one's different bestie, this one imports a JSON file ๐ found at the given path relative to a directory in a search path. A .json suffix gets added to the relative path string. The file's data will be available as $NAME::NAME. yes, $NAME::NAME. it said what it said. โจ
The optional metadata must be a constant jq expression. It should be an object with keys like homepage and so on. At this time jq only uses the search key/value of the metadata. The metadata is also made available to users via the modulemeta builtin.
The search key in the metadata, if present, should have a string or array value (array of strings) โ this is the search path to be prefixed to the top-level search path.
module <metadata>;
This directive is entirely optional. It's not required for proper operation. It serves only one purpose: providing metadata that can be read with the modulemeta builtin. lowkey just a note-to-self. ๐
The metadata must be a constant jq expression. It should be an object with keys like homepage. At this time jq doesn't use this metadata, but it is made available to users via the modulemeta builtin.
modulemeta
Takes a module name as input and outputs the module's metadata as an object, with the module's imports (including metadata) as an array value for the deps key, and the module's defined functions as an array value for the defs key. ๐ธ
Programs can use this to query a module's metadata, which they could then use to, for example, search for, download, and install missing dependencies. it's giving package manager. obsessed. ๐
๐จ COLORS ๐จ
Wanna configure alternative colors? just set the JQ_COLORS environment variable to a colon-delimited list of partial terminal escape sequences like "1;31", in this exact order:
- color for
null - color for
false - color for
true - color for numbers
- color for strings
- color for arrays
- color for objects
- color for object keys
The default color scheme is the same as setting:
JQ_COLORS="0;90:0;39:0;39:0;39:0;32:1;39:1;39:1;34"
Now โ this is not a manual for VT100/ANSI escapes, okay? I'm not writing that for you. ๐ However, each of these color specifications should consist of two numbers separated by a semi-colon. The first number is one of these:
1(bright)2(dim)4(underscore)5(blink)7(reverse)8(hidden)
and the second is one of these:
30(black)31(red)32(green)33(yellow)34(blue)35(magenta)36(cyan)37(white)
make it cute. make it yours. glow up your terminal ๐
๐ BUGS ๐
Presumably. ๐ญ
Report them or discuss them at:
https://github.com/jqlang/jq/issues
๐ AUTHOR ๐
Stephen Dolan <mu@netsoc.tcd.ie>
and that's the whole page bestie, we made it to the end together ๐ฅน this one's from May 2025, it's the JQ(1) manual page, and you now officially know more jq than 99% of the group chat. go forth and filter. slay forever, fr fr ๐โจ๐
๐ฆ where this page comes from
- alpine 3.22: jq-doc 1.8.2-r0 ยท MIT
- alpine 3.23: jq-doc 1.8.2-r0 ยท MIT
- alpine 3.24: jq-doc 1.8.2-r0 ยท MIT
- arch rolling: jq 1.8.2-1 ยท MIT
- nixpkgs unstable: jq 1.8.2
- ubuntu stonking: jq 1.8.2-1ubuntu1 ยท MIT
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms