使用chrome.storage.local.set时JSON对象受到损坏
从chrome.storage.local检索复杂JSON对象时,该对象正在中断 mock.json } 我正在使用 为什么它在我获取对象时工作,而在我检索对象时不工作。我尝试在JSON.stringify之后存储它。我尝试在JSON.parsing之后使用它,它返回 VM6:1未捕获的语法错误:JSON中位置1处的意外标记o 在JSON.parse()处 表示它已经是一个JS对象。使用chrome.storage.local.set时JSON对象受到损坏,json,google-chrome-extension,Json,Google Chrome Extension,从chrome.storage.local检索复杂JSON对象时,该对象正在中断 mock.json } 我正在使用 为什么它在我获取对象时工作,而在我检索对象时不工作。我尝试在JSON.stringify之后存储它。我尝试在JSON.parsing之后使用它,它返回 VM6:1未捕获的语法错误:JSON中位置1处的意外标记o 在JSON.parse()处 表示它已经是一个JS对象。 我试过使用点符号和括号符号,但不起作用。当我将它作为var data={//json here}存储在chrom
我试过使用点符号和括号符号,但不起作用。当我将它作为var data={//json here}存储在chrome控制台中时,它就可以工作了。但不是活着。没有帮到我 代码中存在多个问题
fetch
和chrome.storage
都是异步的,因此chrome.storage.local.get
将在设置数据之前运行,并且不会看到正确的数据
waitfunction()
不会等待任何东西,它不会影响之前或之后的异步代码
chrome.storage.local.get('StoredJson',callback)
将数据读取到名为StoredJson
的对象属性中,也就是说,您可以将值读取为result.StoredJson
async/await
:
(异步()=>{
试一试{
const data=await(await fetch('./mock.json')).json();
log('Fetched',data);
等待写入存储区({StoredJson:data});
const{StoredJson}=await readStorage('StoredJson');
console.log('Stored',StoredJson);
}捕捉(错误){
控制台日志(err);
}
})();
函数读取存储(键){
返回新承诺(解决=>{
chrome.storage.local.get(key,resolve);
});
}
函数writestrage(数据){
返回新承诺(解决=>{
chrome.storage.local.set(数据,解析);
});
}
在将对象存储到chrome.storage
之前,不需要对其进行字符串化。您可以直接执行此操作:chrome.storage.local.set({'StoredJson':data})
。请不要在问题中编辑解决方案公告。而是创建一个答案,或者接受现有答案。TL;4号博士是主要问题。谢谢你的回复。1.我尝试了JSON.stringify和JSON.parse的每一种组合,我试图传达这一点,但我没有,这是我的错。2.我知道它们是异步的。我有一个混乱的settimeout系统现在在我的真实代码中工作,我试图简化它来解决这个问题。3.假设wait函数起作用,这不应该阻止代码在它之后运行吗?。4.是的,我把它搞砸了,我已经把它修好了,但现在当我读这个对象时,它是字符串类型的。JSON.parse修复了它。(2天令人沮丧的错误,真的
{
"ThingOne" : [
"a",
"b"
],
"ThineTwo" : [
"a",
"b"
],
"People" : {
"FamilyOne" : {
"AgeOne" : "3",
"AgeTwo" : "8"
}
},
"Hats" : ["blue", "red", "green"]
fetch('./mock.json').then(response => {
console.log(response);
return response.json();
}).then(data => {
//data == the whole json file
var data2 = JSON.stringify(data);
chrome.storage.local.set({'StoredJson': data2});
//here this is the result of this code
//console.log(data2.ThingOne[0]);
//outputs => "a"
}).catch(err => {
console.log("Error Reading data " + err);
});
waitfunction();
chrome.storage.local.get('StoredJson', function(result) {
console.log("from get ------"); //outputs below
console.log(result); //{Data: ""{\"ThingOneOne\":[\"a\",\"b\"],\...
console.log(typeof result); //object
console.log(typeof result.ThingOne);//undefined
//https://imgur.com/OF7pVQQ
});