Last active
March 4, 2024 01:34
-
-
Save betandr/e27a91dca6b84ba55ae26fda3b2ba43c to your computer and use it in GitHub Desktop.
Fitbit Export Weight Data to CSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Converts the data created by Fitbit export from the output JSON | |
// to comma-separated values. | |
// go run main.go > weight.csv | |
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"os" | |
) | |
type Measurement struct { | |
Weight float32 | |
Date string | |
Time string | |
} | |
func main() { | |
path := "./data/" | |
file, err := os.Open(path + ".") | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "error: could not open data") | |
os.Exit(1) | |
} | |
var measurements []Measurement | |
stat, err := file.Stat() | |
if stat.IsDir() { | |
filenames, err := file.Readdirnames(0) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "error: could not read filenames") | |
os.Exit(1) | |
} | |
for _, f := range filenames { | |
ms, err := processFile(path + f) | |
if err == nil { // no errors | |
measurements = append(measurements, ms...) | |
} | |
} | |
} | |
printCSV(measurements) | |
} | |
func processFile(filename string) ([]Measurement, error) { | |
f, err := os.Open(filename) | |
if err != nil { | |
return nil, fmt.Errorf(fmt.Sprintf("error: could not read %s", filename)) | |
} | |
defer f.Close() | |
bytes, _ := ioutil.ReadAll((f)) | |
var measurements []Measurement | |
json.Unmarshal(bytes, &measurements) | |
return measurements, nil | |
} | |
func printCSV(measurements []Measurement) { | |
fmt.Println("date, time, weight (kg)") | |
for _, m := range measurements { | |
fmt.Printf("%s, %s, %f\n", m.Date, m.Time, conv(m.Weight)) | |
} | |
} | |
func conv(lbs float32) float32 { | |
return lbs * 0.4535924 | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment