Linux jq set value

Содержание
  1. Bash jq command
  2. Reading JSON data
  3. Reading JSON data with –c option
  4. Reading a JSON file
  5. Students.json
  6. Reading JSON file with ‘|’
  7. Reading single key values
  8. Reading multiple keys
  9. Remove key from JSON data
  10. Mapping Values
  11. Searching values by index and length
  12. About the author
  13. Fahmida Yesmin
  14. Modify a key-value in a json using jq in-place
  15. 7 Answers 7
  16. jq (1) — Linux Man Pages
  17. jq: Command-line JSON processor
  18. SYNOPSIS
  19. FILTERS
  20. INVOKING JQ
  21. BASIC FILTERS
  22. Identity: .
  23. Object Identifier-Index: .foo, .foo.bar
  24. Optional Object Identifier-Index: .foo?
  25. Generic Object Index: .[ ]
  26. Array Index: .[2]
  27. Array/String Slice: .[10:15]
  28. Array/Object Value Iterator: .[]
  29. Comma: ,
  30. Parenthesis
  31. TYPES AND VALUES
  32. Array construction: []
  33. Object Construction: <>
  34. Recursive Descent: ..
  35. BUILTIN OPERATORS AND FUNCTIONS
  36. Addition: +
  37. Subtraction: —
  38. Multiplication, division, modulo: *, /, and %
  39. length
  40. utf8bytelength
  41. keys, keys_unsorted
  42. has(key)
  43. map(x), map_values(x)
  44. path(path_expression)
  45. del(path_expression)
  46. getpath(PATHS)
  47. setpath(PATHS; VALUE)
  48. delpaths(PATHS)
  49. to_entries, from_entries, with_entries
  50. select(boolean_expression)
  51. arrays, objects, iterables, booleans, numbers, normals, finites, strings, nulls, values, scalars
  52. empty
  53. error(message)
  54. halt_error, halt_error(exit_code)
  55. $__loc__
  56. paths, paths(node_filter), leaf_paths
  57. any, any(condition), any(generator; condition)
  58. all, all(condition), all(generator; condition)
  59. flatten, flatten(depth)
  60. range(upto), range(from;upto) range(from;upto;by)
  61. floor
  62. tonumber
  63. tostring
  64. infinite, nan, isinfinite, isnan, isfinite, isnormal
  65. sort, sort_by(path_expression)
  66. group_by(path_expression)
  67. min, max, min_by(path_exp), max_by(path_exp)
  68. unique, unique_by(path_exp)
  69. reverse
  70. contains(element)
  71. indices(s)
  72. index(s), rindex(s)
  73. inside
  74. startswith(str)
  75. endswith(str)
  76. combinations, combinations(n)
  77. ltrimstr(str)
  78. rtrimstr(str)
  79. explode
  80. implode
  81. split(str)
  82. join(str)
  83. ascii_downcase, ascii_upcase
  84. while(cond; update)
  85. until(cond; next)
  86. recurse(f), recurse, recurse(f; condition), recurse_down
  87. walk(f)
  88. $ENV, env
  89. transpose
  90. bsearch(x)
  91. String interpolation — \(foo)
  92. Convert to/from JSON
  93. Format strings and escaping
  94. Dates
  95. SQL-Style Operators
  96. builtins
  97. CONDITIONALS AND COMPARISONS
  98. if-then-else
  99. >, >=, > , >= , , 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).
  100. and/or/not
  101. Alternative operator: //
  102. try-catch
  103. Breaking out of control structures
  104. Error Suppression / Optional Operator: ?
  105. REGULAR EXPRESSIONS (PCRE)
  106. test(val), test(regex; flags)
  107. match(val), match(regex; flags)
  108. capture(val), capture(regex; flags)
  109. scan(regex), scan(regex; flags)
  110. split(regex; flags)
  111. splits(regex), splits(regex; flags)
  112. sub(regex; tostring) sub(regex; string; flags)
  113. gsub(regex; string), gsub(regex; string; flags)
  114. ADVANCED FEATURES
  115. Variable / Symbolic Binding Operator: . as $identifier | .
  116. Destructuring Alternative Operator: ?//
  117. Defining Functions
  118. Scoping
  119. Reduce
  120. isempty(exp)
  121. limit(n; exp)
  122. first(expr), last(expr), nth(n; expr)
  123. first, last, nth(n)
  124. foreach
  125. Recursion
  126. Generators and iterators
  127. input
  128. inputs
  129. debug
  130. stderr
  131. input_filename
  132. input_line_number
  133. STREAMING
  134. truncate_stream(stream_expression)
  135. fromstream(stream_expression)
  136. tostream
  137. ASSIGNMENT
  138. Update-assignment: |=
  139. Arithmetic update-assignment: +=, -=, *=, /=, %=, //=
  140. Plain assignment: =
  141. Complex assignments
  142. MODULES
  143. import RelativePathString as NAME [ ];
  144. include RelativePathString [ ];
  145. import RelativePathString as $NAME [ ];
  146. module ;
  147. modulemeta
  148. COLORS

