How to produce JSON with sorted keys in Go?

huangapple go评论88阅读模式
英文:

How to produce JSON with sorted keys in Go?

问题

在Python中,你可以通过以下方式按排序顺序生成带有键的JSON:

import json
print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4, separators=(',', ': ')))

在Go语言中,我还没有找到类似的选项。你有什么想法如何在Go中实现类似的行为?

英文:

In python you can produce JSON with keys in sorted order by doing

import json
print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4, separators=(',', ': '))

I have not found a similar option in Go. Any ideas how I can achieve similar behavior in go?

答案1

得分: 89

json包在进行编组时总是对键进行排序。具体来说:

  • 映射的键按字典顺序排序

  • 结构体的键按照结构体定义的顺序进行编组

实现代码可以在以下链接找到:

英文:

The json package always orders keys when marshalling. Specifically:

  • Maps have their keys sorted lexicographically

  • Structs keys are marshalled in the order defined in the struct

The implementation lives here ATM:

答案2

得分: 12

Gustavo Niemeyer给出了很好的答案,这是我使用的一个小巧的代码片段,用于在需要时验证和重新排序/规范化json的[]byte表示。

func JSONRemarshal(bytes []byte) ([]byte, error) {
	var ifce interface{}
	err := json.Unmarshal(bytes, &ifce)
	if err != nil {
		return nil, err
	}
	return json.Marshal(ifce)
}
英文:

Gustavo Niemeyer gave great answer, just a small handy snippet I use to validate and reorder/normalize []byte representation of json when required

func JSONRemarshal(bytes []byte) ([]byte, error) {
	var ifce interface{}
	err := json.Unmarshal(bytes, &ifce)
	if err != nil {
		return nil, err
	}
	return json.Marshal(ifce)
}

huangapple
  • 本文由 发表于 2013年9月7日 09:02:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/18668652.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定