js writes a function to determine whether a string can be converted to JSON

It's actually very simple.
Here we need to involve catching exceptions, because if you directly transfer it inside the if, I have tried it and it will directly report an error. It doesn't give
us any face. We write a function like this.

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

Write the following code

console.log(isJsonString('{"name":"John","age":30}'));
console.log(isJsonString('{name:"John",age:30}'));
console.log(isJsonString('Not a JSON string'));

Obviously, our first one complies with the json specification.
If the second json is written incorrectly, the third one is far behind.
Insert image description here
The function made the correct judgment smoothly and the error will not be exposed because of the existence of the caught exception.

Guess you like

Origin blog.csdn.net/weixin_45966674/article/details/132990881