Bash jq command

Run the following command to install jq on Ubuntu.

Reading JSON data

Suppose, you have declared a JSON variable named JsonData in the terminal and run jq command with that variable to print the content of that variable.

Reading JSON data with –c option

-c option uses with jq command to print each JSON object in each line. After running the following command, each object of JsonData variable will be printed.

Reading a JSON file

jq command can be used for reading JSON file also. Create a JSON file named Students.json with the following content to test the next commands of this tutorial.

Students.json

Run the following command to read Students.json file.

Reading JSON file with ‘|’

You can use ‘|’ symbol in the following way to read any JSON file.

Reading single key values

You can easily read any particular object from a JSON file by using jq command. In Students.json, there are four objects. These are roll, name, batch, and department. If you want to read the value of department key only from each record then run jq command in the following way.

Reading multiple keys

If you want to read two or more object values from JSON data then mention the object names by separating comma (,) in the jq command. The following command will retrieve the values of name and department keys.

Remove key from JSON data

jq command is used not only for reading JSON data but also to display data by removing the particular key. The following command will print all key values of Students.json file by excluding batch key. map and del function are used in jq command to do the task.

Mapping Values

Without deleting the key from JSON data, you can use map function with jq command for various purposes. Numeric values of JSON data can be increased or decreased by map function. Create a JSON file named Number.json with the following content to test the next commands.

Run the following command to add 10 with each object value of Numbers,json.

Run the following command to subtract 10 from each object value of Numbers,json.

Searching values by index and length

You can read objects from JSON file by specifying the particular index and length. Create a JSON file named colors.json with the following data.

Run the following command to read two values starting from the third index of colors.json file.

You can specify the length or starting index to read data from JSON file. In the following example, the number of data value is given only. In this case, the command will read four data from the first index of colors.json.

You can specify the starting point only without any length value in jq command and the value can be positive or negative. If the starting point is positive then the index will count from the left side of the list and starting from zero. If the starting point is negative then the index will count from the right side of the list and starting from one. In the following example, the starting point is -3. So, the last three values from the data will display.

When you will work with JSON data and want to parse or manipulate data according to your requirements then jq command will help you to make your task easier.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Modify a key-value in a json using jq in-place

I have a json in which I want to modify a particular value but the terminal always displays the json with the modified value but it does not actually change the value in the particular file. Sample json:

I want to change the value of address in the file itself but so far I’ve been unable to do so. I tried using:

but it didn’t work. Any suggestions?

7 Answers 7

Use a temporary file; it’s what any program that claims to do in-place editing is doing.

If the address isn’t hard-coded, pass the correct address via a jq argument:

AFAIK jq does not support in-place editing, so you must redirect to a temporary file first and then replace your original file with it, or use sponge utility from the moreutils package, like that:

There are other techniques to «redirect to the same file», like saving your output in a variable e.t.c. «Unix & Linux StackExchange» is a good place to start, if you want to learn more about this.

Temp files add more complexity when not needed (unless you are truly dealing with JSON files so large you cannot fit them in memory (GB to 100’s of GB or TB, depending on how much RAM/parallelism you have)

The Pure bash way.

  • No temp file to juggle
  • Pure bash
  • Don’t need an admin to install sponge , which is not installed by default
  • Simpler

Note: this can not be combined as «one command», since redirection starts before the left hand side (LHS) of an expression is run, and starting redirection before running jq erroneously empties the file, hence two separate commands.

Источник

jq (1) — Linux Man Pages

jq: Command-line JSON processor

Command to display jq manual in Linux: $ man 1 jq

jq — Command-line JSON processor

SYNOPSIS

jq can transform JSON in various ways, by selecting, iterating, reducing and otherwise mangling JSON documents. 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.

jq can accept text input as well, but by default, jq 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. One or more files may be specified, in which case jq will read input from those instead.

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.

FILTERS

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.

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. Generally, things that would be done with loops and iteration in other languages are just done by gluing filters together in jq.

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. 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.

But that’s getting ahead of ourselves. 🙂 Let’s start with something simpler:

INVOKING JQ

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) the jq program, as 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 as jq foo , which will generally fail because foo is 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 -f program-file option), but then double-quotes in the jq program need backslash escaping.

