How to store and retrieve JSON data into local storage?

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

I have this code:

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


        
5条回答
  •  遥遥无期
    2020-12-28 10:31

    To bring clarity to future people that may stumble across this question and found the accepted answer to not be everything you hoped and dreamed for:

    I've extended the question so that the user may either want to input a string or JSON into localStorage.

    Included are two functions, AddToLocalStorage(data) and GetFromLocalStorage(key).

    With AddToLocalStorage(data), if your input is not a string (such as JSON), then it will be converted into one.

    GetFromLocalStorage(key) retrieves the data from localStorage of said key

    The end of the script shows an example of how to examine and alter the data within JSON. Because it is a combination of objects and array, one must use a combination of . and [] where they are applicable.

    var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
    var json = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"firstName":"John"},{"lastName":"Smith"}]};
    
    localStorage.setItem('added-items', AddToLocalStorage(string));
    localStorage.setItem('added-items', AddToLocalStorage(json));
    
    // this function converts JSON into string to be entered into localStorage
    function AddToLocalStorage(data) {
      if (typeof data != "string") {data = JSON.stringify(data);}
      return data;
    }
    
    // this function gets string from localStorage and converts it into JSON
    function GetFromLocalStorage(key) {
      return JSON.parse(localStorage.getItem(key));
    }
    
    var myData = GetFromLocalStorage("added-items");
    
    console.log(myData.items[2].firstName)    // "John"
    
    myData.items[2].firstName = ["John","Elizabeth"];
    myData.items[2].lastName = ["Smith","Howard"];
    
    console.log(myData.items[2])    // {"firstName":["John","Elizabeth"],"lastName":["Smith","Howard"]}
    
    console.log(myData.items.length)    // 4

提交回复
热议问题