Search code examples
streamjqtruncate

Explanation needed for truncate_stream example in jq manual


I study jq manual and blocked in truncate_stream examples as follows:

$ echo '1' | jq -c '[ 1 |truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]'
[[[0],2],[[0]]]

Can someone explain the example in detail?

Thanks for your interest on basic question.

Cheers.


Solution

  • First, the manual is slightly misleading in that the input value shown ("Input 1") is irrelevant. This can be seen e.g. from the fact that the following invocation produces the same array:

    $ jq -n -c '[ 1 |truncate_stream([[0],1],[[1,0],2],[[1,0]],[[1]])]'
    [[[0],2],[[0]]]
    

    Now, to understand how we get from what I'll call the input stream:

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

    to the output stream:

    [[0],2], [[0]]]
    

    it is helpful to remember that each array in the input stream either has the form

    [path, value]
    

    or else the form

    [path]
    

    The effect of N | truncate_stream(STREAM) where N is a non-negative integer is to remove the first N elements of each path with the understanding that any item in which path == [] is to be removed.

    Thus, removing the first item from each path yields:

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

    and this then becomes:

    [[0],2], [[0]]
    

    Q.E.D.