2016-08-01 132 views
0

是否可以检查变量中的数据是字符串还是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或未定义时。

当我们需要使用JSON.parse?

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

+1

'typeof运算json_string'。 –

+0

[如何检查var是否是JavaScript中的字符串?](http://stackoverflow.com/questions/6286542/how-can-i-check-if-a-var-is-a-字符串在JavaScript) – eclarkso

回答

2

,因为你的第3 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 
2

试试这个:

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

它只会检查其字符串或不,但它不检查JSON。 –

+0

这将是'typeof json_string ==“对象” – stackoverfloweth

0

有没有真正这样的东西'JSON对象。一旦JSON字符串被成功解码,它就变成了一个对象,一个数组或一个基元(字符串,数字等)。

不过,你可能想知道一个字符串是否是一个有效的JSON字符串:

var string1 = '{ "key": 1, "key2": "2" }'; 
 
var string2 = 'Hello World!'; 
 
var object = { "key": 1, "key2": "2" }; 
 
var number = 123; 
 

 
function test(data) { 
 
    switch(typeof data) { 
 
    case 'string': 
 
     try { 
 
     JSON.parse(data); 
 
     } catch (e) { 
 
     return "This is a string"; 
 
     } 
 
     return "This is a JSON string"; 
 

 
    case 'object': 
 
     return "This is an object"; 
 
     
 
    default: 
 
     return "This is something else"; 
 
    } 
 
} 
 

 
console.log(test(string1)); 
 
console.log(test(string2)); 
 
console.log(test(object)); 
 
console.log(test(number));

0

要检查变量类型,你可以使用typeof运算符

,以及用于将一个有效的串化JSON对象,你可以使用以下功能

如果一个变量是对象,那么它不会做任何事情并返回相同的对象。

但如果它是一个字符串,那么它会尝试将其转换为对象并返回。

function getJSON(d) { 
 
    var jsonObject; 
 
    jsonObject = d; 
 
    if (typeof d === 'string') { 
 
     try { 
 
     jsonObject = JSON.parse(d); 
 
     } catch (Ex) { 
 
     jsonObject = undefined; 
 
     console.log("d " ,d, 'Error in parsing', Ex); 
 
     } 
 
    } 
 
    return jsonObject; 
 
    }; 
 
    var obj = {a:2, b:3}; 
 
    var stringified_obj = JSON.stringify(obj); 
 
    console.log(obj); 
 
    console.log(getJSON(stringified_obj));

相关问题