Skip to content

math/big: big.Int (incorrectly) marshals to a number instead of a string #28154

@alvarogzp

Description

@alvarogzp

I am using go version go1.11 linux/amd64, and reproduced this issue with the latest version (1.11).

Type Int on package "math/big" implements both [Un]marshalText and [Un]marshalJSON, the later just calling its *Text counterpart: https://golang.org/src/math/big/intmarsh.go?s=1964:2010#L64

According to json.Marshal and json.Unmarshal documentation, both functions are not equivalent. [Un]marshalJSON works with raw JSON types, but [Un]marshalText only with previously-unquoted strings. The documentation also says that [Un]marshalJSON has priority over [Un]marshalText.

So, with those premises, currently big.Int is being marshaled into a number, as their [Un]marshalJSON functions are being called and they don't quote the result after calling [Un]marshalText on the big.Int.
I think it should marshal into a string, as big.Float does (because it only implements [Un]marshalText). Also, other tools usually work and expect string representations for big numbers.

Here you can see the result of marshaling a struct with a big.Int and a big.Float: https://play.golang.org/p/WIILuWzr57S
Note how the Float is properly quoted and marshaled as a string but the Int isn't.

I propose doing one of the following things:

  • Remove [Un]marshalJSON from https://golang.org/src/math/big/intmarsh.go. According to a comment, they are only there to provide "backwards compatibility" with programs that search for those methods.
  • Modify big.Int's [Un]marshalJSON to quote the string it produces and unquote the one it receives, so that it mimics what json.[Un]marshal does before and after calling [Un]marshalText.
  • If marshaling big.Int to a number is the desired behavior, make it explicit by removing [Un]marshalText from big.Int (as in that case, they won't apply), and also make big.Float marshal to a number too.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions