How to store and retrieve JSON data into local storage?

后端 未结 5 933
迷失自我
迷失自我 2020-12-28 09:28

I have this code:

var string = \'{\"items\":[{\"Desc\":\"Item1\"},{\"Desc\":\"Item2\"}]}\';
localStorage.setItem(\'added-items\', JSON.stringify(string));
         


        
5条回答
  •  猫巷女王i
    2020-12-28 10:32

    var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
    localStorage.setItem('added-items', JSON.stringify(string));
    

    stringify means, take an object and return its presentation as a string. What you have, is already a string and not a JSON object.

    The opposite is JSON.parse which takes a string and turns it into an object.

    Neither of them have anything to do with getting the size of an array. When properly coding JavaScript you almost never use JSON.parse or JSON.stringify. Only if serialization is explicitly wanted.

    Use length for the size of the array:

    var obj = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
    console.debug(obj.items.length);
    

提交回复
热议问题