繁体   English   中英

将JavaScript对象打印到txt文件

[英]Print javascript object to txt file

我有一个像这样的javascript对象

    var data = {
    "person": {
        "name": "John Doe",
        "address": "N.Y City",
        "city": "N.Y",
        "country": "USA",
        "phone": "Ph: 12345"
  }

我想这样打印:txt文件中的Person.Name----Person.Address----Person.Phone。 到目前为止,我可以使用console.log这样

console.log(data['person']['name'] + "----" + data['person']['address'] + "----" + data['person']['phone'])

控制台中的输出为:“ John Doe ----纽约市---- Ph:12345”

我不想打印json的所有值。 我要打印其中一些,也希望在它们之间使用“ ----”。

是否可以将其打印为txt文件? 我还没什么好

在Node.js上下文中,您可以通过以下方式进行操作:

const fs = require('fs');
const yourObject = {
 // ...addProperties here.
}

fs.writeFile("/path/to/save.txt", JSON.stringify(yourObject), 'utf8', function (err) {
    if (err) {
        return console.log(err);
    }

    console.log("The file was saved!");
}); 

在浏览器上下文中,您可以执行以下操作:

// Function to download data to a file
function download(data, filename, type) {
    var file = new Blob([data], {type: type});
    if (window.navigator.msSaveOrOpenBlob) // IE10+
        window.navigator.msSaveOrOpenBlob(file, filename);
    else { // Others
        var a = document.createElement("a"),
                url = URL.createObjectURL(file);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);  
        }, 0); 
    }
}

声明该功能后,执行以下操作:

download(JSON.stringify(yourObject), 'file', 'txt') // file is filename, and txt is type of file.

暂无
暂无

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

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