Fix marshal canonicalization
diff --git a/encode.go b/encode.go
index b3b3334..6334c3b 100644
--- a/encode.go
+++ b/encode.go
@@ -7,6 +7,7 @@
import (
"bytes"
"encoding/base64"
+ "encoding/json"
"math"
"reflect"
"runtime"
@@ -159,7 +160,20 @@
if err != nil {
e.error(&MarshalerError{v.Type(), err})
}
- // TODO: canonicalize this json
+
+ // canonicalize the json if it's an object
+ b = bytes.TrimSpace(b)
+ if len(b) > 0 && b[0] == '{' {
+ var temp interface{}
+ err = json.Unmarshal(b, &temp)
+ if err != nil {
+ e.error(&MarshalerError{v.Type(), err})
+ }
+ b, err = Marshal(temp)
+ if err != nil {
+ e.error(&MarshalerError{v.Type(), err})
+ }
+ }
e.Buffer.Write(b)
return
}
diff --git a/encode_test.go b/encode_test.go
index ea2e98f..b020962 100644
--- a/encode_test.go
+++ b/encode_test.go
@@ -4,14 +4,19 @@
"testing"
)
+type marshaling struct{}
+
+func (m marshaling) MarshalJSON() ([]byte, error) { return []byte("\t\n {\"b\":234,\"a\":123}"), nil }
+
func TestCanonicalization(t *testing.T) {
input := struct {
C map[string]interface{} `json:"c"`
A string `json:"a"`
D []int `json:"d"`
B int `json:"b"`
- }{map[string]interface{}{"b": "b", "a": "\n\r", "c": "\"\\<>"}, "a", []int{1, 2, 3}, 1}
- expected := `{"a":"a","b":1,"c":{"a":"` + "\n\r" + `","b":"b","c":"\"\\<>"},"d":[1,2,3]}`
+ E *marshaling `json:"e"`
+ }{map[string]interface{}{"b": "b", "a": "\n\r", "c": "\"\\<>"}, "a", []int{1, 2, 3}, 1, &marshaling{}}
+ expected := `{"a":"a","b":1,"c":{"a":"` + "\n\r" + `","b":"b","c":"\"\\<>"},"d":[1,2,3],"e":{"a":123,"b":234}}`
output, err := Marshal(input)
if err != nil {