Skip to content

Instantly share code, notes, and snippets.

@duplode
Created March 30, 2014 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duplode/63edd2123fd7c25dcd05 to your computer and use it in GitHub Desktop.
Save duplode/63edd2123fd7c25dcd05 to your computer and use it in GitHub Desktop.
[
{
"id": 1,
"vertices": {
"3": {
"y": 12,
"x": 0
},
"2": {
"y": 16,
"x": 24
},
"1": {
"y": 12,
"x": 10
}
},
"scenario": [
1,
2,
3,
1
]
}
]
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
module Main where
import qualified Data.Text as T
import qualified Data.Text.Read as TR
import qualified Data.Foldable as Foldable
import qualified Data.HashMap.Strict as M
import Control.Monad
import Control.Applicative
import Data.Aeson
import Data.Either
import qualified Data.ByteString.Lazy as BS
type Id = Int
type Edge = (Id, Id)
type Scenario = [Id]
data Point = Point Int Int deriving (Show)
data Vertex = Vertex {-# UNPACK #-}!Id {-# UNPACK #-}!Point deriving (Show)
data Graph = Graph Id [Vertex] Scenario deriving (Show)
instance FromJSON Point where
parseJSON (Object v) = liftM2 Point (v .: "x") (v .: "y")
parseJSON _ = fail "Bad point"
instance FromJSON [Vertex] where
parseJSON j = case j of
(Object o) -> mapM parseVertex $ M.toList o
_ -> fail "Bad vertices"
where
parseVertex (rawID, rawPoint) = do
let eID = TR.decimal rawID
liftM2 Vertex (either (fail "Bad vertex id") (return . fst) eID) $ parseJSON rawPoint
instance FromJSON Graph where
parseJSON (Object v) = do
i <- parseJSON =<< v .: "id"
vs <- parseJSON =<< v .: "vertices"
sc <- parseJSON =<< v .: "scenario"
return $ Graph i vs sc
parseJSON _ = fail "Bad graph"
main = do
input <- BS.readFile "example.json"
print (eitherDecode input :: Either String [Graph])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment