Write formatted JSON in Node.js

久未见 提交于 2019-11-28 16:08:17

问题


I'm using Node.js to POST JSON to PostBin but the data is being wrongly formated (as you can see here: http://www.postbin.org/1cpndqw).

This is the code I'm using for tesT:

var http = require('http');

var options = {
  host: 'www.postbin.org',
  port: 80,
  path: '/1cpndqw',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.write(JSON.stringify({ a:1, b:2, c:3 }, null, 4));
req.end();

回答1:


Well, primarily because JSON doesn't care how it's formatted, and you aren't doing any formatting yourself. What you need is a javascript prettyprinter, if you care, but the first question is "Why do you care?"

Here's a prettyprinting code from the Javascript Recipes.

Actually there's a whole bunch of different examples here on SO.

UPDATE

Okay, so now it's doing what you want, let's ask if you're doing the right thing. As several people have pointed out, you needn't transmit those extra newlines and tabs, or spaces; the efficiency cost is small, probably in the neighborhood of 2-5 percent, but you never know when you might need a couple percent.

On the other hand, I agree completely that it's a lot more convenient to be able to read the JSON output as prettyprinted text. But there's another solution -- you're still probably using a browser to look at these results, so instead of prettyprinting it for transmission, use a client-side prettyprinter. I use JSONView for Chrome and JSONView in Firefox. Many debuggers will also prettyprint the JSON results for you as well.




回答2:


Use JSON.stringify(object, null, 4) where 4 is the number of spaces to use as the unit of indentation. You can also use "\t" if you want tabs. This is actually part of the ECMAScript 5 specification, and is documented on MDN.




回答3:


I used a two step process that I found to work:

var output = JSON.parse(insert_json_here);
var print_to_file = JSON.stringify(output, null, "\t")



回答4:


You should check out underscore-cli - it's a command-line tool for inspecting and processing JSON data.



来源:https://stackoverflow.com/questions/5693999/write-formatted-json-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!