英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论