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

Cannot unmarshal string number value to json.Number #143

Open
sattellite opened this issue Oct 21, 2024 · 0 comments
Open

Cannot unmarshal string number value to json.Number #143

sattellite opened this issue Oct 21, 2024 · 0 comments

Comments

@sattellite
Copy link

If a number is passed in string form, I catch a conversion error. I remember exactly that there was no such problem a few months ago, but now this problem has appeared.

package main

import (
	jsonStd "encoding/json"
	"fmt"

	"github.com/segmentio/encoding/json"
)

type eventStd struct {
	ID jsonStd.Number `json:"id"`
}

type event struct {
	ID json.Number `json:"id"`
}

func main() {
	data1 := []byte(`{"id":151}`)
	data2 := []byte(`{"id":"151"}`)

	var event1, event2 event
	err1 := json.Unmarshal(data1, &event1)
	err2 := json.Unmarshal(data2, &event2)
	fmt.Printf("segmentio:\n%+v, %+v\n", event1, err1)
	fmt.Printf("segmentio:\n%+v, %+v\n", event2, err2)

	var event3, event4 eventStd
	err3 := jsonStd.Unmarshal(data1, &event3)
	err4 := jsonStd.Unmarshal(data2, &event4)
	fmt.Printf("stdlib:\n%+v, %+v\n", event3, err3)
	fmt.Printf("stdlib:\n%+v, %+v\n", event4, err4)
}

Output:

segmentio:
{ID:151}, <nil>
segmentio:
{ID:}, json: cannot unmarshal "\"151\"}" into Go struct field main.event.id of type json.Number
stdlib:
{ID:151}, <nil>
stdlib:
{ID:151}, <nil>

This example in executable form https://go.dev/play/p/_ZilgKjQYwL

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