Mou Hsiao
Mou Hsiao

Reputation: 366

How to ignore an association field in JSON output when it is not loaded?

In my gorm models, I have User, and Profile:

type User struct {
    ID            int    
    Username      string
    Password      string     `json:"-"`

    Profile Profile
}

type Profile struct {
    UserID        int    
    Gender        string
    Places        string

    //...And many more fields
}

When I look for a full display of one's profile by using:

db.Preload("Profile").Where("id = ?", 1).First(&user)
c.JSON(200, user) 

The JSON result which client side will receive is perfectly fine:

{
    "ID": 1,
    "Username": {
        "String": "",
        "Valid": false
    },
    "Profile": {
        "UserID": 1,
        "Gender": "men",
        "Places": "Home and staying home",
        // ...And many more
    },
}

But when I want to list only ID and Username two fields, even though I did not Preload() or Related() Profile, there is still an empty set of it:

db.Where("id = ?", 1).First(&user)
c.JSON(200, user) 

// Result
{
    "ID": 1,
    "Username": {
        "String": "",
        "Valid": false
    },
    //below is redundant in this situation
    "Profile": {
        "UserID": 0,
        "Gender": "",
        "Places": "",
        // ...And many more 0 or "" fields
    },
}

My question is how to ignore the Profile fields from JSON response every time when it is not loaded? In order to save some transfer cost

Upvotes: 1

Views: 736

Answers (1)

Puneet Singh
Puneet Singh

Reputation: 3543

You should use pointer of the struct if you want to omit them. It will make it nil if not loaded, and it will not appear in JSON

type User struct {
    ID            int    
    Username      string
    Password      string     `json:"-"`

    Profile *Profile `json:",omitempty"`
}

Upvotes: 2

Related Questions