Reputation: 6206
I need to parse a json string with JSON.parse() but somethimes the input is not in the full format. for examle:
{
"x" : "x",
"x1" : "x1",
"x2" : "x2,
"x3" :
And the parsing is breaking obviously. But in this case I want to "save" the valid rows.
Is it possible?
Upvotes: 0
Views: 95
Reputation: 25659
Here is what you can do:
String.prototype.safeParser = function(){
try{
var that=this;
return JSON.parse(this);
}
catch(err){
if(this.length<3){
return {};
}
else if(this.charAt(this.length - 1) == "}"){
that = this.substring(0, this.length - 2) + "}";
}
else{
that = this.substring(0, this.length - 1) + "}";
}
return that.safeParser();
}
}
and use it like console.log(json_string.safeParser());
It checks whether the string is valid json, if it is not, it looks if it ends with curly braces, it removes one character at a time until it is valid json.
Note: this specific code only works for objects with curly braces, not arrays with square brackets. However, this might not be too hard to implement.
JS Fiddle Demo
(open your console)
Upvotes: 1