Search code examples
jsonexport-to-csvjq

Add element outside of array to csv output


I have a JSON structure similar to this one:

{
  "results": [
    {
      "title": "Page 1",
      "content": {
        "id": "11111"
      }
    },
    {
      "title": "Page 2",
      "content": {
        "id": "22222"
      }
    },
    {
      "title": "Page 3",
      "content": {
        "id": "33333"
      }
    }
  ],
  "start": 0,
  "limit": 25,
  "size": 3,
  "totalSize": 3,
  "query": "Hello World"
}

The output I need is:

"Page 1","11111","Hello World"
"Page 2","22222","Hello World"
"Page 3","33333","Hello World"

I can get the elements from the array with: cat my.json | jq -r '.results[] | [.title, .content.id] | @csv' But how do I add the "query" element which is outside of the array to each line in the output?

I tried a bunch of options but I can't get it to work.


Solution

  • Use a little placeholder to store the value of .query and use it back when putting it in array

    .query as $q | .results[] | [.title, .content.id, $q] | @csv
    

    Or put them in separate arrays. The (...) around .results path ensures, you don't walk to the path below and still remain at the top level node path.

    (.results[] | [.title, .content.id]) + [.query] | @csv