jq · lesson 6 of 32 · Pipes & building output

Building objects

{ … } builds a new object. {name} is shorthand for {name: .name}, and a value can be any expression — wrap computed ones in parentheses.

Examples

Example 1Reshape each member

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

.members[] | {name, next_age: (.age + 1)}
  1. {name Shorthand: copy the key name and its value from the input (same as name: .name).
  2. next_age A brand-new key…
  3. (.age + 1) …whose value is any expression, run against each member. The parentheses group it.

Result

{"name":"Ada","next_age":37}
{"name":"Linus","next_age":29}
{"name":"Grace","next_age":46}
{"name":"Alan","next_age":42}

Try it in the playground

Example 2Use a value as a key

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

.members | map({(.name): .age}) | add
  1. map( Run the filter inside on every element and collect the results in an array.
  2. {(.name): .age} A computed key: the parentheses make .name an expression, so each member becomes a one-key object.
  3. | add Merge the array of small objects into one lookup table.

Result

{"Ada":36,"Linus":28,"Grace":45,"Alan":41}

Try it in the playground

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.