Created
September 16, 2014 03:54
-
-
Save alexhawkins/931c0af2d827dd67a3e8 to your computer and use it in GitHub Desktop.
Recursive JSON.stringify implementation
This file contains hidden or 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
| //Recursive implementation of jSON.stringify; | |
| var stringifyJSON = function(obj) { | |
| var arrOfKeyVals = [], | |
| arrVals = [], | |
| objKeys = []; | |
| /*********CHECK FOR PRIMITIVE TYPES**********/ | |
| if (typeof obj === 'number' || typeof obj === 'boolean' || obj === null) | |
| return '' + obj; | |
| else if (typeof obj === 'string') | |
| return '"' + obj + '"'; | |
| /*********CHECK FOR ARRAY**********/ | |
| else if (Array.isArray(obj)) { | |
| //check for empty array | |
| if (obj[0] === undefined) | |
| return '[]'; | |
| else { | |
| obj.forEach(function(el) { | |
| arrVals.push(stringifyJSON(el)); | |
| }); | |
| return '[' + arrVals + ']'; | |
| } | |
| } | |
| /*********CHECK FOR OBJECT**********/ | |
| else if (obj instanceof Object) { | |
| //get object keys | |
| objKeys = Object.keys(obj); | |
| //set key output; | |
| objKeys.forEach(function(key) { | |
| var keyOut = '"' + key + '":'; | |
| var keyValOut = obj[key]; | |
| //skip functions and undefined properties | |
| if (keyValOut instanceof Function || typeof keyValOut === undefined) | |
| arrOfKeyVals.push(''); | |
| else if (typeof keyValOut === 'string') | |
| arrOfKeyVals.push(keyOut + '"' + keyValOut + '"'); | |
| else if (typeof keyValOut === 'boolean' || typeof keValOut === 'number' || keyValOut === null) | |
| arrOfKeyVals.push(keyOut + keyValOut); | |
| //check for nested objects, call recursively until no more objects | |
| else if (keyValOut instanceof Object) { | |
| arrOfKeyVals.push(keyOut + stringifyJSON(keyValOut)); | |
| } | |
| }); | |
| return '{' + arrOfKeyVals + '}'; | |
| } | |
| }; |
Thanks for the code. While using this I found that it does not handle below cases
- Object having an array
- String contains double quotes.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI, on line 40 there is a typo "keValOut" instead of "keyValOut".