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")
  1. keys The object's key names, as a sorted array.
  2. has("city") Does the key exist? → true.

Result

["city","floor"]
true

Try it in the playground

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)
  1. + {country: "DE"} Merge two objects: country is added, and on a clash the right side wins.
  2. with_entries( Turn the object into {key, value} pairs, run the filter on each pair, and rebuild an object.
  3. .value |= tostring Update each pair's value to a string — so 3 becomes "3".

Result

{"city":"Berlin","floor":"3","country":"DE"}

Try it in the playground

Good to know

  • to_entries and from_entries are the two halves of with_entries: .office | to_entries gives [{"key":"city","value":"Berlin"}, …].

About jsonquery

Query, format and learn JSON with jq, JSONPath, JMESPath and JSON Pointer. It is the engine of the desktop app, run in your browser.

Engine
The desktop app’s, compiled to WebAssembly
Licence
MIT (the engine and the app)
Source
GitHub
Contact
The contact form (private)
Public issues
GitHub
Legal
Privacy policy

Known limitations: a file over 10 MB opens read-only and one over 512 MB does not open here; the desktop app has no such limit.