From d6f52241f332c63811249bd79a522406bea1a7c9 Mon Sep 17 00:00:00 2001 From: Vadim Graboys Date: Sun, 18 Sep 2016 13:52:01 -0700 Subject: [PATCH] allow optional marshalling JSON without quotes --- decimal.go | 15 ++++++++++++++- decimal_test.go | 11 +++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/decimal.go b/decimal.go index e3d8196..91f9f6c 100644 --- a/decimal.go +++ b/decimal.go @@ -43,6 +43,14 @@ import ( // var DivisionPrecision = 16 +// Set this to true if you want the decimal to be JSON marshaled as a number, +// instead of as a string. +// WARNING: this is dangerous for decimals with many digits, since many JSON +// unmarshallers (ex: Javascript's) will unmarshal JSON numbers to IEEE 754 +// double-precision floating point numbers, which means you can potentially +// silently lose precision. +var MarshalJSONWithoutQuotes = false + // Zero constant, to make computations faster. var Zero = New(0, 1) @@ -476,7 +484,12 @@ func (d *Decimal) UnmarshalJSON(decimalBytes []byte) error { // MarshalJSON implements the json.Marshaler interface. func (d Decimal) MarshalJSON() ([]byte, error) { - str := "\"" + d.String() + "\"" + var str string + if MarshalJSONWithoutQuotes { + str = d.String() + } else { + str = "\"" + d.String() + "\"" + } return []byte(str), nil } diff --git a/decimal_test.go b/decimal_test.go index 58c26f1..b0b2088 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -206,6 +206,7 @@ func TestJSON(t *testing.T) { Amount Decimal `json:"amount"` } docStr := `{"amount":"` + s + `"}` + docStrNumber := `{"amount":` + s + `}` err := json.Unmarshal([]byte(docStr), &doc) if err != nil { t.Errorf("error unmarshaling %s: %v", docStr, err) @@ -221,6 +222,16 @@ func TestJSON(t *testing.T) { } else if string(out) != docStr { t.Errorf("expected %s, got %s", docStr, string(out)) } + + // make sure unquoted marshalling works too + MarshalJSONWithoutQuotes = true + out, err = json.Marshal(&doc) + if err != nil { + t.Errorf("error marshaling %+v: %v", doc, err) + } else if string(out) != docStrNumber { + t.Errorf("expected %s, got %s", docStrNumber, string(out)) + } + MarshalJSONWithoutQuotes = false } }