Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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