Home > Mobile >  Can this jq map be simplified?
Can this jq map be simplified?

Time:02-02

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.

CodePudding user response:

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.

jq -r '[.key]   (.source_records[] | [.]) | @tsv'

Alternatively, instead of using @tsv you could build your tab-separated output string yourself. Either by concatenation (… …) or by string interpolation ("\(…)"):

jq -r '.key   "\t"   .source_records[]'
jq -r '"\(.key)\t\(.source_records[])"'

Output:

/books/OL1000072M   ia:daywithtroubadou00pern
/books/OL1000072M   bwb:9780822519157
/books/OL1000072M   marc:marc_loc_2016/BooksAll.2016.part25.utf8:103836014:1267

CodePudding user response:

It's not much shorter, but I think it's clearer than the original and clearer than the other shorter answers.

jq -r '.key as $olid | .source_records[] | [ $olid, . ] | @tsv'
  • Related