无法解组数组

时间:2018-08-02 15:42:06

标签: json go marshalling

拥有此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字段中   调色板。字符串类型的颜色

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

2 个答案:

答案 0 :(得分:7)

您的JSON Blob在“ colors”元素中具有嵌套数组,因此您需要在Palette结构中嵌套颜色数组。将Palette的声明修改为Colors类型的[][]string可以解决此问题:

type Palette struct {
    Colors [][]string
}

Playground link

答案 1 :(得分:1)

您的json具有[] []字符串,而您未指定json属性名称:

package main

import (
    "encoding/json"
    "fmt"
)

type Palette struct {
    Colors [][]string `json:"colors"`
}

func main() {
    jsonStr := `{
  "colors": [
    ["#7ad9ab", "#5ebd90", "#41a277", "#21875e", "#713517"],
    ["#5ebd90", "#41a277", "#21875e", "#006d46", "#561e00"],
    ["#005430"]
  ]
}`
    var palette Palette
    err := json.Unmarshal([]byte(jsonStr),&palette)
    if err != nil {
        fmt.Printf("Error: %v \n", err.Error())
    }
    fmt.Printf("Data: %v", palette)
}

Here is a link to playground sample