Home >Backend Development >Golang >How to Get Sorted JSON Keys When Marshalling in Go?

How to Get Sorted JSON Keys When Marshalling in Go?

Susan Sarandon
Susan SarandonOriginal
2024-12-06 17:17:11716browse

How to Get Sorted JSON Keys When Marshalling in Go?

How to Marshall JSON with Sorted Keys in Go?

Python provides a straightforward method for generating JSON with sorted keys using the sort_keys=True parameter in the json.dumps function. However, finding a similar option in Go may not be immediately apparent.

To achieve sorted JSON key ordering in Go:

The Go json package automatically sorts keys during marshalling. This behavior extends to both maps and structs:

  • Map keys are sorted lexicographically.
  • Struct keys are marshalled in the order defined in the struct.

The underlying implementation can be found in the encoding/json/encode.go file, specifically at the following location:

  • http://golang.org/src/pkg/encoding/json/encode.go?#L359

The above is the detailed content of How to Get 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