Home >Backend Development >Golang >How Can I Achieve Sorted JSON Keys When Marshalling in Go?

How Can I Achieve Sorted JSON Keys When Marshalling in Go?

DDD
DDDOriginal
2024-12-09 09:54:08802browse

How Can I Achieve Sorted JSON Keys When Marshalling in Go?

JSON Marshalling in Go with Sorted Keys

In Python, producing JSON with keys in sorted order is as simple as setting the sort_keys parameter to True. But what about Go? This question explores options for achieving similar behavior in Golang.

Go's Key Ordering Approach

Unlike Python, Go's JSON package inherently orders keys during marshalling. The specific ordering rules are as follows:

  • Keys in maps are sorted lexicographically.
  • Keys in structs are marshalled in the order they are defined in the struct.

This automatic key ordering means that developers do not need to explicitly specify a sort_keys parameter as in Python. The order of the keys is determined by Go's internal sorting algorithms.

Under the Hood

The implementation of key ordering can be found in encoding/json/encode.go, specifically from line 359 onward. Here, the encoder iterates over the keys of the map or struct and sorts them before serializing the JSON.

Example

Consider the following Go code:

package main

import "encoding/json"

type MyStruct struct {
    Field1 string
    Field2 int
}

func main() {
    data := map[string]int{"apple": 1, "banana": 3, "cherry": 2}
    jsonData, _ := json.Marshal(data)

    fmt.Println(string(jsonData))
}

The output of this code will be:

{
    "apple": 1,
    "banana": 3,
    "cherry": 2
}

As you can see, the keys are automatically sorted lexicographically, without any additional configuration.

The above is the detailed content of How Can I Achieve Sorted JSON Keys When Marshalling in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn