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

前端 未结 24 2092
暖寄归人
暖寄归人 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:34

    In prototypeJS, we have method isJSON. You can try that. Even json might help.

    "something".isJSON();
    // -> false
    "\"something\"".isJSON();
    // -> true
    "{ foo: 42 }".isJSON();
    // -> false
    "{ \"foo\": 42 }".isJSON();
    

提交回复
热议问题