Convert a Single line of JSON to csv using jq in shell bash script

Viewed 65
{
  "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

1 Answers

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


To add another column with the current hour in the local timezone (as requested in a comment), using now - 3600 | localtime[3] would be an option:

jq -r '
  ["Hours", "Daily Steps", "Weekly Steps", "Monthly Steps", "Total Steps"],
  ([.dailysteps, .weeklysteps, .monthlysteps] | [now - 3600 | localtime[3]] + . + [add])
  | @csv
'
"Hours","Daily Steps","Weekly Steps","Monthly Steps","Total Steps"
22,99,2377,330003,332479

Demo

To add the hour from a parameter provided externally to jq, use the --argjson option:

jq -r --argjson H "$(date +%H -d "1 hour ago")" '
  ["Hours", "Daily Steps", "Weekly Steps", "Monthly Steps", "Total Steps"],
  ([.dailysteps, .weeklysteps, .monthlysteps] | [$H] + . + [add])
  | @csv
'
"Hours","Daily Steps","Weekly Steps","Monthly Steps","Total Steps"
22,99,2377,330003,332479
Related