by implicit · 11y ago · 0 comments
instance FromJSON Person where
parseJSON = withObject "Person" $ \o -> do
name <- o .: "name"
age <- o .: "age"
return (Person name age)
let person = case decode some_bytestring of
Success p -> p
Error e -> error "Malformed JSON"
It works with arbitrary data types (including enums!), lets you easily, exactly specify what sort of data to accept, and doesn't require stepping outside the language.1. no specific error messages; these take up a good portion of the Go code, although they could certainly be more automatic;
2. does not allow the same code to be used for encoding and decoding (i.e. you don't have to write a list of fields twice, and can specify which format to encode to/decode from once rather than separately specifying the encoding and decoding functions - note that the format may not be uniquely determined by the final type you want in the output, e.g. you just want a generic date value out, but you need to use a specific date format for the JSON conversion).
The first is more of a nitpick (are those going to show up in 'e' anyway?), but the second is important. Do popular Haskell JSON libraries have a way to do that?
Also, reflection is not really stepping outside the language.
Data.Aeson.TH[1] can automatically generate JSON decoders and encoders for data types, if that's what you want.
[1] http://hackage.haskell.org/package/aeson-0.8.0.2/docs/Data-A...