lab09: impl pretty print
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import Text.ParserCombinators.Parsec
|
||||
import System.Environment
|
||||
import Data.List (intercalate)
|
||||
|
||||
data JValue = JString String
|
||||
| JNumber Double
|
||||
@@ -83,11 +84,33 @@ jsonMember = do
|
||||
parseJSON :: String -> Either ParseError JValue
|
||||
parseJSON input = parse jsonFile "(unknown)" input
|
||||
|
||||
prettyPrint :: JValue -> String
|
||||
prettyPrint json = prettyPrint' json 0
|
||||
|
||||
prettyPrint' :: JValue -> Int -> String
|
||||
prettyPrint' json indent = replicate indent ' ' ++ case json of
|
||||
JString s -> show s
|
||||
JNumber n -> show n
|
||||
JBool b -> show b
|
||||
JNull -> "null"
|
||||
JArray arr -> "[\n"
|
||||
++ intercalate ",\n" (map (\x -> prettyPrint' x (indent + 2)) arr)
|
||||
++ "\n]"
|
||||
JObject members -> "{\n"
|
||||
++ intercalate ",\n" (map (
|
||||
\(k, v) -> replicate (indent + 2) ' '
|
||||
++ k
|
||||
++ ": "
|
||||
++ prettyPrint' v 0) members)
|
||||
++ "\n"
|
||||
++ replicate indent ' '
|
||||
++ "}"
|
||||
|
||||
main = do
|
||||
args <- getArgs
|
||||
p <- parseFromFile jsonFile (head args)
|
||||
case p of
|
||||
Left err -> print err
|
||||
Right json -> print json
|
||||
Right json -> putStrLn (prettyPrint json)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user