Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json Unmarshal error

Tags:

json

go

I'm getting an error of:

json.Unmarshal undefined (type interface {} has no field or method Unmarshal)

trying to convert a json byte slice into the generic interface{} type. I'm reading the docs for encoding/json and they give an example that shows this is valid. What gives?

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)

func main() {

    var json interface{}
    data, _ := ioutil.ReadFile("testMusic.json")
    json.Unmarshal(data, &json)
    m := json.(map[string]interface{})
    fmt.Printf("%+v", m)

}
like image 887
enjoylife Avatar asked Mar 28 '13 15:03

enjoylife


People also ask

What is Unmarshal JSON?

To unmarshal a JSON array into a slice, Unmarshal resets the slice length to zero and then appends each element to the slice. As a special case, to unmarshal an empty JSON array into a slice, Unmarshal replaces the slice with a new empty slice.

What does Unmarshal return?

Unmarshal will return an error when the input is not valid JSON (like, change false to hello , or remove the close brace).

How do I use Unmarshal JSON?

To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct. Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. Note: If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

What does JSON NewDecoder do?

NewDecoder() is designed to decode streams of JSON objects and considers a request body like '{"Name": "Bob"}{"Name": "Carol": "Age": 54}' or '{"Name": "Dave"}{}' to be valid. But in the code above only the first JSON object in the request body will actually be parsed.


1 Answers

You've defined a local variable json that masks the global symbol json referring to the JSON module. Renaming your local variable should allow your code to work.

like image 92
Martin Atkins Avatar answered Oct 07 '22 17:10

Martin Atkins