我知道这是一个非常古老的问题,答案很好。但是,似乎仍然可以将我的 2¢ 添加到其中。
假设您尝试测试的不是 JSON 对象本身,而是格式化为 JSON 的字符串(您的 似乎就是这种情况var data
),您可以使用以下返回布尔值的函数(是或不是 ' JSON'):
function isJsonString( jsonString ) {
// This function below ('printError') can be used to print details about the error, if any.
// Please, refer to the original article (see the end of this post)
// for more details. I suppressed details to keep the code clean.
//
let printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}
try {
JSON.parse( jsonString );
return true; // It's a valid JSON format
} catch (e) {
return false; // It's not a valid JSON format
}
}
以下是使用上述函数的一些示例:
console.log('\n1 -----------------');
let j = "abc";
console.log( j, isJsonString(j) );
console.log('\n2 -----------------');
j = `{"abc": "def"}`;
console.log( j, isJsonString(j) );
console.log('\n3 -----------------');
j = '{"abc": "def}';
console.log( j, isJsonString(j) );
console.log('\n4 -----------------');
j = '{}';
console.log( j, isJsonString(j) );
console.log('\n5 -----------------');
j = '[{}]';
console.log( j, isJsonString(j) );
console.log('\n6 -----------------');
j = '[{},]';
console.log( j, isJsonString(j) );
console.log('\n7 -----------------');
j = '[{"a":1, "b": 2}, {"c":3}]';
console.log( j, isJsonString(j) );
当您运行上面的代码时,您将得到以下结果:
1 -----------------
abc false
2 -----------------
{"abc": "def"} true
3 -----------------
{"abc": "def} false
4 -----------------
{} true
5 -----------------
[{}] true
6 -----------------
[{},] false
7 -----------------
[{"a":1, "b": 2}, {"c":3}] true
请尝试下面的代码段,让我们知道这是否适合您。:)
重要提示:本文中介绍的函数改编自https://airbrake.io/blog/javascript-error-handling/syntaxerror-json-parse-bad-parsing,您可以在其中找到有关 JSON.parse 的更多有趣的详细信息( ) 功能。
function isJsonString( jsonString ) {
let printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}
try {
JSON.parse( jsonString );
return true; // It's a valid JSON format
} catch (e) {
return false; // It's not a valid JSON format
}
}
console.log('\n1 -----------------');
let j = "abc";
console.log( j, isJsonString(j) );
console.log('\n2 -----------------');
j = `{"abc": "def"}`;
console.log( j, isJsonString(j) );
console.log('\n3 -----------------');
j = '{"abc": "def}';
console.log( j, isJsonString(j) );
console.log('\n4 -----------------');
j = '{}';
console.log( j, isJsonString(j) );
console.log('\n5 -----------------');
j = '[{}]';
console.log( j, isJsonString(j) );
console.log('\n6 -----------------');
j = '[{},]';
console.log( j, isJsonString(j) );
console.log('\n7 -----------------');
j = '[{"a":1, "b": 2}, {"c":3}]';
console.log( j, isJsonString(j) );