Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unmarshal nested JSON into flat struct in Go [duplicate]

Suppose I define a struct as following:

type User struct {
    ID          string
    Name        string
    Age         uint
    City        string      `json:"address.city"`
    Province    string      `json:"address.province"`
}

I am able to take a User struct, and expand out the flattened fiends into a nested JSON structure, with an address object. I'm struggling however to go in the other direction.

How would I take the following JSON:

{
    "ID": "1",
    "Name": "Keith Baldwin",
    "Age": 30,
    "address": {
        "city": "Saskatoon",
        "province": "Saskatchewan"
    }
}

And unmarshal it into the given struct?

Is there something I'm missing, or will I just have to write it from scratch, probably using reflection?

Thanks

like image 342
robbieperry22 Avatar asked Oct 17 '25 21:10

robbieperry22


1 Answers

Create userInfo class

type UserInfo struct {
    ID      string `json:"ID"`
    Name    string `json:"Name"`
    Age     int    `json:"Age"`
    Address struct {
        City     string `json:"city"`
        Province string `json:"province"`
    } `json:"address"`
}

Then unmarshal your json data into a userinfo object

var userInfo UserInfo
    jsonStr := `{
    "ID": "1",
    "Name": "Keith Baldwin",
    "Age": 30,
    "address": {
        "city": "Saskatoon",
        "province": "Saskatchewan"
    }
}`
json.Unmarshal([]byte(jsonStr), &userInfo)
like image 76
Ehsan.Saradar Avatar answered Oct 20 '25 12:10

Ehsan.Saradar