haskell - Parse JSON with fieldnames that contain reserved keywords -
i'm trying parse following json aeson.
{ "data": [ { "id": "34", "type": "link", "story": "foo" }, { "id": "35", "type": "link", "story": "bar" } ] } since there lot of field i'd ignore, seems i should use ghc generics. how write data type definition uses haskell keywords data , type? following of course gives: parse error on input `data'
data feed = feed {data :: [post]} deriving (show, generic) data post = post { id :: string, type :: string, story :: string } deriving (show, generic)
you can write own fromjson , tojson instances without relying on ghc.generics. means can use different field names data representation , json representation.
example instances post:
{-# language overloadedstrings #-} import control.applicative import data.aeson import qualified data.bytestring.lazy lbs data post = post { postid :: string, typ :: string, story :: string } deriving (show) instance fromjson post parsejson (object x) = post <$> x .: "id" <*> x.: "type" <*> x .: "story" parsejson _ = fail "expected object" instance tojson post tojson post = object [ "id" .= postid post , "type" .= typ post , "story" .= story post ] main :: io () main = print $ (decode $ post "{\"type\": \"mytype\", \"story\": \"really interresting story\", \"id\" : \"someid\"}" :: maybe post) lbs.putstrln $ encode $ post "myid" "mytype" "some other story" the same can done feed. if didn't have ignore fields, use derivejson data.aeson.th, takes function modify field names it's first argument.
Comments
Post a Comment