Search code examples
arraysjsonbashexport-to-csvjq

Generate CSV pairing a field and multiple array elements


Example input:

{
  "firstName": "Jam",
  "Product": [
    {
      "productId": "5e09ad38986b7c30f339c5c0"
    },
    {
      "productId": "5e09407b986b7c30f339c18e"
    },
    {
      "productId": "5e094c2a986b7c30f339c1d2"
    }
  ]
}

Expected output:

Jam,5e09ad38986b7c30f339c5c0
Jam,5e09407b986b7c30f339c18e
Jam,5e094c2a986b7c30f339c1d2

Current command is producing the output but on the same row comma seperated:

jq -rc '.firstName,.Product[0] .productId'

Solution

  • To generate a report in CSV format you need to put column values into an array and pass it to @csv filter.

    $ jq -r '[.firstName] + (.Product[] | [.productId]) | @csv' file
    "Jam","5e09ad38986b7c30f339c5c0"
    "Jam","5e09407b986b7c30f339c18e"
    "Jam","5e094c2a986b7c30f339c1d2"