Preface
The JSON Tag logo of the structure in GoLang (English name backquote or backtick, part of the backtick symbol wrapped) has not been clearly viewed in the complete specifications and instructions for use. There is an ambiguity, and the system is organized as follows:
- The complete syntax of JSON Tag tags, what options are included
- The functions and scope of use of different options (output name /-/omitempty/string)
- Special precautions supplement
Summary of Tag usage in Json
- The JSON Tag tag format is:
json:"FieldName/-/optional, omitempty/optional, string/optional
- Use between multiple options, comma split
- FieldName option: Specify the coded key name
- Can be empty, then use the corresponding field name of Struct as the JSON output name
- FieldName is not empty, then the specified FieldName is used as the JSON output name.
- - Symbol, this field is ignored when output; but be aware that when -, (one more comma ending), the output JSON field with the field named - is not ignored.
- omitempty option: ignore empty values
- Include this option, the field null value (zero value + null value: false, 0, nil pointer, nil interface value, and any empty array, slice, map or string) will not be output.
- string option: The result output is a string
- The field result output is a string
- Applicable only to fields of string, floating point, integer or boolean type
- This extra encoding is sometimes used when communicating with JavaScript programs
- Note that if the field value itself is string, adding JSON's string label option again will lead to multiple quotes
// Sample code: /play/p/ApzFQttV_MBpackage main import ( "encoding/json" "fmt" "os" ) func main() { type ColorGroup struct { Hello bool `json:"Hello,string"` world bool `json:"World,string"` ID int `json:"id,string"` Name string `json:"name,string"` Colors []string `json:"ColorName,omitempty"` Colors1 []string `json:"ColorName1"` Colors2 []string `json:"ColorName2"` } group := ColorGroup{ Hello: true, world: true, ID: 1, Name: "Reds", Colors: []string{"hello", "world"}, Colors1: nil, Colors2: []string{}, } b, err := (group) if err != nil { ("error:", err) } (b) } // Output result//{"Hello":"true","id":"1","name":"\"Reds\"","ColorName":["hello","world"],"ColorName1":null,"ColorName2":[]}
Other notes:
- nil type values such as nil pointer, nil interface, nil slice, etc. are encoded as null JSON objects
- Empty slices, empty arrays are encoded as [] JSON array
- map encoded as {} JSON object
- The pointer type value is encoded as the value pointed to by the pointer, and the interface type value is encoded as the value of the corresponding type.
Official Marshal function description
func Marshal(v interface{}) ([]byte, error)
Marshal returns the JSON encoding result of variable v
The Marshal function recursively processes variable v; if a value implements the Marshaler interface and is not a nil pointer, Marshal calls its MarshalJSON method to generate JSON data. If there is no MarshalJSON method but the method is implemented, Marshal calls the MarshalText method and encodes the result as a JSON string. The nil pointer exception is not a strictly necessary one, but rather imitates a similar, required exception in UnmarshalJSON behavior.
Otherwise, Marshal uses the following default encoding related to the type:
- Boolean value is encoded as JSON boolean value
- Floating point, integer and numeric type values are encoded as JSON numbers
- The string value is encoded as a JSON string, forced to be a valid UTF-8, and invalid bytes are replaced with Unicode. To enable JSON to be safely embedded into HTML <script> tags, strings are encoded using HTMLEscape, escaped "<", ">", "&", "U+2028" and "U+2029" as "\u003c", "\u003e", "\u0026", "\u2028", and "\u2029". When using the encoder, this replacement can be disabled by calling SetEscapeHTML(false).
- The values of the array and shard will be encoded as JSON arrays, but []byte will be encoded as base64-encoded strings, and nil slices will be encoded as null JSON object values.
- Arrays, shards, encoded as JSON arrays
- []byte empty slice, encoded as an empty array []
- nil slice, encoded as null
- The value of the structure type is encoded as a JSON object. Each exported structure field will become a member of the object, using the field name as the object's key unless the field is omitted for the following reasons.
- The encoding of each structure field can be customized by the format string stored under the "json" key of the structure field Tag tag. The format string gives the name of the field, followed by a comma-separated list of options. The name can be empty so that the option is specified without overwriting the default field name
- "omitempty" option, if the field is empty, should be omitted from the encoding, defined as false, 0, nil pointer, nil interface value, and any empty array, slice, map or string
- As a special case, if the field label is "-", the field is always omitted. Note that a field with the name "-" can still be generated using the tag "-,"
Description of the formatted string corresponding to the json key under the structure field Tag tag:
- Given the field encoded name, followed by a comma-segmented list of options
- Field names can be empty and are used to specify different options without overwriting the default field names.
- omitempty option, if the field is empty (false/0/nil pointer/nil interface value/empty array/empty slice/empty map/empty string), the encoding output will be skipped
- When the field label is -, this field is always ignored; but be aware that a field named - can still be generated when it appears in the - label.
Some examples of structure field labels and corresponding meanings:
// Field appears in JSON as key "myName". // When this field appears in JSON, it is named "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. // When this field appears in JSON, it is named "myName". If it is a zero value, this field will be ignored when outputtingField int `json:"myName,omitempty"` // Field appears in JSON as key "Field" (the default), but // the field is skipped if empty. // Note the leading comma. // When this field appears in JSON, it is named "Field". If it is a zero value, this field will be ignored when outputtingField int `json:",omitempty"` // Field is ignored by this package. // Ignore this field when the current package outputs JSONField int `json:"-"` // Field appears in JSON as key "-". // When this field appears in JSON, it is named "-"Field int `json:"-,"`
The "string" option indicates that the field is stored in JSON-encoded strings in JSON format. It only works with fields of string, floating point, integer, or boolean type. This additional encoding is sometimes used when communicating with JavaScript programs.
Int64String int64 `json:",string"`
Key names will be used when they meet the following conditions: non-empty strings, consisting only of Unicode letters, numbers, and ASCII punctuation marks (excluding quotes, backslashes, and commas).
Limited by the Go visibility rules described below, anonymous structure fields can generally be encoded, and the internally derived fields are equivalent to fields in the external structure. Anonymous structure fields use names given in their JSON Tag tags, rather than anonymous. Anonymous structure fields of an interface type are handled in the same way as taking that type as its name, and are not anonymous.
When deciding which field to marshal or unmarshal is used, the structure field visibility rules in Go are adjusted. If there are multiple fields at the same level and the level is the least nested (and will be the nested level selected by the usual Go rules), the following additional rules apply:
1) In these fields, if any of the fields are JSON Tag tags, only the marked fields are considered, even if there are multiple unmarked fields, otherwise conflicts will occur.
2) If there is only one field (marked or not marked according to the first rule), the field is selected.
3) Otherwise, multiple fields will be ignored; no error will occur.
New processing of anonymous structure fields has been added in Go 1.1. Prior to Go 1.1, the anonymous structure field was ignored. To force ignore anonymous structure fields in current and earlier versions, give the field a "-" JSON tag.
The value of the Map is encoded as a JSON object. The key type of the map must be a string, an integer type, or an interface must be implemented. The following rules are applied to sort the keys of the Map and used as keys for JSON objects, but obey the UTF-8 mandatory rules described above for string values.
- Any string type key can be used directly
- Will be encoded
- Integer keys are converted to strings
The pointer type value is encoded as the value pointed to, and a nil pointer is encoded as a null JSON value.
The interface type value is encoded as the value contained in the interface, and a nil interface value is encoded as a null JSON value.
Channels, complex types, and function values cannot be JSON encoding. Trying to encode such values will cause Marshal to return an UnsupportedTypeError error.
JSON cannot represent loop nested data structures, and Marshal functions will not process them. Passing a loop structure to Marshal will result in an error.
refer to
- encoding/json#Marshal
- The use of struct json tag and in-depth understanding
Summarize
This is all about this article about the usage of Json Tag in GoLang. For more related content on the usage of Json Tag in GoLang, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!