json包中的Marshal&Unmarshal 文档译本

Marshal

func Marshal(v interface{})([]byte, error)

  

Marshal returns the JSON encoding of v.

Marshal返回v的JSON编码。

Marshal traverses the value v recursively. If an encountered value implements the Marshaler interface and is not a nil pointer, Marshal calls its MarshalJSON method to produce JSON. If no MarshalJSON method is present but the value implements encoding.TextMarshaler instead, Marshal calls its MarshalText method and encodes the result as a JSON string. The nil pointer exception is not strictly necessary but mimics a similar, necessary exception in the behavior of UnmarshalJSON.

Marshal递归地遍历值v。如果遇到的值实现了Marshaler接口并且不是一个nil指针,Marshal就会调用它的MarshalJSON方法来生成JSON。如果没有MarshalJSON方法,但该值实现了encoding.TextMarshaler,Marshal就会调用它的MarshalText方法,并将结果编码为JSON字符串。严格来说,nil指针异常并不是必要的,而是模仿了UnmarshalJSON行为中类似的必要异常。

 

Otherwise, Marshal uses the following type-dependent default encodings:

否则,Marshal使用以下类型相关的默认编码。

 

Boolean values encode as JSON booleans.

布尔值以JSON布尔值的形式编码。

Floating point, integer, and Number values encode as JSON numbers.

浮点、整数和Number值编码为JSON数字。

 

String values encode as JSON strings coerced to valid UTF-8, replacing invalid bytes with the Unicode replacement rune. So that the JSON will be safe to embed inside HTML <script> tags, the string is encoded using HTMLEscape, which replaces "<", ">", "&", U+2028, and U+2029 are escaped to "\u003c","\u003e", "\u0026", "\u2028", and "\u2029". This replacement can be disabled when using an Encoder, by calling SetEscapeHTML(false).

字符串值编码为JSON字符串并被胁迫为有效的UTF-8,用Unicode替换符替换无效的字节。为了使JSON能够安全地嵌入到HTML <脚本>标签中,字符串应该使用HTMLEscape进行编码,将"<"、">"、"&"、U+2028和U+2029替换为"\u003c"、"\u003e"、"\u0026"、"\u2028 "和"\u2029"。当使用编码器时,可以通过调用SetEscapeHTML(false)来禁止这种替换。

 

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

数组和切片值编码为JSON数组,除了[]byte编码为base64编码的字符串,nil切片编码为空JSON值。

 

Struct values encode as JSON objects. Each exported struct field becomes a member of the object, using the field name as the object key, unless the field is omitted for one of the reasons given below.

Struct值编码为JSON对象。每个导出的结构体字段都会成为JSON对象的成员k:v,使用字段名作为对象的KEY,除非该字段因下面给出的原因之一被省略。

 

The encoding of each struct field can be customized by the format string stored under the "json" key in the struct field's tag. The format string gives the name of the field, possibly followed by a comma-separated list of options. The name may be empty in order to specify options without overriding the default field name.

每个结构体字段的编码可以通过存储在结构体字段(field)标签(tag)中 "json "键下的格式字符串来定制。格式字符串给出了字段的名称,后面可能是一个逗号分隔的选项列表。为了在不覆盖默认字段名的情况下指定选项,名称可以为空。

 

The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

omitempty "选项指定,如果字段的值为空,则应从编码中省略,定义为false、0、nil指针、nil接口值,以及任何空数组、片、映射或字符串。

 

As a special case, if the field tag is "-", the field is always omitted. Note that a field with name "-" can still be generated using the tag "-,".

作为一种特殊情况,如果字段标签是"-",字段总是被省略。请注意,字段的名称在JSON中为"-"的字段标签仍可使用标签"-,"生成,这种带选项的。

 

Examples of struct field tags and their meanings:

结构字段标签的示例及其含义。

// Field appears in JSON as key "myName".  
//字段在JSON中以 "myName "键出现 Field int `json:"myName"` // Field appears in JSON as key "myName" and // the field is omitted from the object if its value is empty, // as defined above.
//字段在JSON中以键 "myName "的形式出现,如果其值为空,则该字段从对象中省略,如上文所定义 Field int `json:"myName,omitempty"` // Field appears in JSON as key "Field" (the default), but // the field is skipped if empty. // Note the leading comma.
//字段在JSON中作为键 "Field"(默认)出现,但如果为空,则跳过该字段。注意前面的逗号 Field int `json:",omitempty"` // Field is ignored by this package.
//这个包忽略了这个字段 Field int `json:"-"` // Field appears in JSON as key "-".
//字段在JSON中以"-"键出现 Field int `json:"-,"`

  

The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types. This extra level of encoding is sometimes used when communicating with JavaScript programs:

