make it TRUE in Go

recently I faced an interesting problem while tightening up a type I was unmarshaling some JSON to in Go. The particular service I was dealing with was sending me JSON for which a particular field, lets call it "E", would be a bool value, with the catch being that if "E" was not present in the JSON at all, it was assumed to be true for operations with that service.

Alarm bells starting going off in my head. Go has a bool type that I could nest inside a struct that would be the instance type for the JSON unmarshal...but bools in Go default to being false. so, if the "E" field was not present in the JSON, my default unmarshal would have the opposite default, false!. How would I know if a value of false was the result of an assignment from the JSON unmarshal, or the default?

The solution was found in json.UnmarshalJSON. Implemented for your own type, you can control how JSON is expressed as fields in your own struct. By changing the field in my struct from bool to interface{}, I was also able to move up to the more general type abstraction, which is nil when not set, a value outside of the range of values for the bool type. simply - if the JSON from the external service does not specify a "E" field, I will see it as nil, and can act on that.

To test for yourself, you can change the value of "E" from the string s in the main func below, or remove it from the JSON entirely to see how it indeed does default to true. Solution below.


last update 2012-07-31