Skip to content

Instantly share code, notes, and snippets.

@lasandell
Last active August 29, 2015 14:07
Show Gist options
  • Save lasandell/b0b8ab0dd87f7a928f84 to your computer and use it in GitHub Desktop.
Save lasandell/b0b8ab0dd87f7a928f84 to your computer and use it in GitHub Desktop.
Simple JSON renderer. It doesn't do indentation nor does it have all the types. Feel free to extend.
type JObject = JProperty list
and JProperty = string * JValue
and JValue =
| JString of string
| JInt of int
| JObject of JObject
| JArray of JValue list
let rec renderJson jObject =
let quote value = sprintf "\"%s\"" value
let delim start render values stop =
let text = values |> Seq.map render |> String.concat ","
sprintf "%c%s%c" start text stop
let renderProp (name, value) =
sprintf "%s:%s" (quote name) (renderJson value)
match jObject with
| JString value -> quote value
| JInt value -> string value
| JObject props -> delim '{' renderProp props '}'
| JArray values -> delim '[' renderJson values ']'
JArray [
JObject [
"FirstName", JString "John"
"LastName", JString "Smith"
"Age", JInt 28
"Pets", JArray [
JString "Cat"
]
]
JObject [
"FirstName", JString "Kate"
"LastName", JString "Jones"
"Age", JInt 52
"Pets", JArray [
JString "Dog"
JString "Parrot"
]
]
] |> renderJson
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment