Here’s my quick reference for getting for some of the basic commands in the command line tool jq
. For the uninitiated - JQ is a json manipulation tool which allows you to perform all sorts of operations on a JSON string passed via an argument or stdin.
This doc isn’t meant to be used as a comprehensive manpage, but a quick reference for operations in JQ that I use a lot.
We’ll be using the following json as input for the next examples:
[
{ "name": "Harry Potter" },
{ "name": "Ron Weasley" },
{ "name": "Hermione Granger" }
]
Extract List Elements
We can extract a field from each item item as valid as json:
$ cat students.json | jq '.[].name'
"Harry Potter"
"Ron Weasley"
"Hermione Granger"
However, if we’re reading these values in a shell script for some other use, it’s probably better to not have the quotes, using the -r
“raw” option to print just the text:
$ cat students.json | jq -r '.[].name'
Harry Potter
Ron Weasley
Hermione Granger
Modifying elements
We can set properties on arbitrary elements like in this example. However, if we omit the 0
in the filter, it’ll set the property on all of the students.
$ cat students.json | jq '.[0].age = 11'
[
{
"name": "Harry Potter",
"age": 11
},
{
"name": "Ron Weasley"
},
{
"name": "Hermione Granger"
}
]
Deleting Properties
We can also delete properties from the json source. To do this, we use the del()
function and the Update-assignment |=
operator:
# this'll leave us with empty objects, because all we have are names!
$ cat students.json | jq '.[] |= del(.name)'
[
{},
{},
{}
]
Adding to lists
We can also use JQ to append to arrays inside of json. For example, we can add a student like so:
$ cat students.json | jq '. += [{ "name": "Draco Malfoy" }]'
[
{
"name": "Harry Potter"
},
{
"name": "Ron Weasley"
},
{
"name": "Hermione Granger"
},
{
"name": "Draco Malfoy"
}
]
A useful feature of jq
is it accepts content from stdin (which we’re already using via cat
). This means we can pipeline them together in order to get a list of the modified students. For example, we could use curl
to fetch something, and then JQ to parse or modify it.
$ cat students.json | jq '. += [{ "name": "Draco Malfoy" }]' | jq -r '.[].name'
Harry Potter
Ron Weasley
Hermione Granger
Draco Malfoy