序列化的内容是否严格遵循在使用 encoding/json 包中定义的顺序?

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

Does serialized content strictly follow the order in definition use encoding/json package?

问题

我使用encoding/json来序列化结构体。我对json.Marshal函数的输出结果感到困惑。序列化后的字段内容是否严格按照结构体定义的顺序进行排列?

例如,这是一个结构体定义:

type MyStruct struct {
    Field1  string
    Field2  string
}

输出结果是否可能是{"Field2":"field2","Field1":"field1"}?因为如果输出的结构体字段顺序不一致,序列化内容的哈希值将是不确定的。

英文:

I use encoding/jsonto serialize struct. I'm confused about the output of json.Marshal function. Does the serialized field content strictly follow the order in the struct definition?

e.g. Here is a struct definition

type MyStruct struct {
    Field1  string
    Field2  string
}

could the output be {"Field2":"field2","Field1":"field1"}? Since if the output struct fields out of order, the hash of the serialized content will be uncertain.

答案1

得分: 6

当前的实现是确定性的,例如对于结构体,请参阅https://golang.org/src/encoding/json/encode.go#L629,它给出了结构体的顺序(而映射是按排序键排序的)。

但是,由于文档没有保证这一点,您应该将其视为实现细节。

如果您想对输出进行哈希处理,您将面临更多问题,例如字符串中有几种等效表示,并且JSON没有整数的概念(仅有浮点数)。这真的取决于您尝试使用哈希做什么。

英文:

The current implementation is deterministic, e.g. for structs see https://golang.org/src/encoding/json/encode.go#L629 which gives struct order (and maps are by sorted keys).

But as this is not guaranteed by the documentation you should consider this an implementation detail.

If you want to hash the output you'll face more problems, e.g. there are several equivalent representations of characters in strings and JSON has no notion of an int (floats only). It really depends on what you try to do wirh that hash.

答案2

得分: 4

序列化字段的内容是否严格遵循结构定义中的顺序?

不是的。没有这个保证。实际上,虽然对于许多数据类型(如结构体)可能是正确的,但对于映射类型来说肯定不是正确的。在这种情况下,永远不应该依赖于顺序保持不变,因为实现细节可能会在不同的Go版本或甚至Go编译器之间发生变化。如果在这种情况下假设一致的顺序,可能会引入错误。

如果对于你的特定数据类型而言顺序很重要,你可以实现一个自定义的json.Marshaler,以保持顺序。

英文:

> Does the serialized field content strictly follow the order in the struct definition?

No. There is no guarantee of this. In practice, while it may be true for many data types, such as structs, it will certainly not be true for maps, and one should never depend on the order remaining the same, as implementation details can change between Go versions or even Go compilers, and if you assume consistent ordering in such cases, you could introduce bugs.

If ordering is important for your specific data types, you can implement a custom json.Marshaler that preserves order.

huangapple
  • 本文由 发表于 2017年6月26日 15:47:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/44755089.html
匿名

发表评论

匿名网友

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

确定