AJAX: Check if a string is JSON?

前端 未结 7 2067
甜味超标
甜味超标 2020-12-02 21:32

My JavaScript sometimes crashes on this line:

var json = eval(\'(\' + this.responseText + \')\');

Crashes are caused when the argument of <

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 22:18

    The problem with depending on the try-catch approach is that JSON.parse('123') = 123 and it will not throw an exception. Therefore, In addition to the try-catch, we need to check the type as follows:

    function isJsonStr(str) {
        var parsedStr = str;
        try {
            parsedStr = JSON.parse(str);
        } catch (e) {
            return false;
        }
        return typeof parsedStr == 'object'
    }
    

提交回复
热议问题