How to store and retrieve JSON data into local storage?

后端 未结 5 913
迷失自我
迷失自我 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:05
    // THIS IS ALREADY STRINGIFIED
    var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
    
    // DO NOT STRINGIFY AGAIN WHEN WRITING TO LOCAL STORAGE
    localStorage.setItem('added-items', string);
    
    // READ STRING FROM LOCAL STORAGE
    var retrievedObject = localStorage.getItem('added-items');
    
    // CONVERT STRING TO REGULAR JS OBJECT
    var parsedObject = JSON.parse(retrievedObject);
    
    // ACCESS DATA
    console.log(parsedObject.items[0].Desc);
    
    0 讨论(0)
  • 2020-12-28 10:06

    JSON.parse is definitely the best way to create an object but I just want to add if that doesn't work (because of lack of support), obj = eval('(' + str + ')'); should work. I've had a problem with a HTML to PDF converter in the past that didn't include JSON.parse and eval did the trick. Try JSON.parse first.

    Access your object: obj.items[0].Desc;

    0 讨论(0)
  • 2020-12-28 10:09
    var object = Json.parse(retrievedObject);
    

    Now you can access it just like an array

    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

    If you need more help i have some previous code where i am reading Json from local storage and making a form from that json. This code will help in understanding how to traverse that array

    Json stored in localstorage

    {"form":[{"element":"input", "type":"text","name":"name","value":"value","min":"2","max":"10"}]}

    JavaScript to read that json

    function readJson(){
        if(!form_created){
            add_form();
        }
        var fetched_json = localStorage.getItem("json");
        var obj=JSON.parse(fetched_json);
        for(var i=0; i<obj.form.length;i++){
            var input = document.createElement(obj.form[i].element);
            input.name = obj.form[i].name;
            input.value = obj.form[i].value;
            input.type = obj.form[i].type;
            input.dataset.min = obj.form[i].min;
            input.dataset.max = obj.form[i].max;
            input.dataset.optional = obj.form[i].optional;
            
            form.insertBefore (input,form.lastChild);
        }
        alert(obj.form[0].name);
    }

    0 讨论(0)
  • 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

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题