问题描述
大家好!
我在 ReactNative 应用程序的异步存储中存储了一个简单的对象。 但是当我取回它时,它没有被正确解析:所有键仍然有引号(在存储它时由 JSON.stringify() 添加)...
我这样存储数据:
const storeData = () => {
let myData = {
title: 'Hummus',price: '6.90',id: '1'
}
AsyncStorage.setItem('@storage_Key',JSON.stringify(myData));
}
然后像这样访问数据:
const getData= async () => {
const jsonValue = await AsyncStorage.getItem('@storage_Key')
console.log(jsonValue);
return JSON.parse(jsonValue);
}
解析后我的对象看起来像这样:
{"title":"Hummus","price":"6.90","id":"1"}
知道为什么不从键中删除引号吗??
解决方法
那是因为 JSON specification 说键应该是字符串。您使用的是 JSON 的现代表示形式,称为 JSON5 (https://json5.org/)。 JSON5 是 JSON 规范的超集,在某些情况下不需要用引号将键括起来。当您进行字符串化时,它会以 JSON 格式返回结果。
JSON 和 JSON5 在现代浏览器中同样有效。因此,您不必担心因为它们看起来不同而以编程方式破坏任何东西。
您可以使用如下所示的 JSON5,它会为您提供所需的字符串化结果。
let myData = {
title: 'Hummus',price: '6.90',id: '1'
}
console.log(JSON5.stringify(myData));
console.log(JSON.stringify(myData));
<script src="https://unpkg.com/json5@^2.0.0/dist/index.min.js"></script>
像这样:
// JSON5.stringify
{title:'Hummus',price:'6.90',id:'1'}
// JSON.stringify
{"title":"Hummus","price":"6.90","id":"1"}