gpt4 book ai didi

javascript - 将javascript对象打印到txt文件

转载 作者:行者123 更新时间:2023-11-28 03:51:44 24 4
gpt4 key购买 nike

我有一个像这样的 JavaScript 对象

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

我想这样打印:人.姓名----人.地址----人.电话在一个txt文件中。到目前为止,我可以像这样使用 console.log 来做到这一点

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

控制台的输出是:“约翰·多伊 ---- 纽约市 ---- 电话: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.

关于javascript - 将javascript对象打印到txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47942244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com