-- | JSON utilities module Json where import Data.Aeson import Data.Aeson.Types (parse) import Data.Text (unpack) import Data.List (intercalate) import qualified Data.Vector as V import qualified Data.Aeson.KeyMap as K import qualified Data.Aeson.Key as K -- | Gets the JSON value of a key (|.) :: Object -> Key -> Value obj |. key = case parse (.: key) obj of Success val -> val Error err -> toJSON err -- | Gets the 'String' value of a key (|:) :: Object -> Key -> String obj |: key = repr (obj |. key) -- | Creates a 'String' representation of a 'Value' repr :: Value -> String repr obj = repr' obj 0 where repr' val lev = case val of Array x -> intercalate ", " $ mapl (\i -> repr' i lev) x Object x -> newline lev $ concat $ map (dump x lev) $ K.keys x String x -> unpack x Number x -> show x Bool x -> show x Null -> "null" mapl f v = V.toList (V.map f v) newline n = if n /= 0 then id else drop 1 indent l = '\n' : (concat . replicate l) " " dump o l k = concat [indent l, K.toString k, ": ", repr' (o |. k) (l+1)] -- | Pretty print a JSON 'Value' pprint :: Value -> IO () pprint = putStrLn . repr