Home > Software engineering >  How to convert a hash of an array of array of hashes JSON input into CSV using jq?
How to convert a hash of an array of array of hashes JSON input into CSV using jq?

Time:11-20

I want to convert the following JSON content stored in a file input.json

{
    "results": [
        [
           {
               "field": "field1",
               "value": "value1-1"
           },
           {
               "field": "field2",
               "value": "value1-2"
           },
           {
               "field": "field3",
               "value": "value1-3"
           }
        ],
        [
           {
               "field": "field1",
               "value": "value2-1"
           },
           {
               "field": "field2",
               "value": "value2-2"
           },
           {
               "field": "field3",
               "value": "value2-3"
           }
        ],
        [
           {
               "field": "field1",
               "value": "value3-1"
           },
           {
               "field": "field2",
               "value": "value3-2"
           },
           {
               "field": "field3",
               "value": "value3-3"
           }
        ]
    ]
}

into a CSV output

"field1","field2","field3"
"value1-1","value1-2","value1-3"
"value2-1","value2-2","value2-3"
"value3-1","value3-2","value3-3"

The closest jq expression I've come up with is this:

$ cat input.json | jq -r '.results | .[] | map(.field), map(.value) | @csv'
"field1","field2","field3"
"value1-1","value1-2","value1-3"
"field1","field2","field3"
"value2-1","value2-2","value2-3"
"field1","field2","field3"
"value3-1","value3-2","value3-3"

which is still not correct. How should I write the jq expression to get the desired CSV output?

CodePudding user response:

You are feeding .[] into map(.field) as well as map(.value).

Use map(.field) only on the first item, and map(.value) on all items .[]:

jq -r '.results | (first | map(.field)), (.[] | map(.value)) | @csv' input.json 

Demo

  • Related