Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a json file to csv using shell script without using jq?

Tags:

linux

bash

shell

I want to convert a json file to csv using shell script without using jq. Is it possible?

Here is a json :

{
  "id": "0001",
    "type": "donut",
    "name": "Cake",
    "ppu": 0.55,
},
{
"id": "0002",
    "type": "donut2",
    "name": "Cake2",
    "ppu": 0.5522,
}

I don't want to use jq.

I want to store it in a csv file.

like image 538
Shubham Avatar asked Jul 18 '26 22:07

Shubham


1 Answers

Bare-bones core-only perl one-liner version, to complement the python and ruby ones already given:

perl -MJSON::PP -0777 -nE '$,=","; say @$_{"id","type","name","ppu"} for @{decode_json $_}' input.json

A more robust one would use a more efficient non-core JSON parser and a CSV module to do things like properly quote fields when needed, but since your sample data doesn't include such fields I didn't bother. Can if requested.


And the unrequested jq version, because that really is the best approach whether you want it or not:

jq -r '.[] | [.id, .type, .name, .ppu] | @csv' input.json
like image 91
Shawn Avatar answered Jul 21 '26 10:07

Shawn