Skip to content

Instantly share code, notes, and snippets.

@ChristophP
Last active January 1, 2019 19:07
Show Gist options
  • Save ChristophP/ebcf05dec61afc46fce73161242644c7 to your computer and use it in GitHub Desktop.
Save ChristophP/ebcf05dec61afc46fce73161242644c7 to your computer and use it in GitHub Desktop.
Haskell JSON
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 ++ " }"
-- print
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