You can affect how jq reads and writes its input and output using some command-line options: ○ —version : Output the jq version and exit with zero. ○ —seq : Use the application/json-seq MIME 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 —seq option. ○ —stream : Parse the input in streaming fashion, outputing 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 [[1,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. ○ —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. ○ —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. ○ —null-input / -n : Don’t read any input at all! Instead, the filter is run once using null as the input. This is useful when using jq as a simple calculator or to construct JSON data from scratch. ○ —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. ○ —tab : Use a tab for each indentation level instead of two spaces. ○ —indent n : Use the given number of spaces (no more than 8) for indentation. ○ —color-output / -C and —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 . Colors can be configured with the JQ_COLORS environment variable (see below). ○ —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. ○ —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). ○ —sort-keys / -S : Output the fields of each object with the keys in sorted order. ○ —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. ○ —join-output / -j : Like -r but jq won’t print a newline after each output. ○ -f filename / —from-file filename : Read filter from the file rather than from a command line, like awk’s -f option. You can also use ‘#’ to make comments. ○ -Ldirectory / -L 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. ○ -e / —exit-status : Sets the exit status of jq to 0 if the last output values was neither false nor null , 1 if the last output value was either false or null , or 4 if no valid result was ever produced. Normally jq exits with 2 if there was any usage problem or system error, 3 if there was a jq program compile error, or 0 if the jq program ran. Another way to set the exit status is with the halt_error builtin function. ○ —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 $foo is available in the program and has the value «bar» . Note that value will be treated as a string, so —arg foo 123 will bind $foo to «123» . Named arguments are also available to the jq program as $ARGS.named . ○ —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 $foo is available in the program and has the value 123 . ○ —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 $foo is available in the program and has an array whose elements correspond to the texts in the file named bar . ○ —rawfile variable-name filename : This option reads in the named file and binds its contents to the given global variable. If you run jq with —rawfile foo bar , then $foo is available in the program and has a string whose contents are to the texs in the file named bar . ○ —argfile variable-name filename : Do not use. Use —slurpfile instead. (This option is like —slurpfile , but when the file has just one text, then that is used, else an array of texts is used as in —slurpfile .) ○ —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[] . ○ —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.

Читайте также:  Pyqt как установить windows

BASIC FILTERS


Identity: .

Since jq by default pretty-prints all output, this trivial program can be a useful way of formatting JSON output from, say, curl .

Object Identifier-Index: .foo, .foo.bar

A filter of the form .foo.bar is equivalent to .foo|.bar .

This syntax only works for simple, identifier-like keys, that is, keys that are all made of alphanumeric characters and underscore, and which do not start with a digit.

If the key contains special characters, you need to surround it with double quotes like this: .»foo$» , or else .[«foo$»] .

For example .[«foo::bar»] and .[«foo.bar»] work while .foo::bar does not, and .foo.bar means .[«foo»].[«bar»] .

Optional Object Identifier-Index: .foo?


Generic Object Index: .[ ]


Array Index: .[2]

Negative indices are allowed, with -1 referring to the last element, -2 referring to the next to last element, and so on.

Array/String Slice: .[10:15]


Array/Object Value Iterator: .[]

You can also use this on an object, and it will return all the values of the object.

Comma: ,

If the one on the left produces multiple results, the one on the right will be run for each of those results. So, the expression .[] | .foo retrieves the «foo» field of each element of the input array.

Note that .a.b.c is the same as .a | .b | .c .

Note too that . is the input value at the particular stage in a «pipeline», specifically: where the . expression appears. Thus .a | . | .b is the same as .a.b , as the . in the middle refers to whatever value .a produced.

Parenthesis


TYPES AND VALUES

Booleans, null, strings and numbers are written the same way as in javascript. Just like everything else in jq, these simple values take an input and produce an output — 42 is a valid jq expression that takes an input, ignores it, and returns 42 instead.

Array construction: []

Once you understand the «,» operator, you can look at jq’s array syntax in a different light: the expression [1,2,3] is not using a built-in syntax for comma-separated arrays, but is instead applying the [] operator (collect results) to the expression 1,2,3 (which produces three different results).

If you have a filter X that produces four results, then the expression [X] will produce a single result, an array of four elements.

Object Construction: <>

If the keys are «identifier-like», then the quotes can be left off, as in . Keys generated by expressions need to be parenthesized, e.g., <("a"+"b"):59>.

The value can be any expression (although you may need to wrap it in parentheses if it’s a complicated one), which gets applied to the <> expression’s input (remember, all filters have an input and an output).

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

Because that is so common, there’s a shortcut syntax for it: .

If one of the expressions produces multiple results, multiple dictionaries will be produced. If the input’s

then the expression

will produce two outputs:

Putting parentheses around the key means it will be evaluated as an expression. With the same input as above,

Recursive Descent: ..

This is particularly useful in conjunction with path(EXP) (also see below) and the ? operator.

BUILTIN OPERATORS AND FUNCTIONS


Addition: +

null can be added to any value, and returns the other value unchanged.

Subtraction: —


Multiplication, division, modulo: *, /, and %

Multiplying a string by a number produces the concatenation of that string that many times. «x» * 0 produces null .

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.

length


utf8bytelength


keys, keys_unsorted

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.

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.

has(key)

has($key) has the same effect as checking whether $key is a member of the array returned by keys , although has will be faster.

map(x), map_values(x)

Similarly, map_values(x) will run that filter for each element, but it will return an object when an object is passed.

map(x) is equivalent to [.[] | x] . In fact, this is how it’s defined. Similarly, map_values(x) is defined as .[] |= x .

path(path_expression)

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 . , if . is null or an array or an object.

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.

del(path_expression)


getpath(PATHS)


setpath(PATHS; VALUE)


delpaths(PATHS)


to_entries, from_entries, with_entries

from_entries does the opposite conversion, and with_entries(foo) is a shorthand for to_entries | map(foo) | from_entries , 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.

select(boolean_expression)

It’s useful for filtering lists: [1,2,3] | map(select(. >= 2)) will give you [2,3] .

arrays, objects, iterables, booleans, numbers, normals, finites, strings, nulls, values, scalars


empty

It’s useful on occasion. You’ll know if you need it 🙂

error(message)


halt_error, halt_error(exit_code)

The given exit_code (defaulting to 5 ) will be jq’s exit status.

For example, «Error: somthing went wrong\n»|halt_error(1) .

$__loc__


paths, paths(node_filter), leaf_paths

paths(f) outputs the paths to any values for which f is true. That is, paths(numbers) outputs the paths to all numeric values.

leaf_paths is an alias of paths(scalars) ; leaf_paths is deprecated and will be removed in the next major release.

If the input is an empty array, add returns null .

any, any(condition), any(generator; condition)

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.

all, all(condition), all(generator; condition)

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 .

flatten, flatten(depth)

flatten(2) is like flatten , but going only up to two levels deep.

range(upto), range(from;upto) range(from;upto;by)

The one argument form generates numbers from 0 to the given number, with an increment of 1.

The two argument form generates numbers from from to upto with an increment of 1.

The three argument form generates numbers from to upto with an increment of by .

floor


tonumber


tostring


infinite, nan, isinfinite, isnan, isfinite, isnormal

Note that division by zero raises an error.

Currently most arithmetic operations operating on infinities, NaNs, and sub-normals do not raise errors.

sort, sort_by(path_expression)

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 may be used to sort by a particular field of an object, or by applying any jq filter.

sort_by(foo) compares two elements by comparing the result of foo on each element.

group_by(path_expression)

Any jq expression, not just a field access, may be used in place of .foo . The sorting order is the same as described in the sort function above.

min, max, min_by(path_exp), max_by(path_exp)

The min_by(path_exp) and max_by(path_exp) functions allow you to specify a particular field or property to examine, e.g. min_by(.foo) finds the object with the smallest foo field.

unique, unique_by(path_exp)

The unique_by(path_exp) function will keep 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 produced by group .

reverse


contains(element)


indices(s)


index(s), rindex(s)


inside


startswith(str)


endswith(str)


combinations, combinations(n)


ltrimstr(str)


rtrimstr(str)


explode


implode


split(str)


join(str)

Numbers and booleans in the input are converted to strings. Null values are treated as empty strings. Arrays and objects in the input are not supported.

ascii_downcase, ascii_upcase


while(cond; update)

Note that while(cond; update) is internally defined as a recursive jq function. Recursive calls within while will not consume additional memory if update produces at most one output for each input. See advanced topics below.

until(cond; next)

Note that until(cond; next) is internally defined as a recursive jq function. Recursive calls within until() will not consume additional memory if next produces at most one output for each input. See advanced topics below.

recurse(f), recurse, recurse(f; condition), recurse_down

Now suppose you want to extract all of the filenames present. You need to retrieve .name , .children[].name , .children[].children[].name , and so on. You can do this with:

Читайте также:  Write iso with dd linux

When called without an argument, recurse is equivalent to recurse(.[]?) .

recurse(f) is identical to recurse(f; . != null) 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. For example, to generate all the integers, at least in principle, one could write recurse(.+1; true) .

For legacy reasons, recurse_down exists as an alias to calling recurse without arguments. This alias is considered deprecated and will be removed in the next major release.

The recursive calls in recurse will not consume additional memory whenever f produces at most a single output for each input.

walk(f)


$ENV, env

env outputs an object representing jq’s current environment.

At the moment there is no builtin for setting environment variables.

transpose


bsearch(x)


String interpolation — \(foo)


Convert to/from JSON


Format strings and escaping

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,

will produce the following output for the input <"search":"what is jq?">:

Note that the slashes, question mark, etc. in the URL are not escaped, as they were part of the string literal.

Dates

The fromdateiso8601 builtin parses datetimes in the ISO 8601 format to a number of seconds since the Unix epoch (1970-01-01T00:00:00Z). The todateiso8601 builtin does the inverse.

The fromdate builtin parses datetime strings. Currently fromdate only supports ISO 8601 datetime strings, but in the future it will attempt to parse datetime strings in more formats.

The todate builtin is an alias for todateiso8601 .

The now builtin outputs the current time, in seconds since the Unix epoch.

Low-level jq interfaces to the C-library time functions are also provided: strptime , strftime , strflocaltime , mktime , gmtime , and localtime . Refer to your host operating system’s documentation for the format strings used by strptime and strftime . Note: these are not necessarily stable interfaces in jq, particularly as to their localization functionality.

The gmtime builtin consumes a number of seconds since the Unix epoch and outputs a «broken down time» representation of Greenwhich Meridian time as an array of numbers representing (in this order): the year, the month (zero-based), 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. The day of the week number may be wrong on some systems for dates before March 1st 1900, or after December 31 2099.

The localtime builtin works like the gmtime builtin, but using the local timezone setting.

The mktime builtin consumes «broken down time» representations of time output by gmtime and strptime .

The strptime(fmt) builtin parses input strings matching the fmt argument. The output is in the «broken down time» representation consumed by gmtime and output by mktime .

The strftime(fmt) builtin formats a time (GMT) with the given format. The strflocaltime does the same, but using the local timezone setting.

The format strings for strptime and strftime are described in typical C library documentation. The format string for ISO 8601 datetime is «%Y-%m-%dT%H:%M:%SZ» .

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.

SQL-Style Operators

JOIN($idx; stream; idx_expr; join_expr):

JOIN($idx; stream; idx_expr):

builtins


CONDITIONALS AND COMPARISONS

!= is «not equal», and ‘a != b’ returns the opposite value of ‘a == b’

if-then-else

Checking for false or null is a simpler notion of «truthiness» than is found in Javascript or Python, but it means that you’ll sometimes have to be more explicit about the condition you want: you can’t test whether, e.g. a string is empty using if .name then A else B end , you’ll need something more like if (.name | length) > 0 then A else B end instead.

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.

More cases can be added to an if using elif A then B syntax.

«zero» elif . == 1 then «one» else «many» end’ 2 => «many»

>, >=, > , >= , , 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).

