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

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

这就是我想要的:

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

当前回答

如果你不介意的话

npm i -S lodash

const isPlainObject = require("lodash/isPlainObject"); // cjs
// import {isPlainObject} from "lodash"; // esm
function checkIfJSON(input) {
  const inputStr = typeof input === "string" ? input : JSON.stringify(input);
  try {
    if (isPlainObject(JSON.parse(inputStr))) {
      return true;
    }
  } catch (e) {
    return false;
  }
}

其他回答

嗯…这取决于你接收数据的方式。我认为服务器正在响应一个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',
});

使用JSON.parse

function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

这段代码是JSON.parse(1234)或JSON.parse(0)或JSON.parse(false)或JSON.parse(null)都会返回true。

function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

所以我这样重写了代码:

function isJson(item) {
    item = typeof item !== "string"
        ? JSON.stringify(item)
        : item;

    try {
        item = JSON.parse(item);
    } catch (e) {
        return false;
    }

    if (typeof item === "object" && item !== null) {
        return true;
    }

    return false;
}

测试结果:

isJson测试结果

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

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 ('-----------------')

当使用jQuery $.ajax()响应将有responseJSON属性,如果响应是JSON,这可以像这样测试:

if (xhr.hasOwnProperty('responseJSON')) {}