繁体   English   中英

local-storage javascript: How can I split 1 JSON containing 2 object into 2 JSON (1 per object?)

[英]local-storage javascript : How can I split 1 JSON containing 2 object into 2 JSON (1 per object?)

我将用户的购物篮存储在 localStorage 中(他可以拥有多个项目):

 let data = [];
 for (i = 0; i < rows.length - 1; i++) {
    let info = {
      "price": price,
      "quantity": quantity,
      "priceTotal": priceTotal
    };
    data.push(JSON.stringify(info));
  }
  localStorage.setItem("reservations", data);
}

如果用户有两个项目,我的 json 看起来像这样:

{"price":"10 €", "quantity":"1", "priceTotal":"10 €"},{"price":"20 €", "quantity":"2", "priceTotal":"40 €"}

我在控制台日志中打印它:

let info = localStorage.getItem("reservations");
console.log(info);

据我了解,这会将其打印为字符串。 我正在尝试将其设置为PARSE以在其他地方使用myObject[propertyName]的数据,但是当我尝试使用getItem()解析时:

  let myObject = JSON.parse(window.localStorage.getItem('reservations'));

我收到一个错误:

VM8224:1 Uncaught SyntaxError: Unexpected token, in JSON at position 123 at JSON.parse ()

是因为我的 Json 中有 2 个对象吗? 如何拆分对象?

我做了一个jsfiddle: https://jsfiddle.net/Demky/4ea1s3rn/28/ (你需要打开控制台才能看到结果)

  • 保存数据

  • 读达达

  • 尝试 json.parse 时崩溃

    VM516:1 Uncaught SyntaxError: Unexpected token, in JSON at position 51 at JSON.parse`

让我知道我是否可以让我的问题更清楚。

当您将数组存储在本地存储中时,您需要首先将该数据字符串化然后存储。 像这样。

 localStorage.setItem("reservations", JSON.stringify(data));

 let data = [];
 for (i = 0; i < rows.length - 1; i++) {
    let info = {
      "price": price,
      "quantity": quantity,
      "priceTotal": priceTotal
    };
    data.push(info);
  }
  localStorage.setItem("reservations", JSON.stringify(data));
}

let myObject = JSON.parse(window.localStorage.getItem('reservations'));

localStorage.setItem 不允许您存储对象。 因此,您应该将整个 object 字符串化,然后获取它。 它应该工作。

在将其存储在本地存储中时,您应该对整个数组而不是数组的每个项目进行字符串化。

 let data = [];
 for (i = 0; i < rows.length - 1; i++) {
    let info = {
      "price": price,
      "quantity": quantity,
      "priceTotal": priceTotal
    };
    data.push(info);
  }
  localStorage.setItem("reservations", JSON.stringify(data));
}

这是更新的小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM