SoFunction
Updated on 2025-03-03

Use of tags during JSON parsing in Go

When processing json format strings, you often see that when declaring struct structures, there are back quotes on the right side of the property. As shown in:

 type User struct {
     UserId   int    `json:"user_id" bson:"user_id"`
     UserName string `json:"user_name" bson:"user_name"`
 }

struct member variable tag (Tag) description

To understand this in more detail, you must first understand the basics of golang. In golang, naming is recommended in camel method, and has a special syntax meaning in the upper and lower case of the first letter: it cannot be quoted outside the package. However, data interaction is often required with other systems, such as converting it to JSON format, storing it to mongodb, etc. At this time, if you use the attribute name as the key value, it may not necessarily meet the project requirements.

So there are more backticks, which are called tags in golang. When converted to other data formats, specific fields will be used as key values. For example, the above example is converted to json format:

 u := &User{UserId: 1, UserName: "tony"}
 j, _ := (u)
 (string(j))
// Output content:// {"user_id":1,"user_name":"tony"}
// If no tag description is added to the attribute, the output is:// {"UserId":1,"UserName":"tony"}// You can see that the attribute name of the struct is used as the key value.// == There is also a bson statement, which is used to store data to mongodb ==

struct member variable tag (Tag) get

So when we need to encapsulate some operations ourselves and use the content in the tag, how to obtain it? Here you can use the method in the reflection package (reflect) to obtain: the complete code is as follows:

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

func main() {
    type User struct {
        UserId   int    `json:"user_id" bson:"user_id"`
        UserName string `json:"user_name" bson:"user_name"`
    }
    // Output json format    u := &User{UserId: 1, UserName: "tony"}
    j, _ := (u)
    (string(j))
    // Output content: {"user_id":1,"user_name":"tony"}
    // Get the content in the tag    t := (u)
    field := ().Field(0)
    (("json"))
    // Output: user_id    (("bson"))
    // Output: user_id}

Custom tags

 type User struct {
     UserId   int    `json:"user_id" bson:"user_id" test:"test"`
     UserName string `json:"user_name" bson:"user_name"`
 }

Get the value of test in the tag

// Get the content in the tagtypeof := (u)
field := ().Field(0)
(("json"))
// Output: user_id(("bson"))
// Output: user_id(("test"))
// Output:test

This is the end of this article about the use of tags during JSON parsing in Go. For more related Go JSON tag content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!