Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json error, cannot unmarshal object into Go value

I have this JSON data:

{
"InfoA" : [256,256,20000],
"InfoB" : [256,512,15000],
"InfoC" : [208,512,20000],
"DEFAULT" : [256,256,20000]
}

With JSON-to-Go, I get this Go type definition:

type AutoGenerated struct {
    InfoA   []int `json:"InfoA"`
    InfoB   []int `json:"InfoB"`
    InfoC   []int `json:"InfoC"`
    DEFAULT []int `json:"DEFAULT"`
}

With this code (play.golang.org)

package main

import (
    "encoding/json"
    "fmt"
    "os"
    "strings"
)

func main() {
    type paramsInfo struct {
        InfoA   []int `json:"InfoA"`
        InfoB   []int `json:"InfoB"`
        InfoC   []int `json:"InfoC"`
        DEFAULT []int `json:"DEFAULT"`
    }
    rawJSON := []byte(`{
"InfoA" : [256,256,20000],
"InfoB" : [256,512,15000],
"InfoC" : [208,512,20000],
"DEFAULT" : [256,256,20000]
}`)
    var params []paramsInfo
    err := json.Unmarshal(rawJSON, &params)
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }
}

I get error json: cannot unmarshal object into Go value of type []main.paramsInfo

I don't understand why. Can you help me?

like image 376
LeMoussel Avatar asked Dec 24 '22 12:12

LeMoussel


1 Answers

The JSON source is a single object, yet you try to unmarshal it into a slice. Change the type of params to paramsInfo (non-slice):

var params paramsInfo
err := json.Unmarshal(rawJSON, &params)
if err != nil {
    fmt.Println(err.Error())
    os.Exit(1)
}
fmt.Printf("%+v", params)

And with that the output (try it on the Go Playground):

{InfoA:[256 256 20000] InfoB:[256 512 15000] InfoC:[208 512 20000]
    DEFAULT:[256 256 20000]}
like image 105
icza Avatar answered Jan 06 '23 11:01

icza