Last active
January 1, 2019 19:07
-
-
Save ChristophP/ebcf05dec61afc46fce73161242644c7 to your computer and use it in GitHub Desktop.
Haskell JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module SimpleJson | |
( JValue(..) | |
, put | |
) where | |
import Data.List (intercalate) | |
-- union type | |
data JValue | |
= JString String | |
| JNumber Float | |
| JBool Bool | |
| JArray [JValue] | |
| JObject [(String, JValue)] | |
| JNull | |
deriving (Show, Eq) | |
-- Json to string | |
renderJValue :: JValue -> String | |
renderJValue value = | |
case value of | |
JString string -> show string | |
JNumber number -> show number | |
JBool True -> "true" | |
JBool False -> "false" | |
JNull -> "null" | |
JArray list -> | |
let values = intercalate ", " $ map renderJValue list | |
in "[" ++ values ++ "]" | |
JObject pairs -> | |
let values = | |
map (\(key, val) -> show key ++ ":" ++ renderJValue val) pairs | |
keyValues = intercalate ", " values | |
in "{ " ++ keyValues ++ " }" | |
put :: JValue -> IO () | |
put = putStrLn . renderJValue | |
-- Run program | |
main :: IO () | |
main = put $ JArray [JString "Peter"] -- prints: ["Peter"] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment