Home >Backend Development >Golang >How to Sort JSON Keys in Go: Replicating Python's `sort_keys` Functionality?
In Python, generating JSON with sorted keys is straightforward using the sort_keys argument in the json.dumps() function. However, Go's standard library doesn't seem to provide an equivalent option. How can we achieve similar functionality in Go?
The good news is that the Go encoding/json package handles key ordering internally. Here's how it works:
To produce JSON with sorted keys in Go, you can take advantage of the built-in ordering behavior.
Consider the following JSON object:
{ "name": "John Smith", "age": 30, "city": "New York" }
You can create this object in Go using a map:
import ( "encoding/json" ) type Person struct { Name string Age int City string } func main() { person := Person{ Name: "John Smith", Age: 30, City: "New York", } jsonBytes, _ := json.Marshal(person) jsonStr := string(jsonBytes) // Output sorted JSON println(jsonStr) }
In this example, the map keys are sorted lexicographically, resulting in:
{ "age": 30, "city": "New York", "name": "John Smith" }
The above is the detailed content of How to Sort JSON Keys in Go: Replicating Python's `sort_keys` Functionality?. For more information, please follow other related articles on the PHP Chinese website!