簡體   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