Skip to content

Instantly share code, notes, and snippets.

@MichaelXavier
Created February 12, 2011 05:45
Show Gist options
  • Save MichaelXavier/823554 to your computer and use it in GitHub Desktop.
Save MichaelXavier/823554 to your computer and use it in GitHub Desktop.
This is why you don't parse JSON in Haskell
{-# LANGUAGE DeriveDataTypeable #-}
import Text.JSON
import Text.JSON.Generic
import Control.Monad (liftM2)
data Foo = Foo { name :: String } deriving (Eq, Show, Typeable, Data)
data FooSet = FooSet { foos :: [(String, Foo)]} deriving (Eq, Show)
-- Input data looks like
-- {"number 1":{"name":"BAZ"}}
-- To parse it:
instance JSON FooSet where
showJSON = undefined
readJSON (JSObject obj) = do
fs <- fmap fromJSObject (readJSON $ showJSON obj :: Result (JSObject JSValue))
fmap wrapfooset $ sequence $ map (uncurry (liftM2 (,))) $ map (\(a,b) -> (return a, fromJSON b :: Result Foo)) fs
where wrapfooset fs = FooSet {foos = fs}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment