Skip to content

Instantly share code, notes, and snippets.

@clsource
Last active September 22, 2020 16:40
Show Gist options
  • Save clsource/3af291596b657aff1a901c440117234f to your computer and use it in GitHub Desktop.
Save clsource/3af291596b657aff1a901c440117234f to your computer and use it in GitHub Desktop.
A simple JSON stringify for Wren language.
// the .js is only for syntax highlighter.
class JSON {
// Based on https://github.com/brandly/wren-json/blob/master/json.wren
static stringify(obj) {
if (obj is Num || obj is Bool || obj is Null) {
return obj.toString
}
if (obj is String) {
// Escape special characters
var specialchars = {
"\"" : "\\\"",
"\\" : "\\\\",
"\b" : "\\b",
"\f" : "\\f",
"\n" : "\\n",
"\r" : "\\r",
"\t" : "\\t",
"\v" : "\\v"
}
var substrings = []
for (char in obj) {
if(specialchars[char]) {
substrings.add(specialchars[char])
} else {
substrings.add(char)
}
}
return "\"" + substrings.join("") + "\""
}
if (obj is List) {
var substrings = obj.map { |item| JSON.stringify(item) }
return "[" + substrings.join(",") + "]"
}
if (obj is Map) {
var substrings = obj.keys.map { |key|
return JSON.stringify(key) + ":" + JSON.stringify(obj[key])
}
return "{" + substrings.join(",") + "}"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment