Go parse JSON array of array

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

Go parse JSON array of array

问题

我有这样的数据

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

我试图用以下方式解码它

  DescriptionMap []struct {
    OpcodeTableIdPair []int
    OpcodeDescription string   
  } `json:"descriptionMap"`

但是我一直得到空数组

[[{[] } {[] }]]
英文:

I have data like this

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

and I was trying to decode it with

  DescriptionMap []struct {
    OpcodeTableIdPair []int
    OpcodeDescription string   
  } `json:"descriptionMap"`

but I keep on getting empty arrays,

[[{[] } {[] }]]

答案1

得分: 3

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

type Body struct {
    DescriptionMap []Description `json:"descriptionMap"`
}

type Description struct {
    IDPair      []int
    Description string
}

func (d *Description) UnmarshalJSON(b []byte) error {
    arr := []interface{}{}
    err := json.Unmarshal(b, &arr)
    if err != nil {
        return err
    }

    idPair := arr[0].([]interface{})
    d.IDPair = make([]int, len(idPair))
    for i := range idPair {
        d.IDPair[i] = int(idPair[i].(float64))
    }

    d.Description = arr[1].(string)

    return nil
}

请注意,如果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:

type Body struct {
	DescriptionMap []Description `json:"descriptionMap"`
}

type Description struct {
	IDPair      []int
	Description string
}

func (d *Description) UnmarshalJSON(b []byte) error {
	arr := []interface{}{}
	err := json.Unmarshal(b, &arr)
	if err != nil {
		return err
	}

	idPair := arr[0].([]interface{})
	d.IDPair = make([]int, len(idPair))
	for i := range idPair {
		d.IDPair[i] = int(idPair[i].(float64))
	}

	d.Description = arr[1].(string)

	return nil
}

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:

确定