How to save JSON data locally (on the machine)?

前端 未结 2 938
后悔当初
后悔当初 2020-12-01 19:30

I am using the following link to create a tree like structure: LINK

This is my code :




    

        
相关标签:
2条回答
  • 2020-12-01 19:57

    LocalStorage does exactly that.

    Use it like this :

    localStorage.setItem('myCat', 'Tom');
    console.log(localStorage.getItem('myCat')); // Tom
    

    Use can use it to store stringify-ed objects as well :

    var obj = { a : 1, b : 2};
    localStorage.setItem('myObj', JSON.stringify(obj));
    var obj2 = JSON.parse(localStorage.getItem('myObj'));
    
    0 讨论(0)
  • 2020-12-01 20:04

    Sure this can be done.

    Once you have your JSON string (Im assuming you know how to get it because if not that's a different question altogether) you can save it using this function:

    function saveText(text, filename){
      var a = document.createElement('a');
      a.setAttribute('href', 'data:text/plain;charset=utf-8,'+encodeURIComponent(text));
      a.setAttribute('download', filename);
      a.click()
    }
    

    Call it:

    var obj = {a: "Hello", b: "World"};
    saveText( JSON.stringify(obj), "filename.json" );
    

    This would prompt the use to save a file named "filename.json", which contains a JSON object of obj

    0 讨论(0)
提交回复
热议问题