make OnlineStat marshal nicely to json
This commit is contained in:
parent
c782f99f05
commit
3e9c1a9df6
20
ostat.go
20
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)
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user