Skip to content

Instantly share code, notes, and snippets.

@ElectricImpSampleCode
Last active February 4, 2019 14:38
Show Gist options
  • Save ElectricImpSampleCode/10ad21f1084262f6c050ea1131925412 to your computer and use it in GitHub Desktop.
Save ElectricImpSampleCode/10ad21f1084262f6c050ea1131925412 to your computer and use it in GitHub Desktop.
Squirrel example code: JSON encode for devices
// VERSION 1.0.1
function jsonencode(obj, opts = null, ins = 0) {
local cp = "compact" in opts ? opts.compact : false;
local es = cp ? "" : " ";
local sp = "";
if (!cp && ins > 0) {
for (local i = 0 ; i < ins ; i++) sp += " ";
}
// Branch on type of object being processed
switch (typeof obj) {
// The following are a containers, so iterate through them
case "table":
local tab = "";
foreach (key, val in obj) {
if (tab != "") tab += "," + (!cp ? "\n " + sp : "");
tab += es + jsonencode(key, opts, ins + key.len() + 7) + es + ":" + es + jsonencode(val, opts, ins + key.len() + 7);
}
return "{" + tab + es + "}";
case "array":
local arr = "";
foreach (val in obj) {
if (arr != "") arr += "," + es;
arr += jsonencode(val, opts, ins + arr.len() + 2);
}
return "[" + es + arr + es + "]";
// The following are not containers, so just return their value
case "string":
// From 1.0.1: only include safe strings (otherwise a warning)
if (obj.find("\0") != null) return "'unsafe string'";
return "'" + obj + "'";
case "integer":
return obj.tostring();
case "float":
// From 1.0.1: add initial float support
return obj.tostring();
case "bool":
return obj ? "true" : "false";
// Unsupported entities (functions, blobs, classes, instances) are
// just presented by their type as a string
default:
// From 1.0.1: include entity type in quotes for valid JSON
return "'" + typeof(obj) + "'";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment