Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty dump JSON to Text

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 ");
        }
    }); 
like image 458
Ivan Bacher Avatar asked Jan 11 '23 20:01

Ivan Bacher


1 Answers

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.

like image 151
Tom Grant Avatar answered Jan 21 '23 09:01

Tom Grant