Created
March 19, 2014 03:22
-
-
Save GZShi/9634937 to your computer and use it in GitHub Desktop.
Stringing JSON for stupid browsers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function stringifyJSON(obj) { | |
var keyValuePair = []; | |
switch(Object.prototype.toString.call(obj)) { | |
case '[object Object]': | |
for(var i in obj) { | |
if(obj.hasOwnProperty(i)) { | |
keyValuePair.push('"' + i + '":' + stringifyJSON(obj[i])); | |
} | |
} | |
return '{' + keyValuePair.join(',') + '}'; | |
case '[object Array]': | |
for(var i = 0, len = obj.length; i < len; ++i) { | |
keyValuePair.push(stringifyJSON(obj[i])); | |
} | |
return '[' + keyValuePair.join(',') + ']'; | |
case '[object String]': | |
return '"' + obj.toString() + '"'; | |
default: | |
return '' + obj; | |
} | |
} | |
// test case | |
var testCase = { | |
num: 1234, | |
obj: { | |
num: 1224, | |
arr: [1,2,3,4,5], | |
mixarr: [1, '2', "3"] | |
}, | |
arr: [{a:1}, {b:2}, true, false], | |
bool: true | |
}; | |
var standare = JSON.stringify(testCase); | |
var output = stringifyJSON(testCase); | |
console.log(standare); | |
console.log(output); | |
console.log(standare === output); | |
console.time('JSON.stringify'); | |
for(var i = 0; i < 0xfffff; ++i) | |
JSON.stringify(testCase); | |
console.timeEnd('JSON.stringify'); | |
console.time('stringifyJSON'); | |
for(var i = 0; i < 0xfffff; ++i) | |
stringifyJSON(testCase); | |
console.timeEnd('stringifyJSON'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment