Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore JSON fields when marshalling not unmarshalling

Tags:

json

go

Assume I have a password field in a User struct.

type User struct{
   UserName string `json:"username"`
   Password string `json:"-"`
}

My clients register their users by posting username and password together. So if I decode JSON to above struct, it ignores password. It's expected. But I wondered is there any way to ignore fields when only marshalling. I checked go official documentation page but couldn't find anything.

https://golang.org/pkg/encoding/json/

I can add an extra field into the struct but I need to know first is it possible to do that with JSON lib.

like image 768
RockOnGom Avatar asked Nov 13 '17 02:11

RockOnGom


1 Answers

One common approach is to use a temporary type or variable, with same structure, but different json tags or even different structure:

type User struct {
    UserName string `json:"username"`
    Password string `json:"password"`
}

func (usr User) MarshalJSON() ([]byte, error) {
    var tmp struct {
        UserName string `json:"username"`
    }
    tmp.UserName = usr.UserName
    return json.Marshal(&tmp)
}
like image 54
Kaveh Shahbazian Avatar answered Sep 16 '22 14:09

Kaveh Shahbazian