jq Cheat Sheet
How to perform common operations on JSON documents.
jq is a very useful tool for parsing and manipulating JSON documents on the command line. For a comprehensive reference on all the features, see the jq manual.
The following examples will use this data.json
document as input:
{
"name": "Julia Sommers",
"items": ["car", "horse", "laptop"],
"friends": [
{ "name": "Amanda Brush", "pet": "dog" },
{ "name": "January Stiles", "pet": "bird" },
{ "name": "Grace Rose", "pet": "bird" }
]
}
Identity
jq '.' data.json
{
"name": "Julia Sommers",
"items": ["car", "horse", "laptop"],
"friends": [
{
"name": "Amanda Brush",
"pet": "dog"
},
{
"name": "January Stiles",
"pet": "bird"
},
{
"name": "Grace Rose",
"pet": "bird"
}
]
}
Get single value from document
jq --raw-output '.name' data.json
Julia Sommers
Get the first N items of an array
jq '.items[:2]' data.json
["car", "horse"]
Map an array
jq '[.friends[] | .name]' data.json
["Amanda Brush", "January Stiles", "Grace Rose"]
Filter an array
jq '[.friends[] | select(.pet=="bird")]' data.json
[
{
"name": "January Stiles",
"pet": "bird"
},
{
"name": "Grace Rose",
"pet": "bird"
}
]
Reduce an array
jq --raw-output 'reduce .items[] as $item (""; . + $item)' data.json
carhorselaptop
Recursively get values from a key name
Return all the values associated with the name
key, recursively.
jq --raw-output 'recurse | objects | .name' data.json
Julia Sommers
Amanda Brush
January Stiles
Grace Rose