Is there a way to dump a JSON object to a text file for debuging from Node server?
I am dealing with a very large JSON object containing various arrays of other objects.
Ideally the generated txt file should be formatted correctly like this
{
type: 'Program',
body: [
{
type: 'VariableDeclaration',
declarations: [
{
type: 'AssignmentExpression',
operator: =,
left: {
type: 'Identifier',
name: 'answer'
},
right: {
type: 'Literal',
value: 42
}
}
]
}
]
}
Solution:
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 ");
}
});
If your json object is called json
, you can use: JSON.stringify(json, null, 2);
that will give you a string you can then dump.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With