Search code examples
gostructtags

How to pass entire json string to a field of nested struct while unmarshaling?


I need to unmarshal flat json string

data := `{"login":"Nickname","password":"some_pass","newPassword":"new_pass"}`

into the UpdatePasswordRequest nested structure:

type SignInRequest struct {
    Login    string `json:"login"`
    Password string `json:"password"`
}

type UpdatePasswordRequest struct {
    NewPassword string        `json:"newPassword"`
    SignInData  SignInRequest `<tag>`
}

Unmarshaling data to the result with all possible <tag> values

var result UpdatePasswordRequest
json.Unmarshal([]byte(data), &result)

gives empty Login and Password:

result.SignInData.Login = ""
result.SignInData.Password = ""

How should I define the <tag> to get correct values for Login and Password fields?


Solution

  • If you are going to use a name for the <tag>, your json should be nested, not flat, like this:

    data := `{"newPassword":"new_pass", "myTag":{"password":"some_pass", "login":"Nickname"}}`
    

    If you can't change your json, should compose the structs ( aka. struct embedding ) like this:

    type SignInRequest struct {
        Login    string `json:"login"`
        Password string `json:"password"`
    }
    
    type UpdatePasswordRequest struct {
        NewPassword string        `json:"newPassword"`
        SignInRequest
    }