SoFunction
Updated on 2025-03-05

Detailed explanation of the conversion between structures and JSON in Go language

Preface

In daily development, we often putJSONAnalyze into the corresponding structure, otherwise it will also convert the structure intoJSON. This article will be passed nextJSONTwo functions of the package are introducedJSONConversion with structure.

Structure to JSON

Marshal(v any) ([]byte, error):WillvConvert toJSONData,[]bytereturn in the form.

import (
    "encoding/json"
    "fmt"
)

type User struct {
    Name           string
    Age            int
    Height         float64
    Weight         *float64
    Child          bool
    marriageStatus string
}

func main() {
    weight := 120.5
    user := User{
        Name:           "gopher",
        Age:            18,
        Height:         180.5,
        Weight:         &weight,
        Child:          false,
        marriageStatus: "unmarried",
    }
    jsonBytes, err := (user)
    if err != nil {
        ("error: ", err)
        return
    }
    (string(jsonBytes)) // {"Name":"gopher","Age":18,"Height":180.5,"Weight":120.5,"Child":false}
}

Execution results:

{"Name":"gopher","Age":18,"Height":180.5,"Weight":120.5,"Child":false}

According to the results, we can see:

  • The fields cannot be exported (the field name starts with lowercase letters), and cannot be converted toJSONofkeyYes, this also fitsGoThe syntax stipulates that variables or structure fields starting with lowercase letters cannot be accessed outside the package.
  • The converted field name is the same as the name of the structure field.
  • If the field is a pointer type, the converted value is the field value pointed to by the pointer.

If we want to specify the name after the field is converted, or ignore an exportable field, we can type the structure fieldJSONImplementation of tags.

import (
    "encoding/json"
    "fmt"
)

type User struct {
    Name           string   `json:"name"`
    Age            int      `json:"age"`
    Height         float64  `json:"height"`
    Weight         *float64 `json:"weight"`
    Child          bool     `json:"child"`
    MarriageStatus string   `json:"-"`
}

func main() {
    weight := 120.5
    user := User{
        Name:           "gopher",
        Age:            18,
        Height:         180.5,
        Weight:         &weight,
        Child:          false,
        MarriageStatus: "unmarried",
    }
    jsonBytes, err := (user)
    if err != nil {
        ("error: ", err)
        return
    }
    (string(jsonBytes)) // {"name":"gopher","age":18,"height":180.5,"weight":120.5,"child":false}
}

By setting the structure fieldJSONTags, can be specified to convertJSONThe field name after that, ifJSONThe value of the label is-, then it is in conversionJSONIgnore this field when .

JSON parsing structure

Unmarshal(data []byte, v any) error:WillJSONResolve into the specified structure.

import (
    "encoding/json"
    "fmt"
)

type User struct {
    Name           string  `json:"name"`
    Age            int     `json:"age"`
    Height         float64 `json:"height"`
    Child          bool    `json:"-"`
    marriageStatus string
}

func main() {
    userStr := `
    {
      "name": "gopher",
      "age": 18,
      "height": 180.5,
      "child": true,
      "marriageStatus": "unmarried"
    }
    `
    user := &User{}
    err := ([]byte(userStr), &user)
    if err != nil {
        ("error: ", err)
        return
    }
    ("%#v", user) // &{Name:"gopher", Age:18, Height:180.5, Child:false, marriageStatus:""}
}

Execution results:

&{Name:"gopher", Age:18, Height:180.5, Child:false, marriageStatus:""}

According to the results, we can see:

useUnmarshalWhen using a function, we need to pass in the pointer type of the structure, otherwise the value of the structure field will not be changed, because the underlying layer changes the value of the structure field through pointers.

JSONWhen parsing,JSONofkeyThe matching rules with the structure field are:

  • Priority searchJSONTag values ​​andkeyThe same thing, if you find it,valueAssign to the corresponding field.
  • If notJSONTag value andkeyIf match, match according to the field name.

It can be found that if the structure field is a non-export field orJSONThe value of the label is-, will not be matched.

summary

This article introducesGoIn language,JSONConversion with structure. Turn in structureJSONWhen we can label the field and specify the convertedkeyName, it should be noted that if the field of the structure is not exported or fieldJSONThe tag value is-, in the conversionJSONwill be ignored. on the contraryJSONThe same is true when parsing structures.

This is the article about detailed explanation of the conversion between structures and JSON in Go. For more related Go structures, please search for my previous articles or continue browsing the related articles below. I hope you can support me in the future!