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

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

    If you're dealing with a response from an AJAX (or XMLHttpRequest) call, what worked for me is to check the response content type and parse or not the content accordingly.

提交回复
热议问题