Skip to content

Instantly share code, notes, and snippets.

@kylebakerio
Last active August 29, 2015 14:25
Show Gist options
  • Save kylebakerio/9e466eec0efdd0994b92 to your computer and use it in GitHub Desktop.
Save kylebakerio/9e466eec0efdd0994b92 to your computer and use it in GitHub Desktop.
function stringifyJSON(subject) {
var output = '';
var type = typeof subject;
if (type === 'number') {
return subject.toString();
} else if (subject === null) {
return 'null';
} else if (type === "boolean") {
return subject.toString();
} else if (type === "string") {
return ('"' + (subject) + '"')
} else if (Object.prototype.toString.call(subject) === '[object Array]') {
var index = subject.length;
output += '[';
subject.forEach(function(val){
if (typeof val === "number") {
// because for some reason we stringify numbers outside of the arrays,
// but not inside the arrays... ok... talk about a 'gotcha'. O_o;
output += val;
} else {
// let all other values in the array be stringified according to the rules above.
output += stringifyJSON(val);
}
index--;
if (index > 0) {output = output.concat(",")}
});
output += ']';
return output;
} else if (Object.prototype.toString.call(subject) === '[object Object]') {
var index = Object.keys(subject).length;
output += '{';
for (var key in subject) {
if ( !((key === 'functions') || (key === "undefined")) ) {
output += (stringifyJSON(key) + ":" + stringifyJSON(subject[key]))
index--;
if (index > 0) { output += "," }
}
}
output += '}';
}
return output;
}
///test values
var stringifiableObjects = [
9,
null,
true,
false,
"Hello world",
[],
[8],
["hi"],
[8, "hi"],
[1, 0, -1, -0.3, 0.3, 1343.32, 3345, 0.00011999999999999999],
[8, [[],3,4]],
[[[["foo"]]]],
{},
{"a": "apple"},
{"foo": true, "bar": false, "baz": null},
{"boolean, true": true, "boolean, false": false, "null": null },
// basic nesting
{"a":{"b":"c"}},
{"a":["b", "c"]},
[{"a":"b"}, {"c":"d"}],
{"a":[],"c": {}, "b": true}
];
var unstringifiableValues = [
{
'functions': function(){},
'undefined': undefined
}
];
//
// start tests
//
var passed = 0, failed = 0;
unstringifiableValues.concat(stringifiableObjects).reverse().forEach(function(val){
JSON.stringify(val) === stringifyJSON(val) ?
passed++ : (failed++,
console.log("what type is it? " + typeof val),
console.log(Object.prototype.toString.call(val)),
// console.log("which statement did it hit? " + hit);
console.log("original input to be stringified:"),
console.dir(val),
console.log("which should be turned into:"),
console.dir(JSON.stringify(val)),
console.log("this is what my script currently turns it into:"),
console.dir(stringifyJSON(val)),
console.log("---- \n")
)
})
console.log("Passed " + passed + " out of " + (passed + failed) + "; failed " + failed)
@kylebakerio
Copy link
Author

Went back and polished both the code and the text, after lessons learned from making a ternary version.

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