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

how to Preserving key order by json parse ? #129

Open
leeonsoft opened this issue Nov 26, 2022 · 1 comment
Open

how to Preserving key order by json parse ? #129

leeonsoft opened this issue Nov 26, 2022 · 1 comment

Comments

@leeonsoft
Copy link

package main

import (
"fmt"
"github.com/Jeffail/gabs"
)

func main() {
jsonStr := {"b":"dddd","a":"111"}
d, _ := gabs.ParseJSON([]byte(jsonStr))
fmt.Println(d.String())
}
// output {"a":"111","b":"dddd"} how to get result : {"b":"dddd","a":"111"} ???

@mihaitodor
Copy link
Contributor

Key order is undefined in JSON and, because Go uses maps to hold JSON objects, the order will not be preserved. Details here: golang/go#27179. When marshalling to string, the keys will be sorted lexicographically:

Map values encode as JSON objects. The map's key type must either be a string, an integer type, or implement encoding.TextMarshaler. The map keys are sorted and used as JSON object keys by applying the following rules, subject to the UTF-8 coercion described for string values above:

keys of any string type are used directly
encoding.TextMarshalers are marshaled
integer keys are converted to strings

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

2 participants