不能簡單地使用來判斷字符串是否是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
詳細的描述見:https://segmentfault.com/q/1010000008460413
我們可以使用如下的方法來判斷:
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"
上面的這段代碼來自:https://www.cnblogs.com/lanleiming/p/7096973.html。 文章中有詳細的描述,代碼的正確性。
JSON數據格式,主要由對象 { } 和數組 [ ] 組成。平時中我們用的基本上是對象,但是我們不能忘了數組也是json的數據格式。例如[ "Google", "Runoob", "Taobao" ]。
JSON 數組在中括號中書寫。
JSON 中數組值必須是合法的 json數據類型(字符串, 數字, 對象, 數組, 布爾值或 null)。