漂亮打印JSON到节点中的文件

所以我有一个非常大的JSON数据,我通过AngularJS发送给节点服务器。 这是我用来发送数据的程序: –

var send_data="data="+encodeURIComponent(JSON.stringify($scope.records,null,4)); $http({ method : 'POST', url : 'http://localhost:8888/updateDetails', data : send_data, responseType : "json", headers: { "Content-Type": 'application/x-www-form-urlencoded' } }).success(function(data, status, headers, config){ console.log(data); }); 

我成功设法通过上面的代码发送一个漂亮的打印的JSON到节点服务器。 但是,当我写这个文件使用:

 jsonfile.writeFile(file, JSON.parse(req['body']['data']), function (err) { console.error(err); }); 

经过一些testing,我发现错误在JSON.parse语句中。 任何方式漂亮打印JSON文件?

使用JSON.stringify(data[, replacer[, indent]])

 jsonfile.writeFile(file, JSON.stringify(JSON.parse(req.body.data), 0, 4), function (err) { console.error(err); }); 

你可能也可能不需要parsing响应主体 – 我相信在构build器中的responseType: "json"会自动为你parsing:

 jsonfile.writeFile(file, JSON.stringify(req.body.data, 0, 4), function (err) { console.error(err); }); 

下面是一个完整的工作原理示例:

 var fs = require('fs'); var req = JSON.parse('{"body": {"data": "Some text."}}'); fs.writeFile('test.json', JSON.stringify(req.body, 0, 4), function (err) { }); 

假设你正在通过一个HTTP侦听器或框架如快递处理POST请求? 你是否使用身体分析器来parsing传入的JSON?

咱们试试吧:

  1. console.log(req.body)确保您的服务器识别请求。
  2. 这是一个JSONstring? 有效吗? 或者它是一个JavaScript对象(即已被parsing)?
  3. 如果它被parsing,那么我的第二个build议将起作用。 如果它没有被parsing,就像我在第一个例子中那样parsing它。