Skip to content

Incompatible encoding behavior for the object with MarshalJSON #336

Closed
@denverdino

Description

@denverdino

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions