gpt4 book ai didi

json.Marshal 映射到 JSON 数组

转载 作者:IT王子 更新时间:2023-10-29 01:42:42 27 4
gpt4 key购买 nike

当我尝试 Marshal map 时,json.Marshal 返回:

{"Map Key":"Map Value"}...

这是正常行为。但我可以将其编码为:

{"Map":[{"Name":"Map Key","Date":"Map Value"},{"Name":"Map Key2","Date":"Map Value2"}]}

最佳答案

您可以定义自定义 json.Marshaler接口(interface)来做到这一点,例如:

type mapInfo struct {
Name string `json:"name"`
Date string `json:"date"`
}

type CustomMap map[string]string

func (cm CustomMap) MarshalJSON() ([]byte, error) {
// if you want to optimize you can use a bytes.Buffer and write the strings out yourself.
var out struct {
Map []mapInfo `json:"map"`
}
for k, v := range cm {
out.Map = append(out.Map, mapInfo{k, v})
}
return json.Marshal(out)
}

func (cm CustomMap) UnmarshalJSON(b []byte) (err error) {
var out struct {
Map []mapInfo `json:"map"`
}
if err = json.Unmarshal(b, &out); err != nil {
return
}
for _, v := range out.Map {
cm[v.Name] = v.Date
}
return
}

playground

关于json.Marshal 映射到 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30134828/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com