Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 465
Chris Salij Avatar asked Aug 05 '11 18:08

Chris Salij


1 Answers

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.

like image 120
hammar Avatar answered Oct 13 '22 06:10

hammar