首页 > 解决方案 > 为什么 JSON.parse() 不解析 JSON 对象的内部数组?

问题描述

有谁知道为什么我的 JSON.parse() 不能正常工作?我已经尝试了所有的调试工具,但它没有解析数组。

我的代码:

console.log(typeof(localStorage.array));
console.log(localStorage.array);
localStorageArray = JSON.parse(localStorage.array);
console.log(localStorageArray);

控制台:

String //line 1
[[{"color":"#000000","teacher":"ELA","tasks":[[{"selection":"homework","name":"HW 1","date":"2020-05-15","time":"16:05","marked":false}]]}]] //line 2
Array(1)
0: Array(1)
0:
color: "#000000"
tasks: Array(0)
length: 0
__proto__: Array(0)
teacher: "ELA"
__proto__: Object
length: 1
__proto__: Array(0)
length: 1
__proto__: Array(0) //The main thing here is that tasks.length == 0

标签: javascriptjson

解决方案


localStorage对象具有与普通 JavaScript 属性不同的自定义属性 getter/setter object

这在这里解释(强调我的):

https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API

键和值始终是字符串(请注意,与对象一样,整数键将自动转换为字符串)。

因此,当您从属性中检索值时localStorage,它将始终作为 a 返回string,即使您只是为属性设置了object值。

您应该更喜欢getItemandsetItem函数来避免这种自动字符串转换。


推荐阅读