将Json对象导出到文本文件

Alb*_*eis 10 javascript json fwrite

我正在尝试编写一个Json对象(JsonExport),我想将其内容写入文本文件.

我正在使用max4live将数据从Audio DAW导出到Json以便导出到服务器,但之后我想在文本文件中看到整个Json对象:

 var txtFile = "test.txt";
 var file = new File(txtFile);
 var str = JSON.stringify(JsonExport);


 file.open("write"); // open file with write access
 file.write(str);
 file.close();
Run Code Online (Sandbox Code Playgroud)

编译器运行时没有错误,但我无法获取文本文件.我已经使用了一些我的目录,没有任何东西.

知道发生了什么事吗?谢谢

CBa*_*arr 12

如果您有权访问现有文件,只需链接即可.您可以指定下载的文件名将是这样的:

<a href="path/to/file.txt" download="example.json">
    Download as JSON
</a>
Run Code Online (Sandbox Code Playgroud)

如果需要,您也可以写出dataURI

 //Get the file contents
 var txtFile = "test.txt";
 var file = new File(txtFile);
 var str = JSON.stringify(JsonExport);

 //Save the file contents as a DataURI
 var dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(str);

 //Write it as the href for the link
 var link = document.getElementById('link').href = dataUri;
Run Code Online (Sandbox Code Playgroud)

然后只需为链接提供ID和默认值 href

<a href="#" id="link" download="example.json">
    Download as JSON
</a>
Run Code Online (Sandbox Code Playgroud)


Nut*_*ker 7

我知道这个问题已经接受了答案,但是我认为我的答案可以帮助某人。因此,问题是将Json数据导出到文本文件。执行以下代码后,浏览器将下载文件。

const filename = 'data.json';
const jsonStr = JSON.stringify(JsonExport);

let element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(jsonStr));
element.setAttribute('download', filename);

element.style.display = 'none';
document.body.appendChild(element);

element.click();

document.body.removeChild(element);
Run Code Online (Sandbox Code Playgroud)


Alb*_*eis 5

终于我明白了!它通过改变这样的几个参数来工作:

   var txtFile = "/tmp/test.txt";
   var file = new File(txtFile,"write");
   var str = JSON.stringify(JsonExport);

   log("opening file...");
   file.open(); 
   log("writing file..");
   file.writeline(str);
   file.close();
Run Code Online (Sandbox Code Playgroud)

不允许我的目录路径,所以我不得不将其保存在/ tmp目录中.谢谢大家!

  • 如果在浏览器上运行javascript,我们可以使用此方法写入txt文件吗? (2认同)