简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM