go-json-experiment / json

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

optimize the error when map key are not stringifyable #42

Closed ethanvc closed 1 month ago

ethanvc commented 1 month ago

Now, the error returned when map key is not convertiable to string is as below:

func Test_StdMarshal_BoolKey(t *testing.T) {
    m := map[bool]int32{
        true: 3,
    }
    buf, err := json.Marshal(m)
    _ = buf
    require.Equal(t, `jsontext: missing string for object name`, err.Error())
    buf, err = jsonv1.Marshal(m)
    require.Equal(t, `json: unsupported type: map[bool]int32`, err.Error())
}

Maybe better to provide more readable error messages as before. If you have plan, i would glad to offer a MR.

dsnet commented 1 month ago

Hi, thanks for the issue. Revamping errors is something we'd like to do before a formal proposal to the Go stdlib. I'm sure we can fold addressing this into that work.

This case is particular interesting since it's halfway between being a syntactic error and a semantic error. A syntactic error deals with problems as it relates to the JSON grammar, while a semantic error deals with problems assigning meaning as JSON data from Go data (or vice versa).

In this case, we're currently producing syntactic error, since marshaling a Go bool is producing a JSON bool when the JSON grammar is expecting a string. Technically, this is correct.

However, this is also arguably a semantic error as the marshaler should have realized that marshaling a Go bool would have produced invalid JSON, and so there's a higher level semantic problem going on.

We could resolve this tension by nested a SyntacticError into a SemanticError. Thus, it can be both.