无法解组数组

问题描述 投票:0回答:2

有这个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结构字段Palette.Colors类型为string

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

json go marshalling
2个回答
7
投票

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

type Palette struct {
    Colors [][]string
}

Playground link


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

© www.soinside.com 2019 - 2024. All rights reserved.