mirror of
https://github.com/shopspring/decimal.git
synced 2024-11-22 20:40:48 +01:00
allow optional marshalling JSON without quotes
This commit is contained in:
parent
96e19b482b
commit
d6f52241f3
2 changed files with 25 additions and 1 deletions
15
decimal.go
15
decimal.go
|
@ -43,6 +43,14 @@ import (
|
||||||
//
|
//
|
||||||
var DivisionPrecision = 16
|
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.
|
// Zero constant, to make computations faster.
|
||||||
var Zero = New(0, 1)
|
var Zero = New(0, 1)
|
||||||
|
|
||||||
|
@ -476,7 +484,12 @@ func (d *Decimal) UnmarshalJSON(decimalBytes []byte) error {
|
||||||
|
|
||||||
// MarshalJSON implements the json.Marshaler interface.
|
// MarshalJSON implements the json.Marshaler interface.
|
||||||
func (d Decimal) MarshalJSON() ([]byte, error) {
|
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
|
return []byte(str), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -206,6 +206,7 @@ func TestJSON(t *testing.T) {
|
||||||
Amount Decimal `json:"amount"`
|
Amount Decimal `json:"amount"`
|
||||||
}
|
}
|
||||||
docStr := `{"amount":"` + s + `"}`
|
docStr := `{"amount":"` + s + `"}`
|
||||||
|
docStrNumber := `{"amount":` + s + `}`
|
||||||
err := json.Unmarshal([]byte(docStr), &doc)
|
err := json.Unmarshal([]byte(docStr), &doc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("error unmarshaling %s: %v", docStr, err)
|
t.Errorf("error unmarshaling %s: %v", docStr, err)
|
||||||
|
@ -221,6 +222,16 @@ func TestJSON(t *testing.T) {
|
||||||
} else if string(out) != docStr {
|
} else if string(out) != docStr {
|
||||||
t.Errorf("expected %s, got %s", docStr, string(out))
|
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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue