json parse if json code example
Example 1: 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 2: json parse returns object
var str = '[{"UserName":"xxx","Rolename":"yyy"}]';
var parsed = JSON.parse(str);
var user = parsed[0];
console.log(user.UserName);
console.log(user.Rolename);