SoFunction
Updated on 2025-03-05

Detailed explanation of json processing method in go language

json serialization

goSerialization in languagejsonData usageMethod, code is as follows:

func main() {
  mm := map[string]interface{}{
    "name": "uccs",
    "age":  12,
    "extra": map[string]interface{}{
      "phone": "12345678910",
    },
  }
  bytes, _ := (mm)
  (string(bytes))
}

If it needs to be correctjsonThe data is formatted and output, and can be usedMethod, code is as follows:

  • MarshalIndentThe first parameter is the data to be serialized, the second parameter is the prefix, and the third parameter is the indented character
(mm, "", "  ")

Serialized structure

When serializing the structure, you need to pay attention to the following2point:

  • The fields of the structure must start with capital letters, otherwise it cannot be serialized.
  • Availablejson tagTo specify the serialized field name

json tagHow to use:

  • json:"name"Indicates that the serialized field name isname
  • json:"Phone,omitempty"Indicates that the serialized field name isphone, if the field value is empty, it will not be serialized
  • If it is a field in the form of a pointer
    • If the field value is empty, it will not be serialized, for example, the followingNameThe field will not be serialized because the pointer isnil
    • The field value is an empty string, then serialize, for example, the followingEmailThe field will be serialized because the pointer is notnil
type Person struct {
  Name  *string `json:"name,omitempty"`
  Email *string `json:"email,omitempty"`
}
email := ""
p := Person{
  Email: &email,
}
  • json:"age,string"The number can be turned into a string when serializing
  • json:"-"Ignore this field during serialization

Deserialization

goDeserialization useMethod, pass injsonString and structure pointers, the code is as follows:

func main() {
  j := `{
    "name": "uccs",
    "age": 18,
    "email": "",
    "phone": "2222"
  }`
  var p Person
  _ := ([]byte(j), &p)
  (p)
}

When deserializing, you need to note that there is no difference between passing an empty string and not passing a field, and will be deserialized, such as the aboveEmailFields, passing empty strings and the value obtained without passing fields are all empty

How to distinguish between passing an empty string and not passing a field?

You need to use pointer types when defining structures, such as the followingEmailfield, if an empty string is passed,EmailThe value of a field is an address. If no field is passed,EmailThe value of the field isnil

type Person struct {
  Name  string  `json:"name"`
  Age   int     `json:"age"`
  Email *string `json:"email"`
  Phone string  `json:"phone"`
}
j := `{
  "name": "uccs",
  "age": 18,
  "phone": "2222"
}`
k := `{
  "name": "uccs",
  "age": 18,
  "email": "",
  "phone": "2222"
}`
var p1 Person
var p2 Person
_ := ([]byte(j), &p1)
_ := ([]byte(k), &p2)
(p1)  // {uccs 18 <nil> 2222}
(p2)  // {uccs 18 0xc000014140 2222}

So we can judgeEmailIs the field anilTo distinguish between passing empty strings and no passing fields

( == nil)  // Whether the email is nil determines whether the Email field has been passed

encoder

encoderIt's aWriterInterface, can be used to write files

Compared with(string(bytes))Way,encoderThe structure can be written directly to the file and written in a stream

func main() {
  p := Person{
    Name: "xiaoming",
    Age:  543251,
  }
  file, _ := ("")
  defer ()
  encoder := (file)
  (true) // Escape special characters in json  (p)
}

decoder

decoderIt's aReaderInterface, can be used to read files

decoderyesencoderThe reverse operation can be read from the filejsonData and deserialize

func main() {
  file, _ := ("")
  defer ()
  decoder := (file)
  p := Person{}
  (&p)
  (p)
}

This is the end of this article about the detailed explanation of JSON processing methods in Go. For more related content on JSON processing methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!