Parsing a JSON string in Haskell

I am working on a simple Haskell program that retrieves a JSON string from a server, parses it, and does something with the data. The specifics are not very relevant at the moment, the problem I encountered is parsing the JSON that is returned.

I get a JSON string from the server as an IO String type and cannot figure out how to parse this into a JSON object.

Any help would be greatly appreciated :)

Here is my code.

 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 am using Data.Aeson in the example, since this is what seems recommended, however I would more than like to use another library.

Also, any and all of this code can be changed. If you get

+6
source share
1 answer

Data.Aeson intended for use with Attoparsec, so it gives you a Parser that you should use with Attoparsec. In addition, Attoparsec prefers to work with ByteString , so you need to change the request method a bit to get the result of ByteString instead of String .

It works:

 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 just parsed JSON as a simple Value , but you probably want to create your own data type and write an FromJSON instance FromJSON that it handles the conversion neatly.

+10
source

Source: https://habr.com/ru/post/894407/


All Articles