Home > Backend Development > Golang > How Can I Sort JSON Keys When Encoding JSON in Go?

How Can I Sort JSON Keys When Encoding JSON in Go?

DDD
Release: 2024-12-21 08:21:10
Original
137 people have browsed it

How Can I Sort JSON Keys When Encoding JSON in Go?

Sorting JSON Keys in Go

The Python json package provides a sort_keys option to produce JSON with keys in a sorted order. This article explores how to achieve similar functionality in Go's encoding/json package.

Solution

In Go, the json package automatically sorts the keys of:

  • Maps: Keys are sorted lexicographically
  • Structs: Keys are marshalled in the order defined within the struct

Implementation Details

The implementation of key sorting can be found in the encode.go file within the encoding/json package:

func (enc *encodeState) encodeMap(v reflect.Value) {
    m := v.Interface().(map[string]interface{})
    if enc.indent {
        enc.write(`{` + enc.indentPrefix)
    } else {
        enc.write(`{`)
    }
    enc.mapStarted = true
    keys := make([]string, 0, len(m))
    for k := range m {
        keys = append(keys, k)
    }
    sort.Strings(keys)
    for i, k := range keys {
        enc.encodeValue(reflect.ValueOf(k))
        enc.write(`:`)
        enc.encodeValue(reflect.ValueOf(m[k]))
        if i < len(m)-1 {
            enc.write(`,`)
        }
    }
    enc.write(`}`)
    enc.mapStarted = false
}
Copy after login

This implementation ensures that map keys are sorted lexicographically, and struct keys are sorted based on their order within the struct definition.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template