登录
首页 >  Golang >  Go问答

如何去除struct中重复的json信息

来源:stackoverflow

时间:2024-02-11 17:15:19 456浏览 收藏

大家好,今天本人给大家带来文章《如何去除struct中重复的json信息》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我有以下有效的代码

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 中删除?如果我删除它会返回错误


正确答案


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

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

Go Playground

以上就是《如何去除struct中重复的json信息》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>