Skip to content

Instantly share code, notes, and snippets.

@TheSeamau5
Created June 22, 2015 20:37
Show Gist options
  • Save TheSeamau5/91a73a32dc47a249fc26 to your computer and use it in GitHub Desktop.
Save TheSeamau5/91a73a32dc47a249fc26 to your computer and use it in GitHub Desktop.
Little JSON encoder
import String
import List
infixl 2 =>
(=>) = (,)
type Json
= Number Float
| String String
| List (List Json)
| Object (List (String, Json))
number : Float -> Json
number =
Number
string : String -> Json
string =
String
list : List Json -> Json
list =
List
object : List (String, Json) -> Json
object =
Object
type alias Vector =
{ x : Float , y : Float }
vector : Vector -> Json
vector {x,y} =
object
[ "x" => number x
, "y" => number y
]
jsonToString : Json -> String
jsonToString json =
case json of
Number n ->
toString n
String s ->
toString s
List list ->
list
|> List.map jsonToString
|> String.join ","
|> \s -> "[" ++ s ++ "]"
Object listOfFields ->
let
entry (key, value) =
toString key ++ " : " ++ jsonToString value
in
listOfFields
|> List.map entry
|> String.join ","
|> \s -> "{" ++ s ++ "}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment