Last active
September 22, 2020 16:40
-
-
Save clsource/3af291596b657aff1a901c440117234f to your computer and use it in GitHub Desktop.
A simple JSON stringify for Wren language.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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