rosa/Json.hs

48 lines
1.2 KiB
Haskell
Raw Normal View History

2014-11-25 00:08:56 +01:00
module Json
( (|.)
, (|:)
, repr
, jprint
) where
2014-11-20 21:39:25 +01:00
import Data.Aeson
import Data.Aeson.Types (parse)
import Data.Text (Text, unpack)
import Data.List (intercalate)
import qualified Data.Vector as V
import qualified Data.HashMap.Strict as H
-- Get the JSON value of a key
(|.) :: Object -> Text -> Value
obj |. key = case parse (.: key) obj of
Success val -> val
Error err -> toJSON err
-- Get the String value of a key
2014-11-25 00:08:56 +01:00
2014-11-20 21:39:25 +01:00
(|:) :: Object -> Text -> String
2014-11-21 00:13:52 +01:00
obj |: key = repr' (obj |. key) 0
-- Create a String representation of a JSON
repr :: Value -> String
repr obj = drop 1 $ repr' obj 0
2014-11-20 21:39:25 +01:00
-- Create a String representation of a JSON Value
2014-11-21 00:13:52 +01:00
repr' :: Value -> Int -> String
repr' val lev =
2014-11-20 21:39:25 +01:00
case val of
2014-11-21 00:13:52 +01:00
Array x -> intercalate ", " $ mapl (\i -> repr' i lev) x
2014-11-20 21:39:25 +01:00
Object x -> concat $ map (dump x) $ H.keys x
String x -> unpack x
Number x -> show x
Bool x -> show x
Null -> "null"
where
indent = '\n' : (concat . replicate lev) " "
2014-11-21 00:13:52 +01:00
dump o k = concat [indent, unpack k, ": ", repr' (o |. k) (lev+1)]
2014-11-20 21:39:25 +01:00
mapl f v = V.toList $ V.map f v
2014-11-25 00:08:56 +01:00
-- Print a representation of a JSON Value
jprint :: Value -> IO ()
jprint = putStrLn . repr