go-json-experiment / json

Experimental implementation of a proposed v2 encoding/json package
BSD 3-Clause "New" or "Revised" License
377 stars 12 forks source link

Question: Receiving Multiple Unmarshal Error #21

Closed ardan-bkennedy closed 8 months ago

ardan-bkennedy commented 8 months ago

Is there a way to extract multiple errors from an unmarshal operation?

type user struct {
    ID    uuid.UUID `json:"id"`
    Roles Role      `json:"role"`
}

func main() {
    j := `{"id": "asdadsasd", "role": "JACK"}`
    var u user

    if err := json.Unmarshal([]byte(j), &u); err != nil {
        se := err.(*json.SemanticError)
        log.Fatalf("%s\n", se)
    }

    fmt.Printf("%+v\n", u)
}

The value for both id and role are not compliant with the type. Is there a way to get back that information instead of the first field that fails?

dsnet commented 8 months ago

When designing v2, we talked about having a mode where we continue parsing as far as possible and collect up the errors, but didn't have a good API to collect up the errors. At the time errors.Join and the implicit interface{ Unwrap() []error } interface did not exist, so the calculus is different today. We decided back then that failing early on the first error was still the right default with the intention of eventually providing this ability.

dsnet commented 8 months ago

For past discussion: https://youtu.be/tfWn54N6uwc?feature=shared&t=922

ardan-bkennedy commented 8 months ago

Ok cool. Thanks for getting back to me so quickly.