Parsing JSON with Text.JSON

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
instance JSON Status where
    readJSON tweet = let (!) = flip valFromObj in do
        userObject <- tweet ! "user"
        user <- userObject ! "screen_name"
        text <- tweet ! "text"
        return Status {user = user, text = text}

    -- Left undefined  because I'm lazy.
    showJSON = undefined

-- Now we can decode our JSON data directly into a list of Statuses.
let statuses = decode json :: Result [Status]

-- Alternatively, using Text.JSON.Generic we can get rid of the boilerplate parsing code in readJSON altogether:

{-# LANGUAGE DeriveDataTypeable #-}                                                                                                      
                                                                                                                                         
import Text.JSON                                                                                                                         
import Text.JSON.Generic                                                                                                                 
                                                                                                                                         
data User = User {                                                                                                                       
    screen_name :: String                                                                                                                
} deriving (Eq, Show, Data, Typeable)                                                                                                    
                                                                                                                                         
data Status = Status {                                                                                                                   
    user :: User,                                                                                                                        
    text :: String                                                                                                                       
} deriving (Eq, Show, Data, Typeable)

-- Now we can convert our JSON data to our Haskell datatype without having to do any of the parsing ourselves.
let statuses = decodeJSON json :: [Status]