Given this JSON:
{
"key": "/books/OL1000072M",
"source_records": [
"ia:daywithtroubadou00pern",
"bwb:9780822519157",
"marc:marc_loc_2016/BooksAll.2016.part25.utf8:103836014:1267"
]
}
Can the following jq
code be simplified?
jq -r '.key as $olid | .source_records | map([$olid, .])[] | @tsv'
The use of variable assignment feels like cheating and I’m wondering if it can be eliminated. The goal is to map the key
value onto each of the source_records
values and output a two column TSV.
2
Answers
Instead of mapping into an array, and then iterating over it (
map(…)[]
) just create an array and collect its items ([…]
). Also, you can get rid of the variable binding (as
) by moving the second part into its own context using parens.Alternatively, instead of using
@tsv
you could build your tab-separated output string yourself. Either by concatenation (… + …
) or by string interpolation ("(…)"
):Output:
It’s not much shorter, but I think it’s clearer than the original and clearer than the other shorter answers.