Home > Mobile >  convert json to csv using jq bash
convert json to csv using jq bash

Time:05-06

have a JSON data like below

"metric": {
   "name" : "name1"
},
"values": [
 [
   16590879,
   "0.043984349"
],
"values": [
 [
   16590876,
   "0.043983444"
]
]

} }

writing below jq , but not giving proper result

jq -r '[.metric.name,(.values[] | map(.) | @csv)'

Actual result

[
"name1",
"16590879",\"0.043984349\"",
"16590876",\"0.043983444\"",
"16590874",\"0.043934345\""

Expected result

name1,16590879,0.043984349
name1,16590876,0.043983444
name2,16590874,0.043934345

CodePudding user response:

The sample data provided is invalid as JSON, but assuming it has been adjusted as shown below, we would have:

< sample.json  jq -r '[.metric.name]   .values[] | @csv'
"name1",16590879,"0.043984349"
"name1",16590876,"0.043983444"

If you don't want the quotation marks, then use join(",") instead of @csv.


sample.json

{
  "metric": {
    "name": "name1"
  },
  "values": [
    [
      16590879,
      "0.043984349"
    ],
    [
      16590876,
      "0.043983444"
    ]
  ]
}
  • Related