首页 > 解决方案 > 无法解组数组

问题描述

有这个json文件:

    {
  "colors": [
    ["#7ad9ab", "#5ebd90", "#41a277", "#21875e", "#713517"],
    ["#5ebd90", "#41a277", "#21875e", "#006d46", "#561e00"],
    ["#005430"]
  ]
}

而这段代码:

type Palette struct {
    Colors []string
}

func TestStuff(t *testing.T) {
    c, err := os.Open("palette.json")
    if err != nil {
        fmt.Printf("Error: %v", err.Error())
    }
    defer c.Close()
    bc, _ := ioutil.ReadAll(c)
    var palette []Palette //also tried with Palette

    err = json.Unmarshal(bc, &palette)
    if err != nil {
        fmt.Printf("Error: %v \n", err.Error())
    }
    fmt.Printf("Data: %v", palette)

}

并不断获得:

错误:json:无法将数组解组为字符串类型的 Go struct 字段 Palette.Colors

或者如果我更改调色板类型,则类似。提示?谢谢!

标签: jsongomarshalling

解决方案


您的 JSON blob 在“colors”元素中有一个嵌套数组,因此您需要在 Palette 结构中嵌套颜色数组。将 Palette 的声明修改为 hasColors类型[][]string解决了这个问题:

type Palette struct {
    Colors [][]string
}

游乐场链接


推荐阅读