go - 解码 json 值的更好方法
问题描述
假设一个具有一般格式的 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
来访问这样创建的(单个)映射条目:
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 示例(我必须更改 to 的类型ID
并string
修复{
json 中的缺失)。
正如Dave C 在评论中指出的那样,这并不比仅仅使用匿名结构类型更短:
var a struct{ Accounts []AccountProperties }
就Unmarshall
通话而言(以这种方式完成后,使用起来更方便)。如果你想在json.Marshall
调用中使用这样的匿名结构,你需要标记它的单个元素以获得小写编码:没有标记它将被调用"Accounts"
而不是"accounts"
.
(我并不认为 map 方法更好,只是一种替代方法。)
推荐阅读
- html - div表的边框间距问题
- unit-testing - 如何检查 Java 8 Stream 是否关闭?
- php - codeigniter hook post并获取数据进行安全处理(SQL注入)
- r - 从 GRIB 文件中获取特定位置的数据
- ios - iOS Security.framework arm64 架构问题
- netlogo - 网络标志中的补丁可以有两种颜色,有时隐藏一种吗?
- css - 如何组合两个 SCSS 选择器?
- ios - 将字符串拆分为数组数组
- cloud - 当我想在 SAP Cloud Platform 中运行 UI5 应用程序时缺少功能的问题
- vba - 导入数据后刷新表单