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)
}
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.
Unmarshal will return an error when the input is not valid JSON (like, change false to hello , or remove the close brace).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With