質問

Suppose I'm parsing a JSON input into a structure like this:

type Person struct {
        Name string `json:"name"`
        Age  uint   `json:"age"`         
}

and pass erroneous data (string instead of int):

var person Person
err := json.Unmarshal([]byte(`{"name": "Dilbert", "age": "unknown"}`), &person)

This is what I can extract from the error:

// Error json: cannot unmarshal string into Go value of type uint
fmt.Printf("Error %v\n", err) 

// Unexpected value: unknown
jerr := err.(*json.UnmarshalTypeError)
fmt.Printf("Unexpected value: %s\n", (*jerr).Value)

// Expected type: uint
fmt.Printf("Unexpected type: %v\n", (*jerr).Type)

I'd like to report also which field is erroneous (age, in my case), is that possible?

(I understand, that, for example, when you parse an array or a scalar value, that's not applicable, but still, I hope there might be some workaround or trick for the case of objects.)

役に立ちましたか?

解決

Unfortunately this is currently not supported.

There is an accepted issue for this. It seems to be not trivial to implement (see quote from the ticket below) but hopefully it comes with Go 1.3.

Made slightly inconvenient to implement because by the time the error is generated the decoder is looking at the field value itself, not the struct that contains the field. The relevant code doesn't even know that it's decoding into a struct field. There are a few ways to get around this but they are non-trivial.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top