Home  >  Article  >  Backend Development  >  Golang multiple json

Golang multiple json

PHPz
PHPzforward
2024-02-09 10:42:09874browse

Golang 多个 json

php Editor Banana will introduce you to the processing method of multiple JSON in Golang. In Golang, we often need to handle multiple JSON objects. For example, the data obtained from the API interface may be a JSON array. To facilitate handling this situation, we can use Golang's JSON package to parse and process multiple JSON objects. Using the JSON package, we can parse JSON data into structures in Golang, and then operate and process the structures. This way, we can easily handle multiple JSON objects. Of course, we can also use some third-party libraries, such as GJSON, to process multiple JSON objects more flexibly and efficiently. In general, Golang provides a variety of ways to process multiple JSON objects, and developers can choose the appropriate method according to their own needs.

Question content

I have a json sent to the client, it has 2 variations, all the difference is a field name push/pull, how can I do this without Don't copy structure tags just for one

"message": "Project updated successfully.",
        "data": {
            "push": {
                "projects": [
                    {
                        "name": "test",
                        "summary": "nn",
                    
                    }
                ],
                "events": []
            }
        }
    }
    "message": "Project updated successfully.",
        "data": {
            "pull": {
                "projects": [
                    {
                        "name": "test",
                        "summary": "nn",
                    
                    }
                ],
                "events": []
            }
        }
    }

`

I'm thinking of making a date field interface and replacing a different structure

Workaround

Just define a single type with Push and Pull fields:

type A struct {
    Message string `json:"message"`
    Data    struct {
        Push *B `json:"push,omitempty"`
        Pull *B `json:"pull,omitempty"`
    } `json:"data"`
}

type B struct {
    Projects []struct {
        Name    string `json:"name"`
        Summary string `json:"summary"`
    } `json:"projects"`
    Events []interface{} `json:"events"`
}

Check nil after decoding to determine what type of event it represents.

The above is the detailed content of Golang multiple json. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete