简体   繁体   中英

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

I store user's basket in localStorage (he can have more than one item):

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

if the user got two items, my json look like that:

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

I print it in console log with:

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

As I understand, this print it as a String. I'm trying to make it an Object to use the data somewhere else with myObject[propertyName] but when I try to PARSE with getItem() :

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

I receive an error:

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

Is it due to the fact that there is 2 Objects in my Json? How can I split the objects?

I made a jsfiddle: https://jsfiddle.net/Demky/4ea1s3rn/28/ (you need to open console to see result)

  • save data

  • read dada

  • crash when it try to json.parse

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

let me know if I can make my question more clear.

When you store array in local storage you need to first stringify that data then store. Like this.

 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 does not let you store objects. So instead you should stringify the whole object and then get it. It should work.

You should stringify the whole Array instead of each item of the array while storing it in localstorage.

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

Here's the updated fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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