Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect marshalling of json.Number #227

Closed
sudo-suhas opened this issue Jan 23, 2018 · 1 comment
Closed

Incorrect marshalling of json.Number #227

sudo-suhas opened this issue Jan 23, 2018 · 1 comment

Comments

@sudo-suhas
Copy link

Marshalling of json.Number values produces incorrect result:

package main

import (
	"encoding/json"
	"fmt"

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

type Nums struct {
	N1 json.Number `json:"n1,Number"`
	N2 json.Number `json:"n2,Number"`
}

func check(err error) {
	if err != nil {
		panic(err)
	}
}

func main() {
	data := []byte(`{ "n1": 1.2, "n2": "" }`)

	var v1 Nums
	check(json.Unmarshal(data, &v1))
	bs, err := json.Marshal(v1)
	check(err)
	fmt.Printf("\nWith standard library:\n\tValue: %#v\n\tMarshalled: %s\n", v1, bs)

	var v2 Nums
	check(jsoniter.Unmarshal(data, &v2))
	bs, err = jsoniter.Marshal(v2)
	check(err)
	fmt.Printf("\nWith jsoniter:\n\tValue: %#v\n\tMarshalled: %s\n", v2, bs)

	custJSON := jsoniter.Config{
		UseNumber:               true,
		EscapeHTML:              false,
		MarshalFloatWith6Digits: true,
	}.Froze()
	var v3 Nums
	check(custJSON.Unmarshal(data, &v3))
	bs, err = custJSON.Marshal(v3)
	check(err)
	fmt.Printf("\nWith jsoniter custom config:\n\tValue: %#v\n\tMarshalled: %s\n", v3, bs)
	check(jsoniter.Unmarshal(bs, &v2))
}

Output:

With standard library:
	Value: main.Nums{N1:"1.2", N2:""}
	Marshalled: {"n1":1.2,"n2":0}

With jsoniter:
	Value: main.Nums{N1:"1.2", N2:""}
	Marshalled: {"n1":1.2,"n2":}

With jsoniter custom config:
	Value: main.Nums{N1:"1.2", N2:""}
	Marshalled: {"n1":1.2,"n2":}
panic: main.Nums: N2: readNumberAsString: invalid number, error found in #10 byte of ...|:1.2,"n2":}|..., bigger context ...|{"n1":1.2,"n2":}|...

goroutine 1 [running]:
main.check(0x5e43c0, 0xc042044600)
	e:/workspace/golang/src/playground/jsoniter_num.go:17 +0x51
main.main()
	e:/workspace/golang/src/playground/jsoniter_num.go:46 +0x808
exit status 2
@taowen taowen closed this as completed in c39a632 Jan 25, 2018
@sudo-suhas
Copy link
Author

Thanks for the quick fix @taowen! Could you please also make a release for this?

zhenzou pushed a commit to zhenzou/jsoniter that referenced this issue Feb 2, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant