Skip to content

Instantly share code, notes, and snippets.

@gnh1201
Last active August 4, 2023 06:56
Show Gist options
  • Save gnh1201/e372f5de2e076dbee205a07eb4064d8d to your computer and use it in GitHub Desktop.
Save gnh1201/e372f5de2e076dbee205a07eb4064d8d to your computer and use it in GitHub Desktop.
SimpleJSON: JSON encode, decode without default parser (pure javascript JSON parser)
// SimpleJSON: JSON encode, decode without default (pure javascript JSON parser)
// Go Namhyeon <[email protected]>
// https://github.com/gnh1201
// MIT license
var $ = {};
/**
* Decode JSON
*
* @param string jsonString - JSON text
*
* @return object
*/
$.json.decode = function(jsonString) {
return (new Function("return " + jsonString)());
};
/**
* Encode JSON
*
* @param object obj - Key/Value object
*
* @return string
*/
$.json.encode = function(obj) {
var items = [];
var isArray = (function(_obj) {
try {
return (_obj instanceof Array);
} catch (e) {
return false;
}
})(obj);
var _toString = function(_obj) {
try {
if(typeof(_obj) == "object") {
return $.json.encode(_obj);
} else {
var s = String(_obj).replace(/"/g, '\\"');
if(typeof(_obj) == "number" || typeof(_obj) == "boolean") {
return s;
} else {
return '"' + s + '"';
}
}
} catch (e) {
return "null";
}
};
for(var k in obj) {
var v = obj[k];
if(!isArray) {
items.push('"' + k + '":' + _toString(v));
} else {
items.push(_toString(v));
}
}
if(!isArray) {
return "{" + items.join(",") + "}";
} else {
return "[" + items.join(",") + "]";
}
};
/**
* Test JSON
*
* @param object obj - Key/Value object
*
* @return boolean
*/
$.json.test = function(obj) {
var t1 = obj;
var t2 = $.json.encode(obj);
$.echo($.json.encode(t1));
var t3 = $.json.decode(t2);
var t4 = $.json.encode(t3);
$.echo(t4);
if(t2 == t4) {
$.echo("success");
return true;
} else {
$.echo("failed");
return false;
}
};
/**
* Echo
*
* @param string txt
*
* @return void
*/
$.echo = function(txt) {
if($.isWScript()) {
WScript.Echo(txt);
} else {
try {
window.alert(txt);
} catch (e) {
console.log(txt);
}
}
};
/**
* Check if WScript
*
* @return bool
*/
$.isWScript = function() {
return typeof(WScript) !== "undefined";
}
// test your data
var t1 = {"a": 1, "b": "banana", "c": {"d": 2, "e": 3}, "f": [100, 200, "3 hundreds", {"g": 4}]};
$.json.test(t1);
@gnh1201
Copy link
Author

gnh1201 commented Aug 4, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment