首页 > 解决方案 > 解码 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"`,而不是创建一个全新的结构来解码这个对象?

标签: go

解决方案


您需要在某个地方存储 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 的类型IDstring修复{json 中的缺失)。


正如Dave C 在评论中指出的那样,这并不比仅仅使用匿名结构类型更短:

var a struct{ Accounts []AccountProperties }

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

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


推荐阅读