Home > Blockchain >  JQ Add (static) header before filter
JQ Add (static) header before filter

Time:11-20

Consider the following (simplified) JSON:

[
    {
        "type": "foo",
        "name": "test_1"
    },
    {
        "type": "bar",
        "name": "test_2"
    },
    {
        "type": "bar",
        "name": "test_3"
    }
]

I'm using the following filter to generate my output:

group_by(.type)[][] | "\(if "type" == "foo" then "oof" else "rab" end)&\(.name)"

This produces

rab&test_2
rab&test_3
rab&test_1

Demo

Using column -ts '&' this gets converted to:

rab  test_2
rab  test_3
rab  test_1

My problem; I need to add a custom header line, so that the output becomes:

test&foo&bar
rab&test_2
rab&test_3
rab&test_1

There are many questions how to add (a static) set of header lines, like:

But I'm unable to combine it so I can leave the group_by intact and let column handle the spacing

(I'd rather let column handle the spacing)


tl;dr;
How can I add a custom header array, something like:

[ "test", "foo", "bar" ] | join("&")

So that

  • The group_by and everything behind it isn't changed
  • column can parse the output

Edit, of course I can pull off the column from the jq command, and 'abuse' echo like so:

ugly=$(curl --silent <URI> \
        | jq -r 'group_by(.type)[][] | "\(if "type" == "foo" then "oof" else "rab" end)&\(.name)"' \
        | egrep --color -E "FooBar|$")
headers="foo#bar#foorbar"
echo "$headers\n$ugly" | column -ts '#' \

But I'd rather keep the | column on the jq part so that echo and $ugly aren't needed.

CodePudding user response:

Enclose your expression in brackets and add | ["test&foo&bar"] . | .[] at the end.

[group_by(.type)[][] | "\(if "type" == "foo" then "oof" else "rab" end)&\(.name)"] | ["test&foo&bar"]   . | .[]

Not sure why you need columns. Seems like you can just replace & with \t.

  • Related