rahul
rahul

Reputation: 463

Cannot unmarshal object into Go value of type []uint8

I am fairly new to Go. I have the following code:

package main

import (
    "encoding/json"
    "fmt"
)
func main() {

    byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
    dat := []byte(`{"num":7.13,"strs":["c","d"]}`)
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    fmt.Println(dat)

}

Getting the error:

cannot "unmarshal object into Go value of type []uint8".

How can I fix this please?

Upvotes: 2

Views: 15307

Answers (2)

Maroun
Maroun

Reputation: 95948

I think you meant to do something like this:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    var dat interface{}
    byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    fmt.Println(dat)
}

What you were trying to do makes no sense, since you're trying to unmarshal two JSON objects one into another.

Upvotes: 2

icza
icza

Reputation: 417412

You have 2 JSON inputs, and you're trying to unmarshal one into the other. That doesn't make any sense.

Model your JSON input (the object) with a type (struct), and unmarshal into that. For example:

type Obj struct {
    Num  float64  `json:"num"`
    Strs []string `json:"strs"`
}

func main() {
    byt := []byte(`{"num":6.13,"strs":["a","b"]}`)

    var obj Obj
    if err := json.Unmarshal(byt, &obj); err != nil {
        panic(err)
    }
    fmt.Println(obj)

}

Output (try it on the Go Playground):

{6.13 [a b]}

Upvotes: 9

Related Questions