The ordering is the same as that described for sort , above.

and/or/not

If an operand of one of these operators produces multiple results, the operator itself will produce a result for each input.

not is in fact a builtin function rather than an operator, so it is called as a filter to which things can be piped rather than with special syntax, as in .foo and .bar | not .

These three only produce the values «true» and «false», and so are only useful for genuine Boolean operations, rather than the common Perl/Python/Ruby idiom of «value_that_may_be_null or default». If you want to use this form of «or», picking between two values rather than evaluating a condition, see the «//» operator below.

Alternative operator: //

This is 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 (jq’s or operator is reserved for strictly Boolean operations).

try-catch

The try EXP form uses empty as the exception handler.

Breaking out of control structures

jq has a syntax for named lexical labels to «break» or «go (back) to»:

The break $label_name expression will cause the program to to act as though the nearest (to the left) label $label_name produced empty .

The relationship between the break and corresponding label is lexical: the label has to be «visible» from the break.

To break out of a reduce , for example:

The following jq program produces a syntax error:

because no label $out is visible.

Error Suppression / Optional Operator: ?


REGULAR EXPRESSIONS (PCRE)

The jq regex filters are defined so that they can be used using one of these patterns:

where: * STRING, REGEX and FLAGS are jq strings and subject to jq string interpolation; * REGEX, after string interpolation, should be a valid PCRE regex; * FILTER is one of test , match , or capture , as described below.

