diff --git a/ostat.go b/ostat.go index 5b86241..98313bd 100644 --- a/ostat.go +++ b/ostat.go @@ -4,6 +4,7 @@ package ostat import ( + "encoding/json" "fmt" "math" ) @@ -128,3 +129,22 @@ func (os *OnlineStat) String() string { }, ) } + +func (os *OnlineStat) MarshalJSON() ([]byte, error) { + s := struct { + N uint64 `json:"n"` + Min float64 `json:"min"` + Max float64 `json:"max"` + Mean float64 `json:"mean"` + Variance float64 `json:"variance"` + StdDev float64 `json:"std_dev"` + }{ + N: os.n, + Min: os.Min, + Max: os.Max, + Mean: os.Mean(), + Variance: os.Variance(), + StdDev: os.StdDev(), + } + return json.Marshal(s) +} diff --git a/ostat_test.go b/ostat_test.go index e9ace90..9d5defc 100644 --- a/ostat_test.go +++ b/ostat_test.go @@ -1,6 +1,8 @@ package ostat import ( + "bytes" + "encoding/json" "fmt" "math" "testing" @@ -279,3 +281,19 @@ func TestString(t *testing.T) { t.Errorf("failed to generate correct string") } } + + +func TestJson(t *testing.T) { + ps := NewPopulationStat() + for _, v := range []float64{1, 1, 2, 2} { + ps.Push(v) + } + expected := "{\"n\":4,\"min\":1,\"max\":2,\"mean\":1.5,\"variance\":0.25,\"std_dev\":0.5}\n" + buf := &bytes.Buffer{} + if err := json.NewEncoder(buf).Encode(ps); err != nil { + t.Fatalf("encoding problem:", err) + } + if got, want := expected, buf.String(); got != want { + t.Fatalf("wrong json encoding; got %q, want %q", got, want) + } +}