Home > front end >  Convert a Single line of JSON to csv using jq in shell bash script
Convert a Single line of JSON to csv using jq in shell bash script

Time:07-25

{
  "name": "john",
  "age": "22",
  "state": "Texas",
  "city": "Dallas",
  "dailysteps": 99,
  "weeklysteps": 2377,
  "monthlysteps": 330003
}

For example, i have this line of json data (lets call it data.json) and i need to convert it to csv with the following output format (pls, output example in picture attached).I'm only interested in picking out the dailysteps, weeklysteps and monthlysteps and adding a "Total Steps" column like in the picture attached

It should have its custom Title Headers like this

Daily Steps, Weekly Steps, Monthly Steps, Total Steps
99 , 2377 , 330003 , 332479

example

CodePudding user response:

Would this do it?

jq -r '
  ["Daily Steps", "Weekly Steps", "Monthly Steps", "Total Steps"], 
  ([.dailysteps, .weeklysteps, .monthlysteps] | .   [add])
  | @csv
' data.json
"Daily Steps","Weekly Steps","Monthly Steps","Total Steps"
99,2377,330003,332479

Demo

  • Related