FLAGS is a string consisting of one of more of the supported flags: ○ g — Global search (find all matches, not just the first) ○ i — Case insensitive search ○ m — Multi line mode (‘.’ will match newlines) ○ n — Ignore empty matches ○ p — Both s and m modes are enabled ○ s — Single line mode (‘^’ -> ‘\A’, ‘$’ -> ‘\Z’) ○ l — Find longest possible matches ○ x — Extended regex format (ignore whitespace and comments)

To match whitespace in an x pattern use an escape such as \s, e.g. ○ test( «a\sb», «x» ).

Note that certain flags may also be specified within REGEX, e.g. ○ jq -n ‘(«test», «TEst», «teST», «TEST») | test( «(?i)te(?-i)st» )’

evaluates to: true, true, false, false.

test(val), test(regex; flags)


match(val), match(regex; flags)

Capturing group objects have the following fields: ○ offset — offset in UTF-8 codepoints from the beginning of the input ○ length — length in UTF-8 codepoints of this capturing group ○ string — the string that was captured ○ name — the name of the capturing group (or null if it was unnamed)

Capturing groups that did not match anything return an offset of -1

capture(val), capture(regex; flags)


scan(regex), scan(regex; flags)


split(regex; flags)


splits(regex), splits(regex; flags)


sub(regex; tostring) sub(regex; string; flags)


