gpt4 book ai didi

javascript - 将 JSON 漂亮地转储到文本

转载 作者:搜寻专家 更新时间:2023-10-31 23:33:16 25 4
gpt4 key购买 nike

有没有办法将 JSON 对象转储到文本文件以便从 Node 服务器进行调试?

我正在处理一个非常大的 JSON 对象,其中包含各种其他对象数组。

理想情况下,生成的 txt 文件应该像这样正确格式化

{
type: 'Program',
body: [
{
type: 'VariableDeclaration',
declarations: [
{
type: 'AssignmentExpression',
operator: =,
left: {
type: 'Identifier',
name: 'answer'
},
right: {
type: 'Literal',
value: 42
}
}
]
}
]
}

解决方法:

    var fs = require('fs');

var myData = {
name:'bla',
version:'1.0'
}

var outputFilename = '/tmp/my.json';

fs.writeFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
if(err) {
console.log(err);
} else {
console.log("JSON saved to ");
}
});

最佳答案

如果您的 json 对象称为 json,您可以使用:JSON.stringify(json, null, 2); 这将为您提供一个字符串,然后您可以转储.

关于javascript - 将 JSON 漂亮地转储到文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20123858/

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