"string "选项标志着一个字段以JSON的形式存储在一个JSON编码的字符串中,它只适用于字符串、浮点、整数或布尔类型的字段。它只适用于字符串、浮点、整数或布尔类型的字段。这种额外的编码级别有时在与JavaScript程序通信时使用。

Int64String int64 `json:",string"`

  

The key name will be used if it's a non-empty string consisting of only Unicode letters, digits, and ASCII punctuation except quotation marks, backslash, and comma.

如果键名是一个非空字符串,除了引号、反斜杠和逗号之外,只包含Unicode字母、数字和ASCII标点符号,那么就会被使用。

 

Anonymous struct fields are usually marshaled as if their inner exported fields were fields in the outer struct, subject to the usual Go visibility rules amended as described in the next paragraph. An anonymous struct field with a name given in its JSON tag is treated as having that name, rather than being anonymous. An anonymous struct field of interface type is treated the same as having that type as its name, rather than being anonymous.

匿名结构字段通常被当作其内部导出的字段在外部结构中的字段来进行调集,但要遵守下一段中所描述的通常的Go可见性规则。一个匿名结构体字段如果在它的JSON标签中给出了一个名字,那么它将被视为拥有该名字,而不是匿名。一个接口类型的匿名结构体字段被视为具有该类型的名称,而不是匿名的。

 

The Go visibility rules for struct fields are amended for JSON when deciding which field to marshal or unmarshal. If there are multiple fields at the same level, and that level is the least nested (and would therefore be the nesting level selected by the usual Go rules), the following extra rules apply:

在决定对哪个字段进行整合或取消整合时,对JSON结构字段的Go可见性规则进行了修正。如果同一层次有多个字段,而且该层次是最小的嵌套层次(因此是通常的Go规则所选择的嵌套层次),则适用以下额外规则。

 

1) Of those fields, if any are JSON-tagged, only tagged fields are considered, even if there are multiple untagged fields that would otherwise conflict.

在这些字段中,如果有任何字段是JSON标记的,则只考虑标记的字段,即使有多个未标记的字段,否则会发生冲突

2) If there is exactly one field (tagged or not according to the first rule), that is selected.

如果只有一个字段(无论是否根据第一条规则被标记),该字段被选中。

3) Otherwise there are multiple fields, and all are ignored; no error occurs.

否则有多个字段,都会被忽略,不会出现错误。

Handling of anonymous struct fields is new in Go 1.1. Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of an anonymous struct field in both current and earlier versions, give the field a JSON tag of "-".

匿名结构体字段的处理是 Go 1.1 中的新内容。在 Go 1.1 之前,匿名结构字段是被忽略的。要在当前和早期版本中强制忽略匿名结构字段,请给字段一个JSON标签"-"。

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:

Map值编码为JSON对象。Map的键类型必须是字符串、整数类型或实现 encoding.TextMarshaler。通过应用以下规则对Map键进行排序,并将其作为JSON对象键使用,但须遵守上面为字符串值描述的UTF-8胁迫。

 

- keys of any string type are used directly

- 任何字符串类型的键都可以直接使用

- encoding.TextMarshalers are marshaled
- 编码.TextMarshalers是被调集的。 - integer keys are converted to strings
- 整数键被转换为字符串

  

Pointer values encode as the value pointed to. A nil pointer encodes as the null JSON value.

指针值编码为所指向的值。nil指针编码为空JSON值。

 

Interface values encode as the value contained in the interface. A nil interface value encodes as the null JSON value.

接口值编码为接口中包含的值。无接口值编码为空JSON值。

 

Channel, complex, and function values cannot be encoded in JSON. Attempting to encode such a value causes Marshal to return an UnsupportedTypeError.

通道、复数和函数值不能用JSON编码。试图对这样的值进行编码会导致Marshal返回一个UnsupportedTypeError。

 

JSON cannot represent cyclic data structures and Marshal does not handle them. Passing cyclic structures to Marshal will result in an error.

JSON不能表示循环数据结构,Marshal不能处理它们。将循环结构传递给Marshal会导致错误。

 

 

 

Unmarshal

func Unmarshal(data []byte, v interface{}) error

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

Unmarshal解析JSON编码的数据,并将结果存储在v指向的值中,如果v为nil或不是指针,Unmarshal将返回一个InvalidUnmarshalError。

 

Unmarshal uses the inverse of the encodings that Marshal uses, allocating maps, slices, and pointers as necessary, with the following additional rules:
Unmarshal使用与Marshal使用的编码相反的编码,根据需要分配Map、切片和指针,附加规则如下


To unmarshal JSON into a pointer, Unmarshal first handles the case of the JSON being the JSON literal null. In that case, Unmarshal sets the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into the value pointed at by the pointer. If the pointer is nil, Unmarshal allocates a new value for it to point to.
要将JSON反序列化成一个指针,Unmarshal首先要处理JSON是JSON文字空的情况。在这种情况下,Unmarshal会将指针设置为nil。否则,Unmarshal会将JSON反序列化为指针指向的值。如果指针为nil,Unmarshal为其分配一个新的值

