简体   繁体   中英

How I can transform json to csv with jq?

My json file is similar of this:

{
"A1": "1.2"
"A2": "3.5"
"A3": "2.6"
}

I need transform it to csv file and it looks like this

A1,1.2
A2,3.5
A3,2.6

My code is

jq -r 'map(.[] | tonumber) | @csv' file.json > file.csv

and my result is

1.2,3.5,2.6

Once you fix your example JSON so it's valid:

$ jq -r 'to_entries[] | [.key, (.value | tonumber)] | @csv' input.json
"A1",1.2
"A2",3.5
"A3",2.6

to_entries turns an object into an array of objects with the key field holding the name of one of the original object's keys and value its corresponding value. Then turn each of those objects into a two-element array which is fed to @csv .

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