go icon indicating copy to clipboard operation
go copied to clipboard

MarshalIndent not work properly when value is map

Open jeschou opened this issue 4 years ago • 0 comments

environ os: Mac OSX Big Sur 11.3.1 go version go1.14.15 darwin/amd64 jsoniter version github.com/json-iterator/go v1.1.12

test case

package json_test

import (
	"encoding/json"
	"fmt"
	jsoniter "github.com/json-iterator/go"
	"testing"
)

type M = map[string]interface{}

var testMapData = M{
	"a": "",
	"b": "",
	"c": M{
		"c1": "",
		"c2": "",
		"c3": M{
			"d": "",
			"e": "",
			"f": M{
				"h": "",
				"i": "",
			},
		},
	},
}

type testStruct struct {
	A string `json:"a"`
	B string `json:"b"`
	C struct {
		C1 string `json:"c1"`
		C2 string `json:"c2"`
		C3 struct {
			D string `json:"d"`
			E string `json:"e"`
			F struct {
				H string `json:"h"`
				I string `json:"i"`
			} `json:"f"`
		} `json:"c3"`
	} `json:"c"`
}

var jsonIter = jsoniter.ConfigCompatibleWithStandardLibrary

func TestMarshalIndentMap(t *testing.T) {
	bs1, _ := jsonIter.MarshalIndent(testMapData, "", "  ")
	str1 := string(bs1)
	fmt.Println(str1)
	fmt.Println("------")
	bs2, _ := json.MarshalIndent(testMapData, "", "  ")
	str2 := string(bs2)
	fmt.Println(str1)
	fmt.Println("------")
	if str1 != str2 {
		t.Fatal()
	}
}

func TestMarshalIndentStruct(t *testing.T) {
	bs1, _ := jsonIter.MarshalIndent(testStruct{}, "", "  ")
	str1 := string(bs1)
	fmt.Println(str1)
	fmt.Println("------")
	bs2, _ := json.MarshalIndent(testStruct{}, "", "  ")
	str2 := string(bs2)
	fmt.Println(str1)
	fmt.Println("------")
	if str1 != str2 {
		t.Fatal()
	}
}

explain in this case, the logical structure of testMapData and testStruct are identical,

but jsonIter.MarshalIndent(testMapData, "", " ") broken jsonIter.MarshalIndent(testStruct{}, "", " ") works fine

golang builtin json works fine.

jeschou avatar Sep 24 '21 04:09 jeschou