繁体   English   中英

如何将多行字符串打印到Blob中?

[英]How to print multi-line string into a blob?

我有一本字典,要多行打印到txt文件。

为此,我是:
1)通过JSON.stringify(dict)将dict转换为字符串
2)将字符串输入到Blob并保存

我遇到的麻烦是输出是字典的非常丑陋的1行结果,如下所示:

{"key1":"value1","key2":"value2","key3":"value3",etc}

但我想要这样:

key1:value1  
key2:value2
key3:value3  
etc.  

我该如何实现?

result = JSON.stringify(dict);

// Create blob instance and input the string
var blob1 = new Blob([result], { type: "text/plain" });
url = window.URL.createObjectURL(blob1);

// Create link to download the blob as txt file
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = url;
a.setAttribute("download","My Open Tabs");
a.click();
window.URL.revokeObjectURL(url);

为了获得与预期相似的效果,可以向JSON.stringify添加参数。

JSON.stringify({ key1: 'value1', key2: 'value2' }, null, '\n'); // Unix
JSON.stringify({ key1: 'value1', key2: 'value2' }, null, '\r\n'); // Windows

谢谢@Fefux提到Windows和Unix之间的区别!

第三个参数接受所需的分隔符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM