Golang/gin parse JSON from gin.Context

19,720

You don't need to create a struct for all the fields present in the JSON response, only the fields you are interested in. Any other fields present in the response will be ignored when unmarshaling.

You can also unmarshal to a generic map[string]interface{} but this is only really useful for truly dynamic data. If you know the format of the response ahead of time you will nearly always be best to create a custom struct to get type safety and avoid continual nil checks when accessing the map. Additionally, a targeted struct avoids storing unnecessary values when JSON in unmarshalled.

You can use the JSON to Go tool to help quickly create a struct definition from a JSON response. You could then easily strip out all the fields you don't need.

Share:
19,720

Related videos on Youtube

Lucas Liu
Author by

Lucas Liu

A Test Architect at Xueqiu

Updated on June 04, 2022

Comments

  • Lucas Liu
    Lucas Liu almost 2 years

    I learned from the gin doc that you can bind json to a struct like

    type Login struct {
        User     string `form:"user" json:"user" binding:"required"`
        Password string `form:"password" json:"password" binding:"required"`
    }
    
    func main() {
        router := gin.Default()
    
        // Example for binding JSON ({"user": "manu", "password": "123"})
        router.POST("/loginJSON", func(c *gin.Context) {
            var json Login
            if c.BindJSON(&json) == nil {
                if json.User == "manu" && json.Password == "123" {
                    c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
                } else {
                    c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
                }
            }
        })
    }
    

    You always have to build a struct to bind JSON.

    But if there is a very complex JSON data, I only what to get part of it, to create a complex struct is a big burden. Can avoid id and parse it directly?

  • Lucas Liu
    Lucas Liu over 6 years
    Thank you for your suggestion! now I read josn data as a [ ] byte from gin.Context.Request.Body. And use jsonparser github.com/buger/jsonparser to parse (better than encoding/json). That is good enough for me now.