How to check if a string is a valid JSON string in JavaScript without using Try/Catch

前端 未结 24 2122
暖寄归人
暖寄归人 2020-11-22 07:50

Something like:

var jsonString = \'{ \"Id\": 1, \"Name\": \"Coke\" }\';

//should be true
IsJsonString(jsonString);

//should be false
IsJsonString(\"foo\");         


        
24条回答
  •  臣服心动
    2020-11-22 08:35

    I think I know why you want to avoid that. But maybe try & catch !== try & catch. ;o) This came into my mind:

    var json_verify = function(s){ try { JSON.parse(s); return true; } catch (e) { return false; }};
    

    So you may also dirty clip to the JSON object, like:

    JSON.verify = function(s){ try { JSON.parse(s); return true; } catch (e) { return false; }};
    

    As this as encapsuled as possible, it may not break on error.

提交回复
热议问题