在 Node.js 中编写格式化的 JSON

我正在使用 Node.js 将 JSON POST 到 PostBin,但是数据的格式错误(正如您在这里看到的: http://www.postbin.org/1cpndqw)。

下面是我用于 testT 的代码:

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();
87273 次浏览

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.

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

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.

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")