1

Have tried :

function isJSON(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

To check weather a string is json or not. It returns true for boolean type formats.

Is there any possible way to identify a valid json string in Java Script or in JQuery?

3
  • what do you mean by boolean type formats? Commented Aug 16, 2016 at 10:16
  • He means isJSON(false) returns true. Commented Aug 16, 2016 at 10:17
  • Yeah you were right Jeremy Thille Commented Aug 16, 2016 at 11:03

2 Answers 2

8

To assure you have a valid json you must have a string first

function isJSON(str) {

    if( typeof( str ) !== 'string' ) { 
        return false;
    }
    try {
        JSON.parse(str);
        return true;
    } catch (e) {
        return false;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Your function works, just add a boolean check :

function isJSON(str) {

    if(typeof(str) === "boolean"){ return false; } // or if(typeof(str) !== "string")

    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

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.