Go parse JSON array of array

huangapple go评论115阅读模式
英文:

Go parse JSON array of array

问题

我有这样的数据

  1. "descriptionMap": [[[1,2], "a"], [[3,4], "b"]]

我试图用以下方式解码它

  1. DescriptionMap []struct {
  2. OpcodeTableIdPair []int
  3. OpcodeDescription string
  4. } `json:"descriptionMap"`

但是我一直得到空数组

  1. [[{[] } {[] }]]
英文:

I have data like this

  1. "descriptionMap": [[[1,2], "a"], [[3,4], "b"]]

and I was trying to decode it with

  1. DescriptionMap []struct {
  2. OpcodeTableIdPair []int
  3. OpcodeDescription string
  4. } `json:"descriptionMap"`

but I keep on getting empty arrays,

  1. [[{[] } {[] }]]

答案1

得分: 3

你有一个非常不幸的JSON模式,将数组视为对象。在这种情况下,你可以尝试以下方法:

  1. type Body struct {
  2. DescriptionMap []Description `json:"descriptionMap"`
  3. }
  4. type Description struct {
  5. IDPair []int
  6. Description string
  7. }
  8. func (d *Description) UnmarshalJSON(b []byte) error {
  9. arr := []interface{}{}
  10. err := json.Unmarshal(b, &arr)
  11. if err != nil {
  12. return err
  13. }
  14. idPair := arr[0].([]interface{})
  15. d.IDPair = make([]int, len(idPair))
  16. for i := range idPair {
  17. d.IDPair[i] = int(idPair[i].(float64))
  18. }
  19. d.Description = arr[1].(string)
  20. return nil
  21. }

请注意,如果JSON中的任何类型不匹配,这段代码将会引发panic。你可以创建一个更好的版本,在这种情况下返回错误。

英文:

You have a very unfortunate JSON schema which treats arrays as objects. The best you can do in this situation is something like this:

  1. type Body struct {
  2. DescriptionMap []Description `json:"descriptionMap"`
  3. }
  4. type Description struct {
  5. IDPair []int
  6. Description string
  7. }
  8. func (d *Description) UnmarshalJSON(b []byte) error {
  9. arr := []interface{}{}
  10. err := json.Unmarshal(b, &arr)
  11. if err != nil {
  12. return err
  13. }
  14. idPair := arr[0].([]interface{})
  15. d.IDPair = make([]int, len(idPair))
  16. for i := range idPair {
  17. d.IDPair[i] = int(idPair[i].(float64))
  18. }
  19. d.Description = arr[1].(string)
  20. return nil
  21. }

Playground: https://play.golang.org/p/MPho12GJfc.

Notice though that this will panic if any of the types in the JSON don't match. You can create a better version which returns errors in such cases.

huangapple
  • 本文由 发表于 2016年12月9日 17:24:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/41057016.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定