开发者

parsing complicated jsons with Aeson

开发者 https://www.devze.com 2023-04-11 06:21 出处:网络
I\'m trying to parse a call to an API into a haskell record type using the Aeson Library I\'m using wikipedia pages, and parsing them to the title and a list of links.

I'm trying to parse a call to an API into a haskell record type using the Aeson Library

I'm using wikipedia pages, and parsing them to the title and a list of links. A sample would be this,

{"query":{"pages":{"6278041":{"pageid":6278041,"ns":0,"title":"Lass","links":[{"ns":0,"title":"Acronym"},{"ns":0,"title":"Dead Like Me"},{"ns":0,"title":"Donna Lass"},{"ns":0,"title":"George Lass"},{"ns":0,"title":"Girl"},{"ns":0,"title":"Lassana Diarra"},{"ns":0,"title":"Lightning Lass"},{"ns":0,"title":"Real Madrid"},{"ns":0,"title":"Shadow Lass"},{"ns":0,"title":"Solway Lass"},{"ns":0,"title":"Szymon Lass"},{"ns":0,"title":"The Bonnie Lass o' Fyvie"},{"ns":0,"title":"The Tullaghmurray Lass"},{"ns":0,"title":"Woman"},{"ns":12,"title":"Help:Disambiguation"}]}}}}

and I would like to parse it to the title and a list of links in a data type like this.

data WikiPage = WikiPage { title :: String,
                           links :: String }

What code I currently have is this,

instance FromJSON WikiPage where
  parseJSON j = do
    o <- parseJSON j
    let id = head $ o .: "query" .: "pages" 
    let name = o .: "query" .: "pages" .: id .: "title"
    let links = mapM (.: "title") (o .: "query".: "pages" .: id .: "links")
    return $ WikiPage name links

I'm getting the error,

Couldn't match expected type `Data.Text.Internal.Text'
                with actual type `[Char]'
    In the second argument of `(.:)', namely `"title"'

I don't really get whats going on, I feel like there must be a problem with how I'm mapping over the links but I'm not sure exactly what has to be done. I also don't get how I'm supposed to use id in the second query string as it's a parser (I'm sure I need to use开发者_运维问答 applicative in here somewhere but I'm not sure how.) I haven't found any examples that decompose more complicated jsons like this.


I'm also trying to figure out aeson. I had the same problem you were having, and I solved it by adding {-# LANGUAGE OverloadedStrings #-} at the top of my source file. I'm very new to Haskell, but I believe it adds an unofficial extension to the language, presumably to allow strings to double as other string-like datatypes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号