为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
holdtom 2023-01-03 17:18:56
我有以下有效的代码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吗?如果我删除它会返回错误
查看完整描述

1 回答

?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

将每个结构声明为命名类型将避免重复重写整个结构类型:


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))

}


查看完整回答
反对 回复 2023-01-03
  • 1 回答
  • 0 关注
  • 137 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号