by chimeracoder · 13y ago · 0 comments
I wrote a short script to automate generating the struct definitions, since I didn't want to generate the structs by hand. Go's reflection made this really easy.
1. It assumes all slices to be of type []interface{} by default, though oftentimes a more precise type is possible. (This is just a matter of looping through and determining the most specific type)
2. It only accepts valid JSON. Not a bug, but for example, the sample responses on the foursquare API documentation omit the (required) quotation marks around identifiers: https://developer.foursquare.com/docs/venues/venues (click "Try it Out"). That's a common problem which I'd like to fix eventually.
It also can decode directly into typed structures. An example from the documentation (you'll have to open the linked example): http://golang.org/pkg/encoding/json/#example_Decoder
Anecdotally, a typed version of JSON decoding is much nicer to work with.
How so? Considering that JSON isn't strongly typed.
Why is this nicer?
Let's say you are working with the Reddit API. You can, of course, do it the way you suggested, and just decode the result into an untyped object. However, I find this incredibly brittle. You end up with strings indexing into arrays all over the place.
On the other hand, when you decode into a Go struct, you use the regular dot syntax to access parameters. You can't misspell these or use the value inappropriately (trying to loop over a JSON number, for example). You can write comments on the fields to document what you expect various values to hold. It is nicer in the same sense that using classes is nicer than just using arrays for everything.
Another benefit is of course the improvement of performance. Accessing an string value in a JSON object by a key is the equivalent of a hash table lookup in Python or PHP. It is incrementing a pointer by a constant number in Go (assuming you use strongly typed decoding).
I'll say it again, Go's encoding/json can do what you want (the equivalent of json_decode). There are better alternatives available to users of that package, and the GP was discussing how to exploit one of those better alternatives without having to write the struct by hand (which I personally find a trivial one time cost).
In pseudo-code-ish:
type FacebookUser struct {
ProfileID int
Name string
....
}
json.Unmarshal(response, FacebookUser)
Compare it to the implementations that just give you a hash: json_decode($response);
json.parse response
Yeah, you can document it with comments, or visit the API documentation, but you can fix the code and let your comments go stale. You fix both your documentation and your implementation in one go in the first example.It's certainly why I find it more appealing, anyway. Makes me feel more secure in my code.