lab09: impl pretty print
This commit is contained in:
@@ -1,5 +1,6 @@
|
|||||||
import Text.ParserCombinators.Parsec
|
import Text.ParserCombinators.Parsec
|
||||||
import System.Environment
|
import System.Environment
|
||||||
|
import Data.List (intercalate)
|
||||||
|
|
||||||
data JValue = JString String
|
data JValue = JString String
|
||||||
| JNumber Double
|
| JNumber Double
|
||||||
@@ -83,11 +84,33 @@ jsonMember = do
|
|||||||
parseJSON :: String -> Either ParseError JValue
|
parseJSON :: String -> Either ParseError JValue
|
||||||
parseJSON input = parse jsonFile "(unknown)" input
|
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
|
main = do
|
||||||
args <- getArgs
|
args <- getArgs
|
||||||
p <- parseFromFile jsonFile (head args)
|
p <- parseFromFile jsonFile (head args)
|
||||||
case p of
|
case p of
|
||||||
Left err -> print err
|
Left err -> print err
|
||||||
Right json -> print json
|
Right json -> putStrLn (prettyPrint json)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user