4

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 ");
        }
    }); 
cam8001
  • 1,581
  • 1
  • 11
  • 22
Ivan Bacher
  • 5,855
  • 9
  • 36
  • 56
  • 2
    This question should help: http://stackoverflow.com/questions/5670752/write-pretty-json-to-file-using-node-js – tymeJV Nov 21 '13 at 14:45
  • is this a duplicate of https://stackoverflow.com/questions/7428235/how-do-you-log-content-of-a-json-object-in-node-js ? – David Cary Oct 25 '19 at 20:53

1 Answers1

9

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.

Tom Grant
  • 2,027
  • 18
  • 22
  • will that format everything correctly? IN perl theres a Dumper module that does this for you. does one exist in JS – Ivan Bacher Nov 21 '13 at 14:49
  • 1
    @BuildingJarl It will pretty print it. You can tweak the integer argument you pass to the level of indentation you require. I think what you have to be careful of is if it prints a new line when dumped to a text file, of that I'm not sure. – Tom Grant Nov 21 '13 at 14:59