博客
关于我
json.parse细节
阅读量:314 次
发布时间:2019-03-04

本文共 591 字,大约阅读时间需要 1 分钟。

在JavaScript中,字符串表示数组和对象的方式存在显著差异,这一点在实际开发中经常会被忽视。以下案例展示了两种结构在解析时的不同表现。

当使用单引号定义数组时,["a","b","c"],可以通过JSON.parse正确解析为数组:

let a = '["a","b","c"]';console.log(JSON.parse(a)); // Array

然而,当使用单引号定义对象时,{"name":"听风是风","age":"26"},同样可以通过JSON.parse正确解析为对象:

let a1 = '{"name":"听风是风","age":"26"}';console.log(JSON.parse(a1)); // Object

相比之下,当使用双引号定义数组或对象时,['a','b','c']{'name':'听风是风','age':'26'},则会导致JSON.parse解析失败:

let b = "['a','b','c']";console.log(JSON.parse(b)); // 错误let b1 = "{'name':'听风是风','age':'26'}";console.log(JSON.parse(b1)); // 错误

这种区分在实际编码中至关重要,尤其是在处理外部数据源或API响应时,正确理解数据结构是确保程序正常运行的关键。

转载地址:http://rnjq.baihongyu.com/

你可能感兴趣的文章
poj 3083 Children of the Candy Corn
查看>>
POJ 3083 Children of the Candy Corn 解题报告
查看>>
POJ 3253 Fence Repair C++ STL multiset 可解 (同51nod 1117 聪明的木匠)
查看>>
Qt笔记——控件总结
查看>>
poj 3262 Protecting the Flowers 贪心
查看>>
poj 3264(简单线段树)
查看>>
Qt笔记——布局管理三件套分割窗口、停靠窗口和堆栈窗口
查看>>
poj 3277 线段树
查看>>
POJ 3349 Snowflake Snow Snowflakes
查看>>
POJ 3411 DFS
查看>>
poj 3422 Kaka's Matrix Travels (费用流 + 拆点)
查看>>
Qt笔记——官方文档全局定义(二)Functions函数
查看>>
POJ 3468 A Simple Problem with Integers
查看>>
poj 3468 A Simple Problem with Integers 降维线段树
查看>>
poj 3468 A Simple Problem with Integers(线段树 插线问线)
查看>>
poj 3485 区间选点
查看>>
poj 3518 Prime Gap
查看>>
poj 3539 Elevator——同余类bfs
查看>>
Qt笔记——官方文档全局定义(三)Macros宏
查看>>
poj 3628 Bookshelf 2
查看>>