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
.aThe array[1, [2, 3]].tostreamOne[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]]
Example 2Every leaf as path = value
Document
{ "a": [1, [2, 3]], "b": { "c": "x" } }Query
tostream | select(length == 2) | "\(.[0] | map(tostring) | join(".")) = \(.[1])"
tostreamEvery event of the whole document.select(length == 2)Keep the leaf events; the closing ones have only a path..[0] | map(tostring) | join(".")The path as text: keys and indexes joined with dots.\(.[1])The leaf's value.
Result
"a.0 = 1" "a.1.0 = 2" "a.1.1 = 3" "b.c = x"
Example 3Where is a value?
Document
{ "a": [1, [2, 3]], "b": { "c": "x" } }Query
tostream | select(.[1] == 3) | .[0]
tostreamEvery event of the document, however deep.select(.[1] == 3)Keep the events whose value is 3. A closing event has no value, so for it.[1]isnull.| .[0]Read the path: keya, then index 1, then index 1 again.
Result
["a",1,1]
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.