Skip to content

How to keep order of keys when convert map[string]interface{} to json ? #2536

@kkqy

Description

@kkqy

1. What version of Go and system type/arch are you using?

go version go1.20.2 windows/amd64

2. What version of GoFrame are you using?

v2.3.3

3. Can this issue be re-produced with the latest release?

yes

4. What did you do?

package main

import (
	"context"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
)

func main() {
	amap := map[string]string{}
	gjson.DecodeTo("{\"b\":\"b\",\"a\":\"a\"}", &amap)
	g.Log().Info(context.Background(), amap)
	result, _ := gjson.EncodeString(amap)
	g.Log().Info(context.Background(), result)
}

INPUT is:
{"b":"b","a":"a"}
OUTPUT is:
{"a":"a","b":"b"}

5. What did you expect to see?

Keep the order of keys as that in map.

package main

import (
	"context"

	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
)

func main() {
	amap := map[string]string{
		"c": "c",
		"b": "b",
	}
	amap["a"] = "a"
	g.Log().Info(context.Background(), amap)
	result, _ := gjson.EncodeString(amap)
	g.Log().Info(context.Background(), result)
}

I want get {"c":"c","b":"b","a":"a"} instead of {"a":"a","b":"b","c":"c"}.

6. What did you see instead?

Keys are order by alphabet.

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