Go json.Decoder Considered Harmful

submited by
Style Pass
2021-07-22 20:00:04

If you are coding with Go and using json.Decoder to deserialize a JSON payload, then you are probably signing up for unexpected outcomes. You should use json.Unmarshal instead.

None of this should be a surprise for someone reading the godoc of the package, but it is. I have done this mistake myself many times. Most developers are finding the method signature of json.Decoder.Decode(...) a better fit to parse from an io.Reader type than json.Unmarshal(...).

Not all invalid syntax, but some strings that are invalid JSON but valid JSON streams can be ignored by json.Decoder. Here is an example to illustrate this. Let’s say your API is supposed to return:

you are going to get empty string in v.Name, and no error at all. json.Decoder has unmarshaled the first JSON object and the rest is just ignored.

Is this likely to happen? Probably not, but can you be 100% sure? Because when it happens you will not be able to debug it so easily.

Leave a Comment