And more examples when json.Unmarshal() returns an error (in addition to indicating an invalid JSON):
Specifying a nil or empty fragment:
i := 0 err := json.Unmarshal(nil, &i) fmt.Println(err) // unexpected end of JSON input
Indication of no pointer to unmarshal in:
err = json.Unmarshal([]byte('{"name":"a"}'), i) fmt.Println(err) // json: Unmarshal(non-pointer int)
Specifying nil as the target pointer:
err = json.Unmarshal([]byte('{"name":"a"}'), nil) fmt.Println(err) // json: Unmarshal(nil)
Specifies the JSON numbers that will overflow the target type. json.Unmarshal() doc json.Unmarshal() :
If the JSON value is not suitable for the target type, or if the JSON number overflows the target type, Unmarshal skips this field and completes the dismantling as best as possible. If no more serious errors are found, Unmarshal returns a UnmarshalTypeError describing the earliest such error.
To demonstrate this:
var j int8 err = json.Unmarshal([]byte('1112'), &j) fmt.Println(err)
Or when trying to analyze something like time. time.Time which is not an RFC3339 timestamp:
var t time.Time err = json.Unmarshal([]byte('"xx"'), &t) fmt.Println(err) // parsing time ""xx"" as ""2006-01-02T15:04:05Z07:00"": cannot parse "xx"" as "2006"
source share