将Json对象导出到文本文件中

Export a Json object to a text File

本文关键字:文本 文件 Json 对象      更新时间:2023-09-26

我正在尝试编写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();

编译器运行时没有错误,但我无法获取文本文件。我也使用了一些目录的路径,但什么都没有。

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

我知道这个问题已经被接受了,但我认为我的答案可以帮助别人。因此,问题是将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);

如果你可以访问一个已经存在的文件,只需链接到它。你可以指定下载的文件名如下:

<a href="path/to/file.txt" download="example.json">
    Download as JSON
</a>

如果需要,您还可以写出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;

然后只需给链接一个ID和一个默认的href

<a href="#" id="link" download="example.json">
    Download as JSON
</a>

终于拿到了!它通过改变一些参数来工作,比如:

   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();

我的目录的路径是不允许的,所以我不得不把它保存在/tmp目录上。感谢大家!