I a have a short TSV stream that outputs key/value pairs and I would like to create a JSON object out of it, with jq
.
For now I have this code, which generates a stack of JSON objects:
printf '%s\t%s\n' key1 val1 key2 val2 |
jq -R 'rtrimstr("\n") | split("\t") | { (.[0]): .[1] }'
{
"key1": "val1"
}
{
"key2": "val2"
}
I can pipe it to jq -s 'add'
for getting my expected output:
{
"key1": "val1",
"key2": "val2"
}
But, is it possible to get this output with a single jq
call?
Use -n
and inputs
to access the stream item by item.
For instance using reduce
:
jq -Rn 'reduce (inputs/"\t") as [$k,$v] ({}; .[$k] = $v)'
Or using from_entries
:
jq -Rn '[inputs/"\t" | {key: .[0], value: .[1]}] | from_entries'