go - 解码 json 值的更好方法

标签 go

假设一个具有通用格式的 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/

相关文章:

docker - 如何防止 docker build 重新下载复制的 Go vendor

json - 从 Golang 中的模数和指数创建公钥

Golang "best"使用空值和数据库时的实践

json - 如何更改 json 对象数组的字段名称

Go - 如何将结构字段的数据类型定义为另一个结构

mongodb - sort _id : -1 的 mgo 翻译

unit-testing - Uber Cadence 事件的单元测试上下文

go - 非主包装的Dump Go组件

string - 如何在 Golang 中使用 Append 方法。语法要求接口(interface)?

go - 如何从 Go 服务器在浏览器中下载文件