Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 1nstinct/3d6ea5f24f931ea2fdc3 to your computer and use it in GitHub Desktop.
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.
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