haskell - Parse Array in nested JSON with Aeson -


i'm trying write fromjson function aeson.

the json:

{   "total": 1,   "movies": [     {       "id": "771315522",       "title": "harry potter , philosophers stone (wizard's collection)",       "posters": {         "thumbnail": "http://content7.flixster.com/movie/11/16/66/11166609_mob.jpg",         "profile": "http://content7.flixster.com/movie/11/16/66/11166609_pro.jpg",         "detailed": "http://content7.flixster.com/movie/11/16/66/11166609_det.jpg",         "original": "http://content7.flixster.com/movie/11/16/66/11166609_ori.jpg"       }     }   ] } 

the adt: data movie = movie {id::string, title::string}

my attempt:

instance fromjson movie     parsejson (object o) =        movies <- parsejson =<< (o .: "movies") :: parser array        v <- head $ decode movies        return $ movie <$>            (v .: "movies" >>= (.: "id") ) <*>            (v .: "movies" >>= (.: "title") )     parsejson _ = mzero 

this gives couldn't match expected type 'parser t0' actual type 'maybe a0' in first argument of 'head'.

as can see, i'm trying pick first of movies in array, wouldn't mind getting list of movies either (in case there several in array).

if want parse single movie json array of movies, can this:

instance fromjson movie     parsejson (object o) =         movievalue <- head <$> o .: "movies"         movie <$> movievalue .: "id" <*> movievalue .: "title"     parsejson _ = mzero 

but safer route parse [movie] via newtype wrapper:

main = print $ movielist <$> decode "{\"total\":1,\"movies\":[ {\"id\":\"771315522\",\"title\":\"harry potter , philosophers stone (wizard's collection)\",\"posters\":{\"thumbnail\":\"http://content7.flixster.com/movie/11/16/66/11166609_mob.jpg\",\"profile\":\"http://content7.flixster.com/movie/11/16/66/11166609_pro.jpg\",\"detailed\":\"http://content7.flixster.com/movie/11/16/66/11166609_det.jpg\",\"original\":\"http://content7.flixster.com/movie/11/16/66/11166609_ori.jpg\"}}]}"  newtype movielist = movielist {movielist :: [movie]}  instance fromjson movielist     parsejson (object o) = movielist <$> o .: "movies"     parsejson _ = mzero  data movie = movie {id :: string, title :: string}  instance fromjson movie     parsejson (object o) = movie <$> o .: "id" <*> o .: "title"     parsejson _ = mzero 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -