随笔 - 424  文章 - 0  评论 - 13  阅读 - 90万

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

  详细的描述见: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)。

       

  

posted on   lnlvinso  阅读(42283)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示