gsub(regex; string), gsub(regex; string; flags)


ADVANCED FEATURES

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 is also possible to define functions in jq, although this is is a feature whose biggest use is defining jq’s standard library (many jq functions such as map and find 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 | .

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, perhaps 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.

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:

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:

We want to produce the posts with the author field containing a real name, as in:

We use a variable, $names, to store the realnames object, so that we can refer to it later when looking up author usernames:

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. Thus as functions as something of a foreach loop.

Just as is a handy way of writing , so <$foo>is a handy way of writing .

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»):

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

For programming language theorists, it’s more accurate to say that jq variables are lexically-scoped bindings. In particular there’s no way to change the value of a binding; one can only setup a new binding with the same name, but which will not be visible where the old one was.

Destructuring Alternative Operator: ?//

Suppose we have an API that returns a list of resources and events associated with them, and we want to get the user_id and timestamp of the first event for each resource. The API (having been clumsily converted from XML) will only wrap the events in an array if the resource has multiple events:

We can use the destructuring alternative operator to handle this structural change simply:

Or, if we aren’t sure if the input is an array of values or an object:

Each alternative need not define all of the same variables, but all named variables will be available to the subsequent expression. Variables not matched in the alternative that succeeded will be null :

Additionally, if the subsequent expression returns an error, the alternative operator will attempt to try the next binding. Errors that occur during the final alternative are passed through.

Defining Functions

From then on, increment is usable as a filter just like a builtin function (in fact, this is how many of the builtins are defined). A function may take arguments:

Arguments are passed as filters (functions with no arguments), not as values. The same argument may be referenced multiple times with different inputs (here f is run for each element of the input array). Arguments to a function work more like callbacks than like value arguments. This is important to understand. Consider:

