Teach you how to use Json in Go
Dec 28, 2021 pm 03:44 PMThis article is provided by the golang tutorial column to introduce how to use Json in the Go language. I hope it will be helpful to friends in need!
Encode
Encode an object into JSON
data, accepting an interface{}
Object, returns []byte
and error
:
func Marshal(v interface{}) ([]byte, error)
Marshal
The function will recursively traverse the entire object and evaluate the object by member type in turn. Encoding, the type conversion rules are as follows:
bool
type conversion toJSON
Boolean
Integers, floating point numbers and other numerical types are converted to
JSON
Number
string
Convert to a string ofJSON
(with "" quotes)struct
Convert to aof
JSONObject
, and then recursively pack the-
array or slice into
## based on the type of each member.JSON
’sArray
#[]byte
will be
base64encoded first and then converted to
JSONstring
map
converted to
Objectconverted to
JSON,
keymust be
string- ##interface{}
Convert according to the actual internal type
##nil - Convert to
JSON
##channelnull
, - func
and other types will return
UnsupportedTypeError
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">type ColorGroup struct { ID int Name string Colors []string } group := ColorGroup{ ID: 1, Name: "Reds", Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, } b, err := json.Marshal(group) if err != nil { fmt.Println("error:", err) } os.Stdout.Write(b) Output: {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}</pre><div class="contentsignin">Copy after login</div></div>
Decode JSONdata
func Unmarshal(data []byte, v interface{}) error
Type conversion rules and the above rules Similar to <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">var jsonBlob = []byte(`[
{"Name": "Platypus", "Order": "Monotremata"},
{"Name": "Quoll", "Order": "Dasyuromorphia"}
]`) type Animal struct {
Name string
Order string
} var animals []Animal
err := json.Unmarshal(jsonBlob, &amp;animals) if err != nil {
fmt.Println("error:", err) } fmt.Printf("%+v", animals) Output: [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]</pre><div class="contentsignin">Copy after login</div></div>
The structure must be a member starting with a capital letter to be processed by JSON, Members starting with a lowercase letter have no effect.
Mashal
, the member variable name of the structure will be directly packaged into ## as the
of JSON
Object
#JSON;
Unmashal, the corresponding variable name will be automatically matched for assignment, and is not case-sensitive. When
Unmarshal
, if there are extra fields in
JSON
JSON is missing a field, it will be discarded directly. Ignore not assigning values to variables in the structure and no error will be reported.
type Message struct { Name string Body string Time int64 inner string } var m = Message{ Name: "Alice", Body: "Hello", Time: 1294706395881547000, inner: "ok", } b := []byte(`{"nAmE":"Bob","Food":"Pickle", "inner":"changed"}`) err := json.Unmarshal(b, &m) if err != nil { fmt.Printf(err.Error()) return} fmt.Printf("%v", m) Output: {Bob Hello 1294706395881547000 ok}
StructTagIf you want to manually configure the corresponding relationship between the members of the structure and the JSON field, you can define When labeling the structure, label the members:
Useomitempty to be familiar with, if the field is
nil
JSON result will not have this field.
type Message struct { Name string `json:"msg_name"` // 对应JSON的msg_name Body string `json:"body,omitempty"` // 如果为空置则忽略字段 Time int64 `json:"-"` // 直接忽略字段 } var m = Message{ Name: "Alice", Body: "", Time: 1294706395881547000, } data, err := json.Marshal(m) if err != nil { fmt.Printf(err.Error()) return} fmt.Println(string(data)) Output: {"msg_name":"Alice"}
More flexibility in using
JSON
Use json.RawMessage
json .RawMessage is actually a redefinition of the []byte
type. Casting is possible.Now there is a scenario where the format of one of the fields in the structure is unknown:
type Command struct { ID int Cmd string Args *json.RawMessage }
If
json.RawMessage is used, Args# The ## field will not be parsed when
Unmarshal, and the byte data will be assigned directly to Args
. We can first unpack the JSON
data of the first layer, and then determine the specific type of Args
based on the value of Cmd
for the second time Unmarshal
. It should be noted here that you must use the pointer type
*json.RawMessage
, otherwise the Args
will be considered
Type will be packed into a base64
encoded string when packaging. Using interface{}
interface{}type will automatically Convert JSON to the corresponding data type:
JSON的boolean 转换为boolJSON的数值 转换为float64JSON的字符串 转换为stringJSON的Array 转换为[]interface{}JSON的Object 转换为map[string]interface{}JSON的null 转换为nil
There are two things to note. One is that all JSON
values are automatically converted to the float64
type. When used, they need to be manually converted to the required int
,
and other types. . The second one is object
of JSON
which is automatically converted to map[string]interface{}
type. When accessing, use JSON ``Object## directly. The field name of # is accessed as
key. When you don’t know the format of
JSON data, you can use
interface{}.
自定义类型
如果希望自己定义对象的打包解包方式,可以实现以下的接口:
type Marshaler interface { MarshalJSON() ([]byte, error) } type Unmarshaler interface { UnmarshalJSON([]byte) error }
实现该接口的对象需要将自己的数据打包和解包。如果实现了该接口,json
在打包解包时则会调用自定义的方法,不再对该对象进行其他处理。
The above is the detailed content of Teach you how to use Json in Go. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use reflection to access private fields and methods in golang

Tips for dynamically creating new functions in golang functions

The difference between performance testing and unit testing in Go language

What pitfalls should we pay attention to when designing distributed systems with Golang technology?

Golang technology libraries and tools used in machine learning

The evolution of golang function naming convention

The role of Golang technology in mobile IoT development

Can golang variable parameters be used for function return values?
