0

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?

5
  • 1
    You'd have to write your own parser. Commented Sep 5, 2014 at 18:04
  • Nope. Unless you want to write your own parser. Commented Sep 5, 2014 at 18:04
  • 5
    no. json is either syntactically valid, or it's not json. you'd have to extract the individual bits manually, or "fix" the string so it becomes valid json. Commented Sep 5, 2014 at 18:04
  • 1
    Have you tried fixing the source that provides this data? Why is it not providing "" where there is no value? Commented Sep 5, 2014 at 18:05
  • For it to be parsed it must be a valid JSON string, unless you somehow "fix" it before feeding it into the parser. Commented Sep 5, 2014 at 18:07

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.