jq · lesson 29 of 32 · Event streams

tostream

tostream flattens any value into events: [path, value] for every leaf, and a one-element [path] event that closes each array or object. The path lists the keys and indexes that lead to the value.

Examples

Example 1The events of a small value

Document

{ "a": [1, [2, 3]], "b": { "c": "x" } }

Query

.a | tostream
  1. .a The array [1, [2, 3]].
  2. tostream One [path, value] event per number, and a closing [path] event after the last item of each array.

Result

[[0],1]
[[1,0],2]
[[1,1],3]
[[1,1]]
[[1]]

Try it in the playground

Example 2Every leaf as path = value

Document

{ "a": [1, [2, 3]], "b": { "c": "x" } }

Query

tostream | select(length == 2) | "\(.[0] | map(tostring) | join(".")) = \(.[1])"
  1. tostream Every event of the whole document.
  2. select(length == 2) Keep the leaf events; the closing ones have only a path.
  3. .[0] | map(tostring) | join(".") The path as text: keys and indexes joined with dots.
  4. \(.[1]) The leaf's value.

Result

"a.0 = 1"
"a.1.0 = 2"
"a.1.1 = 3"
"b.c = x"

Try it in the playground

Example 3Where is a value?

Document

{ "a": [1, [2, 3]], "b": { "c": "x" } }

Query

tostream | select(.[1] == 3) | .[0]
  1. tostream Every event of the document, however deep.
  2. select(.[1] == 3) Keep the events whose value is 3. A closing event has no value, so for it .[1] is null.
  3. | .[0] Read the path: key a, then index 1, then index 1 again.

Result

["a",1,1]

Try it in the playground

Good to know

  • An empty array or object is a leaf of its own, [path, []] or [path, {}], and a lone scalar is [[], value].
  • A closing event carries the path of its container's last child. In the first example [[1,1]] ends the inner array [2, 3] after its index 1, and [[1]] ends the outer array after its index 1.

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.