-
Notifications
You must be signed in to change notification settings - Fork 18.7k
Description
package main
import (
"fmt"
"encoding/json"
)
func main() {
var x map[string]int
err := json.Unmarshal([]byte(`{"a":1,"b":"c"}`), &x)
fmt.Printf("x = %#v, err = %s", x, err)
}Output:
x = map[string]int{"a":1, "b":0}, err = json: cannot unmarshal string into Go value of type int
I think this violates the principle of least astonishment, "b" key shouldn't appear in the output x map.
The relevant part of the documentation for json.Unmarshal() is:
To unmarshal a JSON object into a map, Unmarshal first establishes a map to use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal reuses the existing map, keeping existing entries. Unmarshal then stores key-value pairs from the JSON object into the map. The map's key type must either be any string type, an integer, implement json.Unmarshaler, or implement encoding.TextUnmarshaler.
If a JSON value is not appropriate for a given target type, or if a JSON number overflows the target type, Unmarshal skips that field and completes the unmarshaling as best it can. If no more serious errors are encountered, Unmarshal returns an UnmarshalTypeError describing the earliest such error. In any case, it's not guaranteed that all the remaining fields following the problematic one will be unmarshaled into the target object.
It doesn't seem to me that it describes the above behaviour.