Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Json in Go

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you how to use Json in Go, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Encode

Encode an object into JSON data, accept an interface {} object, and return [] byte and error:

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

The Marshal function will recursively traverse the entire object and encode the object according to the member type in turn. The rules for type conversion are as follows:

Boolean that converts bool types to JSON

Integer, floating-point number and other numerical types are converted to Number of JSON

String converted from string to JSON (with "" quotation marks)

Struct is converted to Object of JSON, and then recursively packaged according to the type of each member.

Array that converts arrays or slices to JSON

[] byte encodes base64 first and then converts it to JSON string

The Object,key that converts map to JSON must be string

Interface {} converts according to the internal actual type

Nil to null of JSON

Types such as channel,func will return UnsupportedTypeError

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"]}

Decode

Decode JSON data

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

The type conversion rule is similar to the above rule

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, & animals) if err! = nil {fmt.Println ("error:", err)} fmt.Printf ("% + v") Animals) Output: [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]

Structural body

Structures must be members that begin with uppercase letters to be processed by JSON, and members that begin with lowercase letters will not be affected.

In the case of Mashal, when the member variable name of the structure is directly packaged as the key of JSON Object into JSON;Unmashal, it will automatically match the corresponding variable name and be assigned, and it is not case-sensitive.

In Unmarshal, if there are extra fields in the JSON, they will be discarded directly; if the JSON lacks a certain field, it will directly ignore the non-assignment of variables in the structure and will not report an error.

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}

StructTag

If you want to manually configure the correspondence between the members of the structure and the JSON field, you can label the members when defining the structure:

Familiar with using omitempty, if the field is nil or a value of 0 (number 0, string "", empty array [], etc.), the packaged JSON result will not have this field.

Type Message struct {Name string `json: "msg_name" `/ / msg_name Body string `json: "body,omitempty"` / / ignore field Time int64 `json: "-" `/ / ignore field} 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 flexible use of JSON

Use json.RawMessage

Json.RawMessage is actually a redefinition of the [] byte type. You can cast a type.

There is now 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}

With json.RawMessage, the Args field is not parsed during Unmarshal and the byte data is assigned directly to the Args. We can first unpack the JSON data of the first layer, and then determine the specific type of Args for the second Unmarshal according to the value of Cmd.

Note here that the pointer type * json.RawMessage must be used, otherwise it will be considered as [] byte type in Args and will be packaged into a base64-encoded string when packaged.

Use interface {}

When the interface {} type is Unmarshal, JSON is automatically converted to the corresponding data type:

JSON boolean conversion to boolJSON numeric conversion to float64JSON string conversion to stringJSON Array conversion to [] interface {} JSON Object conversion to mapping [string] interface {} JSON null conversion to nil

There are two things to pay attention to. One is that all JSON values are automatically converted to float64 types, which need to be manually converted to required int,int64 and other types when in use. The second is that the object of JSON is automatically converted to map [string] interface {}, and the field name of JSON ``Object is directly used as key for access. When you no longer know the format of JSON data, you can use interface {}.

Custom type

If you want to define how to package and unpack objects, you can implement the following interfaces:

Type Marshaler interface {MarshalJSON () ([] byte, error)} type Unmarshaler interface {UnmarshalJSON ([] byte) error}

Objects that implement this interface need to package and unpack their own data. If the interface is implemented, json will call the custom method when packaging and unpacking, and no other processing will be done on the object.

The above is all the content of the article "how to use Json in Go". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report