javascript check if json is valid code example

Example 1: if json valide js

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

Example 2: javascript is valid json string

function isValidJSONString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}
//usage
var personJSONString = '{"first_name":"Tony","last_name":"Hawk","age":31}';
if(isValidJSONString(personJSONString)){
 //cool we are valid, lets parse
 var person= JSON.parse(personJSONString);
}

Example 3: javascript json trypass

Uncaught SyntaxError: Unexpected token c in JSON at position 1