Skip to content

Cannot unmarshal string number value to json.Number #143

@sattellite

Description

@sattellite

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions