2016-08-01 5 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- string-in-javascript) – eclarkso

答えて

2

を:

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

この試してください:あなたの第三json_stringはあなたもエラーをチェックする必要が無効なため

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

これは文字列をチェックするだけで、JSONをチェックしません。 –

+0

であり、 'typeof json_string ==" object "' – 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));

関連する問題