亚洲最大看欧美片,亚洲图揄拍自拍另类图片,欧美精品v国产精品v呦,日本在线精品视频免费

  • 站長(zhǎng)資訊網(wǎng)
    最全最豐富的資訊網(wǎng)站

    javascript怎么判斷是否是json格式

    判斷方法:首先使用“JSON.parse(str)”語(yǔ)句解析指定數(shù)據(jù)str;然后使用“if(typeof obj =='object'&&obj)”語(yǔ)句判斷解析后數(shù)據(jù)的類(lèi)型是否為“object”類(lèi)型;如果是,則str數(shù)據(jù)是json格式。

    javascript怎么判斷是否是json格式

    本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版、Dell G3電腦。

    js判斷字符串是否為JSON格式

    不能簡(jiǎn)單地使用來(lái)判斷字符串是否是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的確實(shí)不能完全檢驗(yàn)一個(gè)字符串是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ù)類(lèi)型分為:字符串、數(shù)字、布爾、數(shù)組、對(duì)象、Null、Undefined。

    我們可以使用如下的方法來(lái)判斷:

    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"]'))

    運(yùn)行結(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() 方法用來(lái)解析JSON字符串,json.parse()將字符串轉(zhuǎn)成json對(duì)象

    如果JSON.parse能夠轉(zhuǎn)換成功;并且轉(zhuǎn)換后的類(lèi)型為object 且不等于 null,那么這個(gè)字符串就是JSON格式的字符串。

    JSON.parse():

    JSON 通常用于與服務(wù)端交換數(shù)據(jù)。

    在接收服務(wù)器數(shù)據(jù)時(shí)一般是字符串。

    我們可以使用 JSON.parse() 方法將數(shù)據(jù)轉(zhuǎn)換為 JavaScript 對(duì)象。

    語(yǔ)法:

    JSON.parse(text[, reviver])

    參數(shù)說(shuō)明:

    • text:必需, 一個(gè)有效的 JSON 字符串。

    • reviver: 可選,一個(gè)轉(zhuǎn)換結(jié)果的函數(shù), 將為對(duì)象的每個(gè)成員調(diào)用此函數(shù)。

    解析前要確保你的數(shù)據(jù)是標(biāo)準(zhǔn)的 JSON 格式,否則會(huì)解析出錯(cuò)。

    贊(0)
    分享到: 更多 (0)
    網(wǎng)站地圖   滬ICP備18035694號(hào)-2    滬公網(wǎng)安備31011702889846號(hào)