javascript check if string is json code example
Example 1: javascript check if string is json parsable
var isJsonParsable = string => {
try {
JSON.parse(string);
} 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;
}
var personJSONString = '{"first_name":"Tony","last_name":"Hawk","age":31}';
if(isValidJSONString(personJSONString)){
var person= JSON.parse(personJSONString);
}
Example 3: check if the data can be parsed javascript
function isJson(str) {
try {
return JSON.parse(str);
} catch (e) {
return false;
}
}