如何在结构体中删除重复的 JSON 信息

huangapple go评论91阅读模式
英文:

How to remove duplicate json information on struct

问题

我有以下可以工作的代码:

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

英文:

I have the following code that works


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

However, I find bad the repeteation of json fields, it is possible to remove it from expected? If I remove it returns an error

答案1

得分: 3

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

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

英文:

Declaring each struct as a named type will avoid having to rewrite the whole struct type repeatedly:

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

huangapple
  • 本文由 发表于 2022年7月25日 06:29:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/73102530.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定