4 ms·
PHP has json_decode() and json_encode() which do all of this correctly ... GO is interesting, but production ready? Not for awhile.
by lucian303 14y ago
PHP has json_decode() and json_encode() which do all of this correctly ... GO is interesting, but production ready? Not for awhile.
- munificent 14y agoPHP is dynamically typed, Go isn't.
- agentS 14y agoPackage encoding/json from the standard library can decode to objects ("Object" in the Java sense, "void *" in the C++ sense) like json_decode does. 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 http://golang.org/pkg/encoding/json/#example_Decoder Anecdotally, a typed version of JSON decoding is much nicer to work with.
- lucian303 14y ago"Anecdotally, a typed version of JSON decoding is much nicer to work with." How so? Considering that JSON isn't strongly typed.
- agentS 14y agoIndeed JSON is not strongly typed. However, in practice, every API, every data exchange format I've ever seen or used has used JSON in a strongly typed fashion. i.e. they say "the returned object will have a key of 'foo' with a number as the value, and a key of 'bar' with an array of strings as the value. 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).