how.wtf

Passing variables to jq

· Thomas Taylor

Passing a shell / bash variable / environment variable to jq is simple using the native functionality of:

--arg name value or --argjson name value.

How to pass variable to jq filters

This is a generic projects.json file:

 1{
 2	"projects": [
 3		{
 4			"name": "project 1",
 5			"owner": "owner 1",
 6			"id": 1,
 7			"version": "2.3.0"
 8		},
 9		{
10			"name": "project 2",
11			"owner": "owner 1",
12			"id": 2,
13			"version": "1.54.0"
14		},
15		{
16			"name": "project 3",
17			"owner": "owner 2",
18			"id": 3,
19			"version": "4.9.2"
20		}
21	]
22}

String variables

Retrieve project information via a name supplied by a user.

1echo "Enter name: "
2read name
3
4cat projects.json | 
5	jq -r --arg n "$name" '.projects[]|select(.name == $n)'

Output:

1Enter name: 
2project 1
3{
4  "name": "project 1",
5  "owner": "owner 1",
6  "id": 1,
7  "version": "2.3.0"
8}

--arg name value: value is automatically interpreted as a string.

Number variables

Retrieve project information via an id supplied by a user.

1echo "Enter id: "
2read id
3
4cat projects.json | 
5    jq -r --arg id "$id" '.projects[]|select(.id == ($id|tonumber))'

Output:

1Enter id: 
22
3{
4  "name": "project 2",
5  "owner": "owner 1",
6  "id": 2,
7  "version": "1.54.0"
8}

--arg name value: value must be explicitly converted to a number using the native tonumber function.

Optionally, --argjson name value may be used in jq versions 1.5 or higher. --argjson respects the value type. Following the same example as before,

1echo "Enter id: "
2read id
3
4cat projects.json | 
5    jq -r --argjson id "$id" '.projects[]|select(.id == $id)'

Output:

1Enter id: 
22
3{
4  "name": "project 2",
5  "owner": "owner 1",
6  "id": 2,
7  "version": "1.54.0"
8}

#linux  

Reply to this post by email ↪