JSON 使用 chrome.storage.local.set 时对象损坏

JSON object getting damaged when using chrome.storage.local.set

从 chrome.storage.local 检索复杂的 JSON 对象时,对象正在损坏。

mock.json

{
"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
    });  

为什么在我获取对象时有效,但在检索对象时却无效。我试过在 JSON.stringifying 之后存储它。我尝试在 JSON.parsing 之后使用它 returns

VM6:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse ()

说明已经是JS对象了。 我试过使用点符号和括号符号它不起作用。当我将它作为 var data = {//json here} 存储在 chrome 控制台中时,它可以工作。但不是活着。 hasn't helped me. Picture of console

代码中存在多个问题。

  1. 不需要JSON.stringify。直接存储数据即可。

  2. fetchchrome.storage 都是异步的,因此您的 chrome.storage.local.get 将在数据设置之前 运行 并且它不会看到正确的数据。

  3. waitfunction();不会等待任何东西,它不会影响它之前或之后的异步代码。

  4. chrome.storage.local.get('StoredJson', callback) 将数据读入名为 StoredJson 的对象 属性 即您可以将值读取为 result.StoredJson.

总的来说,一个合适的现代解决方案是切换到 async/await:

(async () => {
  try {
    const data = await (await fetch('./mock.json')).json();
    console.log('Fetched', data);
    await writeStorage({StoredJson: data});
    const {StoredJson} = await readStorage('StoredJson');
    console.log('Stored', StoredJson);
  } catch (err) {
    console.log(err);
  }
})();

function readStorage(key) {
  return new Promise(resolve => {
    chrome.storage.local.get(key, resolve);
  });
}

function writeStorage(data) {
  return new Promise(resolve => {
    chrome.storage.local.set(data, resolve);
  });
}