There is JSON like below:
{
"data": [
{
"a": 1,
"d": 2,
"c": 3,
"b": 4
},
{
"a": 5,
"d": 6,
"c": 7,
"b": 8,
"e": 9
}
]
}
I want to transform it to the table like this:
c d a b e
3 2 1 4 <absent>
7 6 5 8 9
So:
- Columns
c
andd
are moved to the beginning of the table; - All other columns are sorted alphabetically.
2
Answers
If the key names are known, you could pre-define their order in a variable as an array, then use that for the header as well as the columns in each row.
@tsv
will turn arrays into tab-separated text, so make sure to usejq -r
orjq --raw-output
.Demo
If the
<absent>
string was intended to be inserted literally, use//
to provide an alternative content:Demo
Then scan the keys first, make a
unique
list, dropc
andd
, and prepend them. This is your dynamic$keys
variable.Demo