Gabriel
Gabriel

Reputation: 5723

Cannot unmarshal array

Have this json file:

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

And this code:

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)

}

And keep getting:

Error: json: cannot unmarshal array into Go struct field Palette.Colors of type string

Or similar if i change the palette type. Tips? Thanks!

Upvotes: 1

Views: 2365

Answers (2)

Cosmic Ossifrage
Cosmic Ossifrage

Reputation: 5379

Your JSON blob has a nested array within the "colors" element, so you need to nest the array of colors in your Palette struct. Amending the declaration of Palette to have Colors of type [][]string resolves this:

type Palette struct {
    Colors [][]string
}

Playground link

Upvotes: 7

Cetin Basoz
Cetin Basoz

Reputation: 23797

Your json has [][]string and you didn't specify json property name:

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

Upvotes: 1

Related Questions