Is it possible to unmarshal an int to a string without a custom decoder?

Hi there,

I’m trying to unmarshal this:

{ "field" : 1 }

into this:

type S struct {
  Field string `json:",int"`

From everything I’ve been able to find this isn’t possible and my options are either to use a json.Number or to write a custom decoder. I’m happy to do both, but I’m curious as to why this isn’t allowed, but the reverse is? I seem to be able to turn a string into a field of type int, so I thought it would make sense to do the reverse.

I’ve got a playground link at , I was about to raise an issue in GH but I saw the advice is ask in the community first. I’d appreciate any feedback, is my understanding of how you use this right? And, if so, is this an intentional decision? Or is it worth pursuing as a bug/enhancement if its not necessarily been explored before?



You are correct that this isn’t possible. The options you see are the ones I know of. If your intent is just to store the number, I would use json.RawMessage.

I think the string struct tag option exists there but its reverse (e.g., int) does not because:

  1. The string is assumed to be JSON encoded, and since there is already a decoder running it was fairly easy to implement
  2. The number of reverse options is large (e.g., int, int32, int64 …). At present there are only two options: omitempty and string
  3. The goal of unmarshling JSON is to put the JSON data into types that match the semantics of the data. A string representation of a JSON number does not do this.
1 Like

Thanks for your response Nathan. So as I looked at it again I actually found keeping it an int and then creating a new transformed object later actually made this easier (I had to combined this data with other data anyway). And thinking on it that seems to correlate with your point 3 really well, keeping the datatypes matching helped me avoid marshal/unmarshal special handling. Given this I’m thinking this really doesn’t need to be raised on GH.

Thanks for helping me get my head around this :slight_smile:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.