SoFunction
Updated on 2025-03-04

How to use JSON in Go

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 its member type in turn. The type conversion rules are as follows:

bool type Boolean converted to JSON
Number of integers, floating point numbers, etc. Convert to JSON
string converted to JSON string (with ""quotes)
Convert struct to JSON Object, and then recursively package according to the type of each member
Array or slice Convert to JSON
[]byte will first base64 encoding and then convert it to a JSON string
Convert map to JSON Object, key must be string
interface{} converts according to the internal actual type
nil to JSON null
Channel, func and other types 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 := (group) 
if err != nil { 
 ("error:", err) 
} 
(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 rules are similar to the above rules

var jsonBlob = []byte(`[ 
 {"Name": "Platypus", "Order": "Monotremata"}, 
 {"Name": "Quoll", "Order": "Dasyuromorphia"} 
]`) 
type Animal struct { 
 Name string 
 Order string 
} 
var animals []Animal 
err := (jsonBlob, &animals) 
if err != nil { 
 ("error:", err) 
} 
("%+v", animals) 
Output: 
[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]

Structure

The structure must be a member starting with uppercase letters before it will be processed by JSON, and members starting with lowercase letters will not be affected.

When Mashal, the member variable name of the structure will be packaged directly as the key of the JSON Object into JSON; when Unmashal, the corresponding variable name will be automatically matched for assignment, and the upper and lower and lower and lower variable names will be insensitive.

When Unmarshal, if there are extra fields in JSON, it will be discarded directly; if JSON lacks a field, it will directly ignore the 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 := (b, &m) 
if err != nil { 
 (()) 
 return 
} 
("%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 tag the members when defining the structure:

Use omitempty to be familiar with, if the field is nil or 0 value (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 corresponding to JSON Body string `json:"body,omitempty"` // If empty, ignore the field Time int64 `json:"-"`    // Ignore fields directly} 
var m = Message{ 
 Name: "Alice", 
 Body: "", 
 Time: 1294706395881547000, 
} 
data, err := (m) 
if err != nil { 
 (()) 
 return 
} 
(string(data)) 
Output: 
{"msg_name":"Alice"} 

More flexible use of JSON

use

In fact, it is a redefinition of the []byte type. Cases can be performed.

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 * 
}

If used, the Args field will not be parsed in Unmarshal, and the byte data will be assigned to Args directly. We may first unpack the JSON data of the first layer, and then determine the specific type of Args to perform the second Unmarshal based on the value of Cmd.

It should be noted here that you must use pointer type*, otherwise Args will be considered as []byte type and will be packaged into a base64-encoded string when packaged.

Using interface{}

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

JSONofboolean Convert tobool
JSONof数值 Convert tofloat64
JSONof字符串 Convert tostring
JSONofArray Convert to[]interface{}
JSONofObject Convert tomap[string]interface{}

JSON's null conversion to nil

There are two things to note. One is that all JSON values ​​are automatically converted to float64 type, and when used, they need to be manually converted to required int, int64 and other types. The second is that JSON object is automatically converted to map[string]interface{} type. When accessing, it is directly used as the key to access the field name of JSON Object. If you don't know the format of JSON data, you can use interface{}.

Custom Type

If you want to define the packaging and unpacking method of the object yourself, you can implement the following interface:

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

The objects that implement this interface need to package and unpack their own data. If this interface is implemented, json will call a custom method when packaging and unpacking, and no longer perform other processing on the object.

Summarize

The above is the method of using JSON in Go language introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!