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)。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架