tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
14.1k stars 846 forks source link

Bind Nested Json by Gin Framework #216

Closed majidalaeinia closed 3 years ago

majidalaeinia commented 3 years ago

Hi, On your examples, you have used raw JSON and parse that, but most of the time we are getting the JSON from an API.

I want to use github.com/gin-0gonic/gin and also your package to parse nested JSON, how should I do that?

// This is the input json on the postman 
{
    "name": {
        "first": "Janet",
        "last": "Prichard"
    },
    "age": 47
}

This is the equivalent controller to handle the route which sent that json body:

func (ctrl BookController) ItemUpdate(c *gin.Context) {
    id := cast.ToInt(c.Param("id"))

    type NameStruct struct {
        First string `json:"first"`
        Last  string `json:"last"`
    }
    type Complete struct {
        Name NameStruct `json:"name"`
        Age int `json:"age"`
    }
    var complete Complete

    json := c.BindJSON(&complete)

    //const json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}`
    value := gjson.Get(json, "name.last") // This is wrong. What should I do to get the value `name.last` (Prichard) on my controller?
}
majidalaeinia commented 3 years ago

No need to use this package actually, found that I can use a struct in another struct and bind it.