CodeBot
CodeBot

Reputation: 165

converting csv to json not working as expected?

I am following this article to convert csv to json. But I am not getting required output.

step 1 -

$ echo -e "foo,bar,quux\n1,2,3\n4,5,6\n7,8,9" > foo.csv

Test Step 2 -

$ jq -R 'split(",")' foo.csv | jq -cs

The output is as expected as below -

[["foo","bar","quux"],["1","2","3"],["4","5","6"],["7","8","9"]]

Next i copied the code from jq cookbook in to csv2json.jq and executed below command.

$ jq -cR 'split(",")' foo.csv | jq -csf csv2json.jq

But i am not getting expected output, I am getting below output -

[["foo","bar","quux"],["1","2","3"],["4","5","6"],["7","8","9"]]

Could someone help me fix this. Thanks in advance.

The expected or required output is -

[
 {
   "foo": 1,
   "bar": 2,
   "quux": 3
 },
 {
   "foo": 4,
   "bar": 5,
   "quux": 6
 },
 {
   "foo": 7,
   "bar": 8,
   "quux": 9
 }
]

Upvotes: 0

Views: 212

Answers (1)

Fravadona
Fravadona

Reputation: 17290

I would use Miller (available here for several OSs) for this task:

mlr --c2j cat foo.csv

Output:

[
{
  "foo": 1,
  "bar": 2,
  "quux": 3
},
{
  "foo": 4,
  "bar": 5,
  "quux": 6
},
{
  "foo": 7,
  "bar": 8,
  "quux": 9
}
]

Upvotes: 3

Related Questions