如何检查变量包含的是JSON对象还是字符串?

14 浏览
0 Comments

如何检查变量包含的是JSON对象还是字符串?

可以检查一个变量中的数据是字符串还是JSON对象吗?

var json_string = '{ "key": 1, "key2": "2" }';
var json_string = { "key": 1, "key2": "2" };
var json_string = "{ 'key': 1, 'key2', 2 }";

当json_string.key2返回2或undefined时。

我们需要使用JSON.parse吗?

我如何检查哪个是字符串或JSON对象。

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

试试这个:

if(typeof json_string == "string"){
   json = JSON.parse(json_string);
}

0
0 Comments

由于您的第三个json_string是无效的,您还必须检查错误:

function checkJSON(json) {
 if (typeof json == 'object')
   return 'object';
 try {
   return (typeof JSON.parse(json));
 }
 catch(e) {
   return 'string';
 }
}
var json_string = '{ "key": 1, "key2": "2" }';
console.log(checkJSON(json_string));    //object
json_string = { "key": 1, "key2": "2" };
console.log(checkJSON(json_string));    //object
json_string = "{ 'key': 1, 'key2', 2 }";
console.log(checkJSON(json_string));    //string

0