go icon indicating copy to clipboard operation
go copied to clipboard

bug: Different handling of json.Number than standard library

Open matoous opened this issue 4 years ago • 1 comments

Description

"encoding/json" behaves differently for certain inputs for json.Number. Specifically, "encoding/json" checks that json.Number is a valid number whereas jsoniter doesn't check anything. This should be either specified in docs (i.e. remove A high-performance 100% compatible drop-in replacement of "encoding/json") or fixed.

Example

the go play space

package main

import (
	stdJson "encoding/json"
	"fmt"

	jsonIter "github.com/json-iterator/go"
)

type X struct {
	Y json.Number `json:"y"`
}

func main() {
	var x1, x2 X
	err := jsonIter.Unmarshal([]byte(`{"y": " 1"}`), &x1)
	fmt.Printf("1: %q, %v\n", x1.Y, err)
	err = stdJson.Unmarshal([]byte(`{"y": " 1"}`), &x2)
	fmt.Printf("2: %q, %v\n", x2.Y, err)
}

which results into:

1: " 1", <nil>
2: "", json: invalid number literal, trying to unmarshal "\" 1\"" into Number

Caused by this check used in "encoding/json": https://github.com/golang/go/blob/e6ac2df2b198f583780277a7cf96e3b0b61fe0a1/src/encoding/json/encode.go#L652

matoous avatar Apr 01 '21 10:04 matoous

Run into this problem as well

package main

import (
	"encoding/json"
	"fmt"

	"github.com/json-iterator/go"
)

type test struct {
	Numbers []json.Number `json:"numbers"`
}

func main() {
	var text = `{"numbers":["some text"]}`
	var ptr = new(test)
	fmt.Println(jsoniter.Unmarshal([]byte(text), ptr))
	fmt.Println(json.Unmarshal([]byte(text), ptr))
}
<nil>
json: invalid number literal, trying to unmarshal "\"some text\"" into Number

gonejack avatar Apr 20 '23 06:04 gonejack