The result will be 20 because f is .*2 , and during the first invocation of f . will be 5, and the second time it will be 10 (5 * 2), so the result will be 20. Function arguments are filters, and filters expect an input when invoked.

If you want the value-argument behaviour for defining simple functions, you can just use a variable:

Or use the short-hand:

With either definition, addvalue(.foo) will add the current input’s .foo field to each element of the array. Do note that calling addvalue(.[]) will cause the map(. + $f) part to be evaluated once per value in the value of . at the call site.

Читайте также:  Как открыть корневую папку mac os

Multiple definitions using the same function name are allowed. Each re-definition replaces the previous one for the same number of function arguments, but only for references from functions (or main program) subsequent to the re-definition. See also the section below on scoping.

Scoping

For example, in the following expression there is a binding which is visible «to the right» of it, . | .*3 as $times_three | [. + $times_three] | . , but not «to the left». Consider this expression now, . | (.*3 as $times_three | [.+ $times_three]) | . : here the binding $times_three is not visible past the closing parenthesis.

Reduce

For each result that .[] produces, . + $item is run to accumulate a running total, starting from 0. In this example, .[] produces the results 3, 2, and 1, so the effect is similar to running something like this:

isempty(exp)


limit(n; exp)


first(expr), last(expr), nth(n; expr)

The nth(n; expr) function extracts the nth value output by expr . This can be defined as def nth(n; expr): last(limit(n + 1; expr)); . Note that nth(n; expr) doesn’t support negative values of n .

first, last, nth(n)

The nth(n) function extracts the nth value of any array at . .

foreach

The form is foreach EXP as $var (INIT; UPDATE; EXTRACT) . Like reduce , INIT is evaluated once to produce a state value, then each output of EXP is bound to $var , UPDATE is evaluated for each output of EXP with the current state and with $var visible. Each value output by UPDATE replaces the previous state. Finally, EXTRACT is evaluated for each new state to extract an output of foreach .

This is mostly useful only for constructing reduce — and limit -like functions. But it is much more general, as it allows for partial reductions (see the example below).

Recursion

Tail calls are optimized whenever the expression to the left of the recursive call outputs its last value. In practice this means that the expression to the left of the recursive call should not produce more than one output for each input.

Generators and iterators

Even the comma operator is a generator, generating first the values generated by the expression to the left of the comma, then for each of those, the values generate 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.

All jq functions can be generators just by using builtin generators. It is also possible to define new generators using only recursion and the comma operator. If the recursive call(s) is(are) «in tail position» then the generator will be efficient. In the example below the recursive call by _range to itself is in tail position. The example shows off three advanced topics: tail recursion, generator construction, and sub-functions.

Besides simple arithmetic operators such as + , jq also has most standard math functions from the C math library. C math functions that take a single input argument (e.g., sin() ) are available as zero-argument jq functions. C math functions that take two input arguments (e.g., pow() ) are available as two-argument jq functions that ignore . . C math functions that take three input arguments are available as three-argument jq functions that ignore . .

Availability of standard math functions depends on the availability of the corresponding math functions in your operating system and C math library. Unavailable math functions will be defined but will raise an error.

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 pow10 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 .

See your system’s manual for more information on each of these.

Two builtins provide minimal output capabilities, debug , and stderr . (Recall that a jq program’s output values are always output as JSON texts on stdout .) The debug builtin can have application-specific behavior, such as 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 stder with no additional decoration, not even a newline.

Most jq builtins are referentially transparent, and yield constant and repeatable value streams when applied to constant inputs. This is not true of I/O builtins.

input


inputs

This is primarily useful for reductions over a program’s inputs.

debug


stderr


input_filename


input_line_number


STREAMING

However, streaming isn’t easy to deal with as the jq program will have [

, ] (and a few other forms) as inputs.

Several builtins are provided to make handling streams easier.

The examples below use the streamed form of [0,[1]] , which is [[0],0],[[1,0],1],[[1,0]],[[1]] .

