welsonjs/lib/json.js

57 lines
1.4 KiB
JavaScript
Raw Normal View History

2020-06-28 14:22:57 +00:00
////////////////////////////////////////////////////////////////////////
// JSON API
////////////////////////////////////////////////////////////////////////
2020-07-03 09:15:23 +00:00
var scope = {
VERSIONINFO: "JSON Module (json.js) version 0.1",
global: global,
require: global.require
};
2020-06-28 14:22:57 +00:00
2020-07-03 09:15:23 +00:00
scope.stringify = function(obj) {
2020-06-28 14:22:57 +00:00
var items = [];
var isArray = (function(_obj) {
try {
return (_obj instanceof Array);
} catch (e) {
return false;
}
})(obj);
var _toString = function(_obj) {
try {
2020-07-03 09:15:23 +00:00
if (typeof(_obj) == "object") {
return scope.stringify(_obj);
2020-06-28 14:22:57 +00:00
} else {
var s = String(_obj).replace(/"/g, '\\"');
2020-07-03 09:15:23 +00:00
if (typeof(_obj) == "number" || typeof(_obj) == "boolean") {
2020-06-28 14:22:57 +00:00
return s;
} else {
return '"' + s + '"';
}
}
} catch (e) {
return "null";
}
};
2020-07-03 09:15:23 +00:00
for (var k in obj) {
2020-06-28 14:22:57 +00:00
var v = obj[k];
2020-07-03 09:15:23 +00:00
if (!isArray) {
2020-06-28 14:22:57 +00:00
items.push('"' + k + '":' + _toString(v));
} else {
items.push(_toString(v));
}
}
2020-07-03 09:15:23 +00:00
if (!isArray) {
2020-06-28 14:22:57 +00:00
return "{" + items.join(",") + "}";
} else {
return "[" + items.join(",") + "]";
}
};
2020-07-03 09:15:23 +00:00
scope.parse = function(jsonString) {
2020-06-28 14:22:57 +00:00
return (new Function("return " + jsonString)());
};
2020-07-03 09:15:23 +00:00
return scope;