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

前端 未结 2 945
后悔当初
后悔当初 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 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

提交回复
热议问题