Home > Software engineering >  jq: convert all fields of a JSON object into CSV
jq: convert all fields of a JSON object into CSV

Time:07-28

I have this JSON object

{
  "a": 68370432,
  "b": 50462720,
  "c": 53608448,
  "d": 245039104
}

where a, b, c, d are arbitrary field names, with plain values.

How to convert it into a CSV like this using jq ?

a,68370432
b,50462720
c,53608448
d,245039104

CodePudding user response:

You can use to_entries in order to be able to derive key-value pairs, then combine the pieces by using join such as

jq -r '. | to_entries[] | [ .key, .value ] | join(",")'

Demo

or use without individually paraphraising key and value such as

jq -r '. | to_entries[] | [ .[] ] | join(",")'

Demo

or if the quotes should be kept within the results, then use

jq -r '. | to_entries[] | [ .[] ] | @csv'

Demo

  • Related