判斷方法:首先使用“JSON.parse(str)”語句解析指定數據str;然后使用“if(typeof obj =='object'&&obj)”語句判斷解析后數據的類型是否為“object”類型;如果是,則str數據是json格式。
本教程操作環境:windows7系統、javascript1.8.5版、Dell G3電腦。
js判斷字符串是否為JSON格式
不能簡單地使用來判斷字符串是否是JSON格式:
function isJSON(str) { if (typeof str == 'string') { try { JSON.parse(str); return true; } catch(e) { console.log(e); return false; } } console.log('It is not a string!') }
以上try/catch
的確實不能完全檢驗一個字符串是JSON
格式的字符串,有許多例外:
JSON.parse('123'); // 123 JSON.parse('{}'); // {} JSON.parse('true'); // true JSON.parse('"foo"'); // "foo" JSON.parse('[1, 5, "false"]'); // [1, 5, "false"] JSON.parse('null'); // null
我們知道,JS中的數據類型分為:字符串、數字、布爾、數組、對象、Null、Undefined。
我們可以使用如下的方法來判斷:
function isJSON(str) { if (typeof str == 'string') { try { var obj=JSON.parse(str); if(typeof obj == 'object' && obj ){ return true; }else{ return false; } } catch(e) { console.log('error:'+str+'!!!'+e); return false; } } console.log('It is not a string!') } console.log('123 is json? ' + isJSON('123')) console.log('{} is json? ' + isJSON('{}')) console.log('true is json? ' + isJSON('true')) console.log('foo is json? ' + isJSON('"foo"')) console.log('[1, 5, "false"] is json? ' + isJSON('[1, 5, "false"]')) console.log('null is json? ' + isJSON('null')) console.log('["1{211323}","2"] is json? ' + isJSON('["1{211323}","2"]')) console.log('[{},"2"] is json? ' + isJSON('[{},"2"]')) console.log('[[{},{"2":"3"}],"2"] is json? ' + isJSON('[[{},{"2":"3"}],"2"]'))
運行結果為:
> "123 is json? false" > "{} is json? true" > "true is json? false" > "foo is json? false" > "[1, 5, "false"] is json? true" > "null is json? false" > "["1{211323}","2"] is json? true" > "[{},"2"] is json? true" > "[[{},{"2":"3"}],"2"] is json? true"
所以得出以下結論:
JSON.parse() 方法用來解析JSON字符串,json.parse()將字符串轉成json對象
如果JSON.parse能夠轉換成功;并且轉換后的類型為object 且不等于 null,那么這個字符串就是JSON格式的字符串。
JSON.parse():
JSON 通常用于與服務端交換數據。
在接收服務器數據時一般是字符串。
我們可以使用 JSON.parse() 方法將數據轉換為 JavaScript 對象。
語法:
JSON.parse(text[, reviver])
參數說明:
-
text:必需, 一個有效的 JSON 字符串。
-
reviver: 可選,一個轉換結果的函數, 將為對象的每個成員調用此函數。
解析前要確保你的數據是標準的 JSON 格式,否則會解析出錯。