-
-
Save duplode/63edd2123fd7c25dcd05 to your computer and use it in GitHub Desktop.
http://stackoverflow.com/questions/22701055/parsing-nested-json-with-random-integer-keys-using-aeson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"id": 1, | |
"vertices": { | |
"3": { | |
"y": 12, | |
"x": 0 | |
}, | |
"2": { | |
"y": 16, | |
"x": 24 | |
}, | |
"1": { | |
"y": 12, | |
"x": 10 | |
} | |
}, | |
"scenario": [ | |
1, | |
2, | |
3, | |
1 | |
] | |
} | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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