【js】判斷一個字符串是否是json


根據如下情況展示內容

//情況一:
var content = "<p>武漢加油</p><div>戰勝疫情</div>"

//情況二:
var content1 = '[{"name":"wwww","url":""},{"name":"","url":"圖片地址XXXXXX"}]'

解決方案:判斷是否是json

//情況一:
var content = "<p>武漢加油</p><div>戰勝疫情</div>";

//情況二:
var content1 = '[{"name":"wwwwwwwwwwwwwwww","url":""},{"name":"","url":"http: \/\/xxx.xxx.com\/xxxx\/xxx\/e\/0\/e0\/fil\/2020\/03\/31\/158562388310695\/158562388368323.png"}]';
//判斷是否是json對象
var isJSON = function (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(isJSON(content)); 
console.log(isJSON(content1));

效果:

 

ps:

  • 如果JSON.parse能夠轉換成功;並且轉換后的類型為object 且不等於 null,那么這個字符串就是JSON格式的字符串。
  • 正確的JSON格式有:  數組、空對象、json  

 

 

相關資料:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM