gpt4 book ai didi

go - 解码 json 值的更好方法

转载 作者:数据小太阳 更新时间:2023-10-29 03:36:04 25 4
gpt4 key购买 nike

假设一个具有通用格式的 JSON 对象

  "accounts": [
{
"id": "<ACCOUNT>",
"tags": []
}
]
}

我可以创建一个带有相应 json 标签的结构来解码它

 type AccountProperties struct {
ID AccountID `json:"id"`
MT4AccountID int `json:"mt4AccountID,omitempty"`
Tags []string `json:"tags"`
}

type Accounts struct {
Accounts []AccountProperties `json:"accounts"`
}

但最后一个只有一个元素的结构对我来说似乎不正确。有没有一种方法可以简单地说 type Accounts []AccountProperties `json:"accounts"` 而不是创建一个全新的结构来解码这个对象?

最佳答案

您需要在某处存储 json 字符串 accounts。使用:

var m map[string][]AccountProperties

就足够了,当然你需要知道使用字符串文字 accounts 来访问这样创建的(单个) map 条目:

type AccountProperties struct {
ID string `json:"id"`
MT4AccountID int `json:"mt4AccountID,omitempty"`
Tags []string `json:"tags"`
}

func main() {
var m map[string][]AccountProperties
err := json.Unmarshal([]byte(data), &m)
fmt.Println(err, m["accounts"])
}

查看完整 Go Playground example (我必须将 ID 的类型更改为 string 并修复 json 中丢失的 {)。


作为Dave C points out in comments ,这不比使用匿名结构类型短:

var a struct{ Accounts []AccountProperties }

Unmarshall 调用而言(以这种方式完成后,使用 会更方便)。如果你想在 json.Marshall 调用中使用这样的匿名结构,你需要标记它的单个元素以获得小写编码:没有标记它将被称为 "帐户” 而不是 “帐户”

(我不认为 map 方法更好,只是一个替代方法。)

关于go - 解码 json 值的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57642677/

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