大佬教程收集整理的这篇文章主要介绍了haskell – 使用Aeson嵌套JSON中的Parse Array,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
JSON:
{ "@R_53_10586@l": 1,"movies": [ { "id": "771315522","title": "Harry Potter and the 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" } } ] }
ADT:data Movie = Movie {id :: String,title :: String}
我的尝试:
instance FromJSON Movie where parseJSON (Object o) = do movies <- parseJSON =<< (o .: "movies") :: Parser Array v <- head $decode movies return $Movie <$> (v .: "movies" >>= (.: "id") ) <*> (v .: "movies" >>= (.: "title") ) parseJSON _ = mzero
这给出了无法匹配预期类型’Parser t0’与实际类型’也许a0’在’头’的第一个参数.
正如你所看到的,我正在尝试选择Array中的第一部电影,但是我也不会介意获得电影列表(如果Array中有几个).
instance FromJSON Movie where parseJSON (Object o) = do movieValue <- head <$> o .: "movies" Movie <$> movieValue .: "id" <*> movieValue .: "title" parseJSON _ = mzero
但更安全的路线是通过newtype包装解析[Movie]:
@H_235_4@main = print $movieList <$> decode "{\"@R_53_10586@l\":1,\"movies\":[ {\"id\":\"771315522\",\"title\":\"Harry Potter and the 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 where parseJSON (Object o) = MovieList <$> o .: "movies" parseJSON _ = mzero data Movie = Movie {id :: String,title :: String} instance FromJSON Movie where parseJSON (Object o) = Movie <$> o .: "id" <*> o .: "title" parseJSON _ = mzero以上是大佬教程为你收集整理的haskell – 使用Aeson嵌套JSON中的Parse Array全部内容,希望文章能够帮你解决haskell – 使用Aeson嵌套JSON中的Parse Array所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。