encoding/json的Marshal函数默认按字母顺序对JSON进行编码吗?

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

Is encoding/json Marshal a JSON alphabetically by default?

问题

func sort(input string) string {
var data interface{}
_ = json.Unmarshal([]byte(input), &data)
ret, _ := json.Marshal(data)
return string(ret)
}

就像上面的代码一样,如果我将一个json字符串解析为接口,然后将其编组为json字符串,这个json ret默认按字母顺序排序吗?

似乎encoding/json Marshal默认会按字母顺序排序键,但是否有任何文档或文章证明了这一点?

谢谢

英文:
func sort(input string) string {
    var data interface{}
    _ = json.Unmarshal([]byte(input), &data)
    ret, _ := json.Marshal(data)
    return string(ret)
}

just like code above, if i Unmarshal a json string into interface, then Marshal it to json string, is this json ret sort by alphabetically default?

seems like encoding/json Marshal will sort keys by alphabetically default, but is there any doc or article prove this?

thanks

答案1

得分: 1

根据函数文档:

映射值被编码为JSON对象。映射的键类型必须是字符串、整数类型或实现encoding.TextMarshaler接口。映射键会按照以下规则进行排序,并作为JSON对象的键使用,同时遵循上述字符串值的UTF-8强制转换的描述:

  • 任何字符串类型的键直接使用
  • encoding.TextMarshaler会被编组
  • 整数键会被转换为字符串
英文:

According to the functions documentation:

Map values encode as JSON objects. The map's key type must either be a string, an integer type, or implement encoding.TextMarshaler. The map keys are sorted and used as JSON object keys by applying the following rules, subject to the UTF-8 coercion described for string values above:

  • keys of any string type are used directly
  • encoding.TextMarshalers are marshaled
  • integer keys are converted to strings

huangapple
  • 本文由 发表于 2022年8月3日 18:53:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/73220510.html
匿名

发表评论

匿名网友

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

确定