Closed
Description
If the result byte array of MarshalJSON has some special char, e.g. \n or char need escape, the jsoniter Encode() will have incompatible behavior to impl of "encoding/json"
A simple test case is as following
package test
import (
"bytes"
"encoding/json"
"github.com/json-iterator/go"
"testing"
)
type Foo struct {
Bar interface{}
}
func (f Foo) MarshalJSON() ([]byte, error) {
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(f.Bar)
return buf.Bytes(), err
}
// Standard Encoder has trailing newline.
func TestEncode(t *testing.T) {
foo := Foo {
Bar: 123,
}
var buf, stdbuf bytes.Buffer
enc := jsoniter.ConfigCompatibleWithStandardLibrary.NewEncoder(&buf)
enc.Encode(foo)
stdenc := json.NewEncoder(&stdbuf)
stdenc.Encode(foo)
t.Logf("%q", string(buf.Bytes()))
t.Logf("%q", string(stdbuf.Bytes()))
}
In Kubernetes project, there are several PRs are blocking on that. E.g. kubernetes/kubernetes#70574
E.g. in kubernetes/staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go, its impl of MarshalJSON() will trigger this problem
// MarshalJSON ensures that the unstructured object produces proper
// JSON when passed to Go's standard JSON library.
func (u *Unstructured) MarshalJSON() ([]byte, error) {
var buf bytes.Buffer
err := UnstructuredJSONScheme.Encode(u, &buf)
return buf.Bytes(), err
}
Metadata
Metadata
Assignees
Labels
No labels