Create Text file from String using JS and html5

后端 未结 4 522
感情败类
感情败类 2020-12-29 10:15

i want to create a text file from a string. currently i am using a function which takes an array and makes it into a string then using that string i want to create a local t

4条回答
  •  一向
    一向 (楼主)
    2020-12-29 10:46

    Convert your object to a JSON string.

    var json_string = JSON.stringify(object, undefined, 2);
    

    Notes:

    1. If you already have a string, skip the step above.
    2. If you don't want it to be formatted nicely, remove the , undefined, 2.

    Create a download link and click it:

    var link = document.createElement('a');
    link.download = 'data.json';
    var blob = new Blob([json_string], {type: 'text/plain'});
    link.href = window.URL.createObjectURL(blob);
    link.click();
    

提交回复
热议问题