jq · lesson 15 of 32 · Transforming
Working with objects
keys lists the key names, has(k) tests for one, a + b merges two objects (the right side wins), and with_entries(f) rewrites keys and values through {key, value} pairs.
Examples
Example 1Key names, and whether a key exists
Document
{
"team": "Platform",
"office": { "city": "Berlin", "floor": 3 },
"members": [
{ "name": "Ada", "age": 36, "role": "lead", "active": true,
"email": "[email protected]", "skills": ["rust", "sql"] },
{ "name": "Linus", "age": 28, "role": "dev", "active": true,
"email": null, "skills": ["c", "shell"] },
{ "name": "Grace", "age": 45, "role": "dev", "active": false,
"skills": ["cobol"] },
{ "name": "Alan", "age": 41, "role": "qa", "active": true,
"email": "[email protected]", "skills": [] }
]
}Query
.office | keys, has("city")
keysThe object's key names, as a sorted array.has("city")Does the key exist? →true.
Result
["city","floor"] true
Example 2Merge, then rewrite every value
Document
{
"team": "Platform",
"office": { "city": "Berlin", "floor": 3 },
"members": [
{ "name": "Ada", "age": 36, "role": "lead", "active": true,
"email": "[email protected]", "skills": ["rust", "sql"] },
{ "name": "Linus", "age": 28, "role": "dev", "active": true,
"email": null, "skills": ["c", "shell"] },
{ "name": "Grace", "age": 45, "role": "dev", "active": false,
"skills": ["cobol"] },
{ "name": "Alan", "age": 41, "role": "qa", "active": true,
"email": "[email protected]", "skills": [] }
]
}Query
.office + {country: "DE"} | with_entries(.value |= tostring)
+ {country: "DE"}Merge two objects:countryis added, and on a clash the right side wins.with_entries(Turn the object into{key, value}pairs, run the filter on each pair, and rebuild an object..value |= tostringUpdate each pair's value to a string — so3becomes"3".
Result
{"city":"Berlin","floor":"3","country":"DE"}Good to know
to_entriesandfrom_entriesare the two halves ofwith_entries:.office | to_entriesgives[{"key":"city","value":"Berlin"}, …].