json.stringify
by xdumaine
HTML
<div class="test-case">Test Results:</div>
CSS
.test-case {
border: 1px solid black;
padding: 5px 10px;
}
.test-case.pass {
background-color: #DCF5DD;
color: #006E04;
}
.test-case.fail {
background-color: #F5DCDC;
color: #800000;
}
JavaScript
var jsonStringify = function (obj) {
if (typeof obj === 'number') {
return obj;
}
if (typeof obj === 'string') {
return '"' + obj + '"';
}
if (typeof obj === 'object') {
var str = '{';
for (var key in obj) {
str += '"' + key + '":' + jsonStringify(obj[key]) + ',';
}
str += '}';
return str.replace(/,}/g, '}');
}
console.log('unknown object type', obj, typeof obj);
};
var testObjects = [
'string',
43,
[1, 2, 3],
{ foo: 'bar' },
{ foo: { bar: 'baz' } },
[ 1, 2, [ 3 ] ],
{ foo: [ 1, 2, 3, 'string' ] },
{ foo: [ 1, 2, 3, { foo: 'bar' } ] },
null,
{ foo: undefined },
{
a: null,
b: 1,
c: 'test',
d: '',
e: {
e1: 'test2',
e2: 'test3',
e3: undefined,
e4: [
1,
2,
3,
'test4', {
e4i: 'test',
e4ii: {
e42iia: [1, 2, 3, [4, 5, 6, [7, 8, 9]]]
}
}]
},
f: [1, 2, 3, 4]
}
];
for (var i = 0; i < testObjects.length; i++) {
var result = jsonStringify(testObjects[i]);
var correctResult = JSON.stringify(testObjects[i]);
assertEqual(result, correctResult, result === correctResult);
}
function testDisplay(resultClass, message) {
var div = document.createElement('div');
div.classList.add('test-case');
div.classList.add(resultClass);
div.innerHTML = message;
return div;
}
function assertEqual(result, expected, pass, testCaseMessage) {
var message,
resultClass;
if (pass) {
message = result + ' - pass';
resultClass = 'pass';
} else {
message = testCaseMessage + ': fail - expected(' + expected + '), got (' + result + ')';
resultClass = 'fail'
}
var resultDisplay = testDisplay(resultClass, message);
document.body.appendChild(resultDisplay);
}