如何删除结构上重复的json信息

我有以下有效的代码



type Q struct {

    Links struct {

        Self struct {

            Href string `json:"href"`

        } `json:"self"`

    } `json:"_links"`

    CreatedAt time.Time `json:"created_at"`

    ID        uuid.UUID `json:"id"`

    Name      string    `json:"name"`

    UpdatedAt time.Time `json:"updated_at"`

}


expected, _ := json.Marshal(Q{Links: struct {

    Self struct {

        Href string `json:"href"`

    } `json:"self"`

}{

    Self: struct {

        Href string `json:"href"`

    }{

        Href: url,

    },

},

    ID:        id,

    Name:      name,

    CreatedAt: now,

    UpdatedAt: now,

})

但是,我发现字段的重复很糟糕json,可以将其从中删除expected吗?如果我删除它会返回错误


holdtom
浏览 138回答 1
1回答

鸿蒙传说

将每个结构声明为命名类型将避免重复重写整个结构类型:type Q struct {    Links     Links     `json:"_links"`    CreatedAt time.Time `json:"created_at"`    ID        string    `json:"id"`    Name      string    `json:"name"`    UpdatedAt time.Time `json:"updated_at"`}type Links struct {    Self Self `json:"self"`}type Self struct {    Href string `json:"href"`}func main() {    expected, _ := json.Marshal(        Q{Links: Links{            Self: Self{                Href: "testurl",            },        },            ID:        "testid",            Name:      "testname",            CreatedAt: time.Now(),            UpdatedAt: time.Now(),        })    fmt.Println(string(expected))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go