To unmarshal JSON into a value implementing the Unmarshaler interface, Unmarshal calls that value's UnmarshalJSON method, including when the input is a JSON null. Otherwise, if the value implements encoding.TextUnmarshaler and the input is a JSON quoted string, Unmarshal calls that value's UnmarshalText method with the unquoted form of the string.
要将JSON反序列化到一个实现Unmarshaler接口的值中,Unmarshal调用该值的UnmarshalJSON方法,包括当输入是JSON null时。否则,如果值实现了encoding.TextUnmarshaler,并且输入是JSON引号的字符串,Unmarshal就用字符串的未引号形式调用该值的UnmarshalText方法

To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. By default, object keys which don't have a corresponding struct field are ignored (see Decoder.DisallowUnknownFields for an alternative).
为了将JSON反序列化成结构体,Unmarshal将传入的JSON对象键与Marshal使用的键(结构体字段名或它的标签)进行匹配,喜欢完全匹配,但也接受不区分大小写的匹配。默认情况下,没有对应的结构体字段的对象键会被忽略(参见Decoder.DisallowUnknownFields获取替代方案)

 

To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

要将JSON解读成一个接口值,Unmarshal会在接口值中存储其中一个。

 

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

To unmarshal a JSON array into a slice, Unmarshal resets the slice length to zero and then appends each element to the slice. As a special case, to unmarshal an empty JSON array into a slice, Unmarshal replaces the slice with a new empty slice.
要将一个JSON数组反序列化化为一个切片,Unmarshal将切片长度重置为零,然后将每个元素追加到切片中。作为一种特殊情况,如果要将一个空的JSON数组反序列化为一个切片,Unmarshal会用一个新的空切片来替换这个分片

 

To unmarshal a JSON array into a Go array, Unmarshal decodes JSON array elements into corresponding Go array elements. If the Go array is smaller than the JSON array, the additional JSON array elements are discarded. If the JSON array is smaller than the Go array, the additional Go array elements are set to zero values.
要将JSON数组反序列化为Go数组,Unmarshal将JSON数组元素解码为相应的Go数组元素。如果Go数组小于JSON数组,那么额外的JSON数组元素将被丢弃。如果JSON数组小于Go数组,则额外的Go数组元素被设置为零值

 

To unmarshal a JSON object into a map, Unmarshal first establishes a map to use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal reuses the existing map, keeping existing entries. Unmarshal then stores key-value pairs from the JSON object into the map. The map's key type must either be any string type, an integer, implement json.Unmarshaler, or implement encoding.TextUnmarshaler.
要将一个JSON对象反序列化成Map,Unmarshal首先要建立一个要使用的Map。如果Map是nil,Unmarshal会分配一个新的Map。否则,Unmarshal会重新使用现有的Map,保留现有的条目。然后Unmarshal将JSON对象中的键值对存储到map中。Map的键类型必须是任何字符串类型、整数、实现json.Unmarshaler或实现encoding.TextUnmarshaler


If a JSON value is not appropriate for a given target type, or if a JSON number overflows the target type, Unmarshal skips that field and completes the unmarshaling as best it can. If no more serious errors are encountered, Unmarshal returns an UnmarshalTypeError describing the earliest such error. In any case, it's not guaranteed that all the remaining fields following the problematic one will be unmarshaled into the target object.
如果一个JSON值不适合给定的目标类型,或者一个JSON数超出了目标类型,Unmarshal就会跳过该字段,并尽可能地完成反序列化。如果没有遇到更严重的错误,Unmarshal会返回一个UnmarshalTypeError,描述最早的这种错误。在任何情况下,都不能保证在有问题的字段之后的所有剩余字段都会被反序列化到目标对象中


The JSON null value unmarshals into an interface, map, pointer, or slice by setting that Go value to nil. Because null is often used in JSON to mean “not present,” unmarshaling a JSON null into any other Go type has no effect on the value and produces no error.
JSON null值通过将该Go值设置为nil,从而反序列化到接口、映射、指针或切片中。因为在JSON中,null经常被用来表示 "不存在",所以将JSON空值解列到任何其他Go类型中,对该值没有影响,也不会产生错误

When unmarshaling quoted strings, invalid UTF-8 or invalid UTF-16 surrogate pairs are not treated as an error. Instead, they are replaced by the Unicode replacement character U+FFFD.
当反序列化引号字符串时,无效的UTF-8或无效的UTF-16代理对不会被视为错误,而会被U+FFFD替换为Unicode替换字符。相反,它们会被Unicode替换字符U+FFFD取代

 

posted @ 2020-11-16 15:23  菜鸟++  阅读(966)  评论(1编辑  收藏  举报