Using Variables in JQ (Command Line JSON Parser)

jq is a lightweight command line JSON processor that is very easy to use. Sometimes being able to use variables within a jq script is very useful. Below are various examples of doing this. Here is a sample record from the JSON file we use in most examples:

Using Simple Variables in jq

To use a simple variable in jq use the --arg option. Using --arg var value will set the variable $var to value. For example, here we set the $dt variable to add dates to our JSON records:

This variable can also be used to represent both a JSON field and value:

Using Environment Variables in jq

Environment variables can be used in jq in a couple of different ways shown below:

In jq versions > 1.4 you can reference environment variables directory in your jq program using env.varname:

Using JSON Variables in jq

If you want to use variables that reference JSON objects, this can be done with the --argsjson option. Using --argjson var object will set the variable $var to object. In the example below we set the $location variable to a JSON object, and nest this object into our results.

Using JSON Array Variables in jq

Using the --slurp option you can store all JSON input records into an array. Using the --slurpfile option you can store all JSON records from a file into an array, and reference this array using a variable.

Here is an example of reading all JSON records from sample.json into $myArray, and using this variable to build another JSON object.

jq is a great library and I highly recommend reading through the official documentation found here.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">