Looking for a one liner with csvkit.
From a plain json object
{
"whatever": 2342,
"otherwise": 119,
"and": 1,
"so": 2,
"on": 3
}
Want this csv
whatever,2342
otherwise,119
and,1
so,2
on,3
I basically want this command to work, but it doesn't.
echo $the_json | in2csv -f json
> When converting a JSON document with a top-level dictionary element, a key must be specified.
Seems like something csvkit can do, and I just haven't found the right options.
short answer
variant A:
in2csv(csvkit) +csvtoolin2csv's-Ioption to avoid unexpected behaviorvariant B: use
jqinsteadThis is a solution using only
jq: (https://stedolan.github.io/jq/)taken from How to map an object to arrays so it can be converted to csv?
long answer (csvkit + csvtool)
the input
in2csv -f jsonexpects a list of JSON objects, so you need to wrap the single object ({...}) into square brackets ([{...}]).On POSIX compatible shells, write
which will print
the csvkit command
You may pipe the above data directly into
in2csv. However, you might run into issues with the ”type inference“ (CSV data interpretation) feature of csvkit:1has becomeTrue. For details, see the Tips and Troubleshooting part of the docs. It's suggested to turn off type inference using the-Ioption:Now the result is as expected
transpose the data
Still, you need to transpose the data. The csvkit docs say:
(
csvtoolis available on github, opam, debian and probably other distribution channels.)Using csvkit + csvtool, your final command looks like this:
with the hyphen (
-) meaning to take the data fromstdin. This is the result:that's it.
I think there is no one-liner solution with
csvtoolonly, you'll needin2csv. You may, however, usejqinstead, see the short answer.FTR, I'm using csvkit version 1.0.3.