Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jsoniter.Marshal makes ordered maps unordered #676

Open
xiaozhiliaoo opened this issue Jun 7, 2023 · 2 comments
Open

jsoniter.Marshal makes ordered maps unordered #676

xiaozhiliaoo opened this issue Jun 7, 2023 · 2 comments

Comments

@xiaozhiliaoo
Copy link

xiaozhiliaoo commented Jun 7, 2023

func Test_jsoniterMarshal(t *testing.T) {
	m := map[string]int{"c": 3, "a": 1, "b": 2}
	keys := make([]string, 0, len(m))
	for key := range m {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	fmt.Println(m) // map[a:1 b:2 c:3]
	marshal, _ := jsoniter.Marshal(m) // jsoniter "github.com/json-iterator/go" package
	fmt.Println(string(marshal)) // {"c":3,"a":1,"b":2}
}

the map is ordered by sort. but jsoniter.Marshal make the map unordered. but json.Marshal json.Marshal

func Test_jsonMarshal(t *testing.T) {
	m := map[string]int{"c": 3, "a": 1, "b": 2}
	keys := make([]string, 0, len(m))
	for key := range m {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	marshal, _ := json.Marshal(m) // "encoding/json" package
	fmt.Println(string(marshal)) //{"a":1,"b":2,"c":3}
}
@JusticeN
Copy link

You try to marshal an umsorted map m. The result is also unsorted which is ok.
May be you need to sort m first before marshalling.

...

sort.Strings(keys)
sort.Strings(m)
// marshal m
// and then do the check/ print
...

@CodyDWJones
Copy link

the map is ordered by sort

This was a surprise to me, but you are right: the built-in encoding/json package documentation says:

"Map values encode as JSON objects... The map keys are sorted and used as JSON object keys..."

May be you need to sort m first before marshalling.

You can't sort a map in Go. Maps have no guaranteed order. The only way to do it is to copy the key-value pairs into some other data structure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants