JSON.hs
1 2 -- | Parse JSON input files 3 4 module JSON where 5 6 -------------------------------------------------------------------------------- 7 8 import Data.List 9 import Data.Foldable as F 10 import Data.Foldable.WithIndex as FI 11 12 import Data.Map (Map) 13 import qualified Data.Map as Map 14 15 import qualified Data.Text as T 16 import qualified Data.ByteString as B 17 18 import Data.Aeson 19 import Data.Aeson.Key as Key 20 import Data.Scientific 21 22 -------------------------------------------------------------------------------- 23 24 parseInputJsonValue :: Value -> Map String [Integer] 25 parseInputJsonValue val = 26 case val of 27 Object obj -> Map.fromList (map worker (FI.itoList obj)) 28 _ -> error "parseInputJsonValue: expecting a JSON object" 29 where 30 31 worker (key,value) = (Key.toString key, flatten value) 32 33 flatten :: Value -> [Integer] 34 flatten val = case val of 35 Number num -> numberToInteger num 36 Array arr -> F.concatMap flatten arr 37 String txt -> [read (T.unpack txt)] 38 _ -> error "parseInputJsonValue/flatten: expecting a number or an array" 39 40 numberToInteger x = case floatingOrInteger x of 41 Right y -> [y] 42 Left _ -> error "parseInputJsonValue/numberToInteger: expecting an integer" 43 44 -------------------------------------------------------------------------------- 45 46 loadInputJsonFile :: FilePath -> IO (Map String [Integer]) 47 loadInputJsonFile fpath = do 48 text <- B.readFile fpath 49 let Just value = decodeStrict text 50 return $ parseInputJsonValue value 51 52 --------------------------------------------------------------------------------