How to parse a list of Json objects in Haskell? -
i have data class:
data mydata = mydata { :: int, b :: string } instance tojson mydata .... instance fromjson mydata ....
i can parse single object json:
get :: io (maybe mydata) = res <- getsingleitemhttp return $ decode $ responsebody res
how can list of mydata?
get2 :: io [mydata] get2 = res <- getmanyitemshttp --???? return $ decode $ responsebody res -- doesn't compile
how go parsing responsebody list
?
it should work once pass in array (and decode list) have change signature get2 :: io (maybe [mydata])
:
{-# language derivegeneric, overloadedstrings #-} module json import ghc.generics import data.aeson import data.text import data.bytestring.lazy data mydata = mydata { :: int, b :: string } deriving (generic, show) instance fromjson mydata example :: bytestring example = "[{ \"a\": 1, \"b\": \"hello\" }, { \"a\": 2, \"b\": \"world\" }]"
example
λ> decode example :: maybe [mydata] [mydata {a = 1, b = "hello"},mydata {a = 2, b = "world"}]
your problem
would this: if try
get :: [mydata] = decode example
the compiler complain with
couldn't match expected type
[mydata]
actual typemaybe a0
…
which should give big hint.
you can still signature data.maybe.maybetolist
:
get :: [mydata] = prelude.concat . maybetolist $ decode example
Comments
Post a Comment