Last active
February 26, 2016 10:56
-
-
Save 1nstinct/3d6ea5f24f931ea2fdc3 to your computer and use it in GitHub Desktop.
JS code example for custom JSON parser for parsing string if you exactly don't know that string in "like json" format.
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
var Parse = function(string) { | |
try { | |
var object = JSON.parse(string); | |
if(typeof(object) == 'object' || typeof(object) == 'array') | |
return object; // return converted object | |
if(typeof(object) == 'number') | |
return string; // return number string | |
} catch (err) { | |
if(err.constructor == SyntaxError && typeof(string) == 'string') { | |
return string; // return string as it is | |
} | |
} | |
}; | |
var str = '222kkk'; // can be like 'kkk', ['kkk'], "{\"kkk\":111}", 222 | |
console.log(Parse(str)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment