如何测试一个字符串是否为JSON格式?

31 浏览
0 Comments

如何测试一个字符串是否为JSON格式?

我有一个简单的AJAX请求,服务器将返回一个JSON字符串,其中包含有用的数据或者由PHP函数mysql_error()生成的错误消息字符串。我要如何测试这个数据是一个JSON字符串还是一个错误消息。

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

这就是我想要的:

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

admin 更改状态以发布 2023年5月22日
0
0 Comments

使用 JSON.parse() 有一些缺点:

  1. JSON.parse(1234) 或者
  2. JSON.parse(0) 或者
  3. JSON.parse(false) 或者
  4. JSON.parse(null)

全部都会返回 true。

function isJson(str) {
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }  
  return true;
}
function testIsJson(value, expected) {
  console.log(`Expected: ${expected}, Actual: ${isJson(value)}`); 
}
// All of the following codes are expected to return false.
// But actually returns true.
testIsJson(1234, false);
testIsJson(0, false);
testIsJson(false, false);
testIsJson(null, false);

处理假阳性的代码

因此我将代码重新编写成了这样:

function isJson(item) {
  let value = typeof item !== "string" ? JSON.stringify(item) : item;    
  try {
    value = JSON.parse(value);
  } catch (e) {
    return false;
  }
  return typeof value === "object" && value !== null;
}

测试结果:

function isJson(item) {
  let value = typeof item !== "string" ? JSON.stringify(item) : item;
  try {
    value = JSON.parse(value);
  } catch (e) {
    return false;
  }
  return typeof value === "object" && value !== null;
}
function testIsJson(value, expected) {
  console.log(`Expected: ${expected}, Actual: ${isJson(value)}`);
}
const validJson = { "foo": "bar" };
const notValidJson = '{ "foo": "bar" } invalid';
// expected: true
testIsJson(validJson, true);
// expected: false
testIsJson(1234, false);
testIsJson(0, false);
testIsJson(notValidJson, false);
testIsJson(false, false);
testIsJson(null, false);

0
0 Comments

使用 JSON.parse

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

0