漂亮转JSON到文本

Iva*_*her 4 javascript json node.js

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

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

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

{
    type: 'Program',
    body: [
        {
            type: 'VariableDeclaration',
            declarations: [
                {
                    type: 'AssignmentExpression',
                    operator: =,
                    left: {
                        type: 'Identifier',
                        name: 'answer'
                    },
                    right: {
                        type: 'Literal',
                        value: 42
                    }
                }
            ]
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

解:

var fs = require('fs');

    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 ");
        }
    }); 
Run Code Online (Sandbox Code Playgroud)

Tom*_*ant 9

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