判斷方法:首先使用“JSON.parse(str)”語句解析指定數(shù)據(jù)str;然后使用“if(typeof obj =='object'&&obj)”語句判斷解析后數(shù)據(jù)的類型是否為“object”類型;如果是,則str數(shù)據(jù)是json格式。
本教程操作環(huán)境:windows7系統(tǒng)、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中的數(shù)據(jù)類型分為:字符串、數(shù)字、布爾、數(shù)組、對象、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"]'))
運行結(jié)果為:
> "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"
所以得出以下結(jié)論:
JSON.parse() 方法用來解析JSON字符串,json.parse()將字符串轉(zhuǎn)成json對象
如果JSON.parse能夠轉(zhuǎn)換成功;并且轉(zhuǎn)換后的類型為object 且不等于 null,那么這個字符串就是JSON格式的字符串。
JSON.parse():
JSON 通常用于與服務(wù)端交換數(shù)據(jù)。
在接收服務(wù)器數(shù)據(jù)時一般是字符串。
我們可以使用 JSON.parse() 方法將數(shù)據(jù)轉(zhuǎn)換為 JavaScript 對象。
語法:
JSON.parse(text[, reviver])
參數(shù)說明:
-
text:必需, 一個有效的 JSON 字符串。
-
reviver: 可選,一個轉(zhuǎn)換結(jié)果的函數(shù), 將為對象的每個成員調(diào)用此函數(shù)。
解析前要確保你的數(shù)據(jù)是標(biāo)準(zhǔn)的 JSON 格式,否則會解析出錯。