我有一个简单的AJAX调用,服务器将返回一个带有有用数据的JSON字符串或一个由PHP函数mysql_error()产生的错误消息字符串。如何测试该数据是JSON字符串还是错误消息。

使用一个名为isJSON的函数会很好,就像你可以使用instanceof函数来测试某个东西是否是数组一样。

这就是我想要的:

if (isJSON(data)){
    //do some data stuff
}else{
    //report the error
    alert(data);
}

当前回答

嗯…这取决于你接收数据的方式。我认为服务器正在响应一个JSON格式 字符串(在PHP中使用json_encode(),例如)。如果你正在使用JQuery post并将响应数据设置为JSON格式,并且它是一个格式错误的JSON,这将产生一个错误:

$.ajax({
  type: 'POST',
  url: 'test2.php',
  data: "data",
  success: function (response){

        //Supposing x is a JSON property...
        alert(response.x);

  },
  dataType: 'json',
  //Invalid JSON
  error: function (){ alert("error!"); }
});

但是,如果你使用类型响应作为文本,你需要使用$. parsejson。根据jquery网站: “传递一个格式错误的JSON字符串可能导致抛出异常”。因此你的代码将是:

$.ajax({
  type: 'POST',
  url: 'test2.php',
  data: "data",
  success: function (response){

        try {
            parsedData = JSON.parse(response);
        } catch (e) {
            // is not a valid JSON string
        }

  },
  dataType: 'text',
});

其他回答

我用了这个(有点混合了不同的答案,但不管怎样):

const isJSON = str => { If (typeof STR === 'string'){ 尝试{ JSON.parse (str) 还真 }捕捉(e) { } } 返回假 } [null, undefined, false, true, [], {}, ”,“asdf ', '{}', '[]', "{\" abc \”:2}”、“{\“abc \”,\“2 \“}”) .map(el => { console.log(' [>${el}<] - ${isJSON(el)} ') }) console.log ('-----------------')

var parsedData;

try {
    parsedData = JSON.parse(data)
} catch (e) {
    // is not a valid JSON string
}

但是,我建议你的http call / service应该总是以相同的格式返回一个数据。所以如果你有一个错误,那么你应该有一个JSON对象来包装这个错误:

{"error" : { "code" : 123, "message" : "Foo not supported" } } 

可能还会使用HTTP状态5xx代码。

如果服务器响应的是JSON,那么它会有一个application/ JSON内容类型,如果它响应的是纯文本消息,那么它应该有一个文本/纯内容类型。确保服务器响应正确的内容类型并进行测试。

所有json字符串都以'{'或'['开头,并以相应的'}'或']'结尾,所以只需检查一下。

Angular.js是这样做的:

var JSON_START = /^\[|^\{(?!\{)/;
var JSON_ENDS = {
  '[': /]$/,
  '{': /}$/
};

function isJsonLike(str) {
    var jsonStart = str.match(JSON_START);
    return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
}

https://github.com/angular/angular.js/blob/v1.6.x/src/ng/http.js

嗯…这取决于你接收数据的方式。我认为服务器正在响应一个JSON格式 字符串(在PHP中使用json_encode(),例如)。如果你正在使用JQuery post并将响应数据设置为JSON格式,并且它是一个格式错误的JSON,这将产生一个错误:

$.ajax({
  type: 'POST',
  url: 'test2.php',
  data: "data",
  success: function (response){

        //Supposing x is a JSON property...
        alert(response.x);

  },
  dataType: 'json',
  //Invalid JSON
  error: function (){ alert("error!"); }
});

但是,如果你使用类型响应作为文本,你需要使用$. parsejson。根据jquery网站: “传递一个格式错误的JSON字符串可能导致抛出异常”。因此你的代码将是:

$.ajax({
  type: 'POST',
  url: 'test2.php',
  data: "data",
  success: function (response){

        try {
            parsedData = JSON.parse(response);
        } catch (e) {
            // is not a valid JSON string
        }

  },
  dataType: 'text',
});