简体   繁体   中英

Parsing a JSON string in Haskell

I'm working on simple Haskell programme that fetches a JSON string from a server, parses it, and does something with the data. The specifics are not really pertinent for the moment, the trouble I'm having is with parsing the JSON that is returned.

I get the JSON string back from the server as an IO String type and can't seem to figure out how to parse that to a JSON object.

Any help would be much appreciated :)

Here is my code thus far.

import Data.Aeson
import Network.HTTP

main = do
    src <- openURL "http://www.reddit.com/user/chrissalij/about.json"
    -- Json parsing code goes here

openURL url = getResponseBody =<< simpleHTTP (getRequest url)

Note: I'm using Data.Aeson in the example as that is what seems to be recommended, however I'd be more than willing to use another library.

Also any and all of this code can be changed. If getting the

Data.Aeson is designed to be used with Attoparsec, so it only gives you a Parser that you must then use with Attoparsec. Also, Attoparsec prefers to work on ByteString , so you have to alter the way the request is made slightly to get a ByteString result instead of a String .

This seems to work:

import Data.Aeson
import Data.Attoparsec
import Data.ByteString
import Data.Maybe
import Network.HTTP
import Network.URI

main = do
    src <- openURL "http://www.reddit.com/user/chrissalij/about.json"
    print $ parse json src

openURL :: String -> IO ByteString
openURL url = getResponseBody =<< simpleHTTP (mkRequest GET (fromJust $ parseURI url))

Here I've just parsed the JSON as a plain Value , but you'll probably want to create your own data type and write a FromJSON instance for it to handle the conversion neatly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM