亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何刪除結構上重復的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 關注
  • 112 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號