Streaming forms include [

, ] (to indicate any scalar value, empty array, or empty object), and [

] (to indicate 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.

truncate_stream(stream_expression)


fromstream(stream_expression)


tostream


ASSIGNMENT

If an object has two fields which are arrays, .foo and .bar , and you append something to .foo , then .bar will not get bigger, even if you’ve previously set .bar = .foo . If you’re used to programming in languages like Python, Java, Ruby, Javascript, etc. then you can think of it as though jq does a full deep copy of every object before it does the assignment (for performance it doesn’t actually do that, but that’s the general idea).

This means that it’s impossible to build circular values in jq (such as an array whose first element is itself). This is quite intentional, and ensures that anything a jq program can produce can be represented in JSON.

All the assignment operators in jq have path expressions on the left-hand side (LHS). The right-hand side (RHS) provides values to set to the paths named by the LHS path expressions.

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 . , then outputting the modified value. This might be made clear by this example: >> | (.a.b|=3), . . This will output <"a":<"b":3>> and <"a":<"b":<"c":1>>> because the last sub-expression, . , sees the original value, not the modified value.

Most users will want to use modification assignment operators, such as |= or += , rather than = .

Note that the LHS of assignment operators refers to a value in . . Thus $var.foo = 1 won’t work as expected ( $var.foo is not a valid or useful path expression in . ); use $var | .foo = 1 instead.

Note too that .a,.b=0 does not set .a and .b , but (.a,.b)=0 sets both.

Update-assignment: |=

The left-hand side can be any general path expression; see path() .

Note that the left-hand side of ‘|=’ refers to a value in . . Thus $var.foo |= . + 1 won’t work as expected ( $var.foo is not a valid or useful path expression in . ); use $var | .foo |= . + 1 instead.

If the right-hand side outputs no values (i.e., empty ), then the left-hand side path will be deleted, as with del(path) .

If the right-hand side outputs multiple values, only the first one will be used (COMPATIBILITY NOTE: in jq 1.5 and earlier releases, it used to be that only the last one was used).

Arithmetic update-assignment: +=, -=, *=, /=, %=, //=


Plain assignment: =

If the RHS of ‘=’ produces multiple values, then for each such value jq will set the paths on the left-hand side to the value and then it will 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.

This example should show the difference between ‘=’ and ‘|=’:

Provide input ‘<"a": <"b": 10>, «b»: 20>’ to the programs:

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>.

Another example of the difference between ‘=’ and ‘|=’:

Complex assignments

What may come as a surprise is that the expression on the left may produce multiple results, referring to different points in the input document:

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).

When jq encounters an assignment like ‘a = b’, it records the «path» taken to select a part of the input document while executing a. This path is then used to find which part of the input to change while executing the assignment. Any filter may be used on the left-hand side of an equals — whichever paths it selects from the input will be where the assignment is performed.

This is a very powerful operation. Suppose we wanted to add a comment to blog posts, using the same «blog» input above. This time, we only want to comment on the posts written by «stedolan». We can find those posts using the «select» function described earlier:

The paths provided by this operation point to each of the posts that «stedolan» wrote, and we can comment on each of them in the same way that we did before:

MODULES

Modules imported by a program are searched for in a default search path (see below). The import and include directives allow the importer to alter this path.

Paths in the a search path are subject to various substitutions.

For paths starting with «

/», the user’s home directory is substituted for «

For paths starting with «$ORIGIN/», the path of the jq executable is substituted for «$ORIGIN».

For paths starting with «./» or paths that are «.», the path of the including file is substituted for «.». For top-level programs given on the command-line, the current directory is used.

Import directives can optionally specify a search path to which the default is appended.

The default search path is the search path given to the -L command-line option, else [«

Null and empty string path elements terminate search path processing.

A dependency with relative path «foo/bar» would be searched for in «foo/bar.jq» and «foo/bar/bar.jq» in the given search path. This is intended to allow modules to be placed in a directory along with, for example, version control files, README files, and so on, but also to allow for single-file modules.

Consecutive components with the same name are not allowed to avoid ambiguities (e.g., «foo/foo»).

For example, with -L$HOME/.jq a module foo can be found in $HOME/.jq/foo.jq and $HOME/.jq/foo/foo.jq .

If «$HOME/.jq» is a file, it is sourced into the main program.

import RelativePathString as NAME [ ];

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.

include RelativePathString [ ];

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 [ ];

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 ;

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

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.

COLORS

The default color scheme is the same as setting «JQ_COLORS=1;30:0;39:0;39:0;39:0;32:1;39:1;39» .

This is not a manual for VT100/ANSI escapes. However, each of these color specifications should consist of two numbers separated by a semi-colon, where 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)

Источник

Оцените статью