Home > Backend Development > Golang > How Can I Dynamically Change JSON Tags in Go Structs at Runtime?

How Can I Dynamically Change JSON Tags in Go Structs at Runtime?

Barbara Streisand
Release: 2024-12-21 15:46:10
Original
841 people have browsed it

How Can I Dynamically Change JSON Tags in Go Structs at Runtime?

Dynamically Changing JSON Tags in Structs

Problem

A struct with nested structs is given, and the goal is to dynamically modify the JSON tag of a specific field within the struct before JSON encoding it. The desired JSON output is to have a specific field name overriden.

Solution

Using an Anonymous Struct in MarshalJSON

In Go versions 1.8 and above, a technique can be employed to dynamically change the JSON tag of a field at runtime. This involves creating an anonymous struct with the desired field tags within the MarshalJSON method of the original struct.

func (u *User) MarshalJSON() ([]byte, error) {
    type alias struct {
        ID   int64  `json:"id"`
        Name string `json:"name"` // The modified JSON tag
        tag  string `json:"-"`
        Another
    }

    var a alias = alias(*u)
    return json.Marshal(&a)
}
Copy after login

Here, the alias struct has the same fields as the User struct, but the Name field has the desired JSON tag ("name" instead of "first"). By returning the JSON encoding of the alias struct, the JSON field name can be overridden dynamically.

Iterating Over All Fields

To iterate over all fields of a struct, including embedded structs, use the reflect package as follows:

value := reflect.ValueOf(*u)
for i := 0; i < value.NumField(); i++ {
    tag := value.Type().Field(i).Tag.Get("json")
    field := value.Field(i)
    fmt.Println(tag, field)
}
Copy after login

This code will iterate over all fields, including those in the embedded Another struct, and print the JSON tag and field value for each field.

The above is the detailed content of How Can I Dynamically Change JSON Tags in Go Structs at Runtime?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template