Basic operations
Identity operator(.)
.Object Identifier-Index
.name
.address.cityGeneric Object Index
.["name"]
.address.["postal-code"]
.["address"].["postal-code"]Array operations
array index
.car.options[1]
.[1]array/string slice
.[10:]
.[10:15]
.[:15]Object Construction
select fields without renaming
.{make, model}
.car.{make, model}select fields with renaming
.{carMake: .make, carModel: .model}
//{"carMake": "mini cooper", "carModel": "countryman"}concatenate fields
.{car: (.make + .model)}
{car: (.make + " wroom!")}value as field name
.{(.make): .model}
//{"mini cooper": "countryman"}Pipe
select from each element
.car.options[] | .priceAdvanced
Filtering JSON objects based on the value of a specific key
jq '.people[] | select(.age > 30)'Sorting JSON objects by key value
jq '.people[] | sort_by(.age)'Grouping JSON objects based on a key value
jq '.people[] | group_by(.gender) | map({key: .[0].gender, value: map(.name)})'Flattening nested JSON objects
jq '.people[].address[]'Merging multiple JSON objects into one
jq --slurp 'reduce .[] as $item ({}; . * $item)'map/to_entries/from_entries/with_entries
map - <
map(x) is equivalent to [.[] | x].countries | map({name, id, people: .population})map_values - similar to map but works well for objects
map_values({name, ageYears: .age})to_entries - Convert from object to an array of key value paris
//input
{
"john": "smith",
"bob": "iger"
}
to_entries
// output
[
{
"key": "john",
"value": "smith"
},
{
"key": "bob",
"value": "iger"
}
]from_entries - convert from an array from key/value pairs to an object
//input
[
{
"key": "john",
"value": "smith"
},
{
"key": "bob",
"value": "iger"
}
]
//command
from_entries
//output
{
"john": "smith",
"bob": "iger"
}with_entries combines it together
with_entries(.key |= ("0"+.))if/else and helper functions
if/else
if .age > 30 then "old" else "young" end;if/elif/else
if .age > 30 then "old" elif .age > 20 then "middle" else "young" end;helper functions
def isOld: .age > 30;
{old: .age | isOld}