用Node.js编写格式化的JSON
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).
我使用的节点。js将JSON发送到PostBin,但是数据被错误地格式化了(正如您在这里看到的: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();
4 个解决方案
#1
10
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?"
主要是因为JSON不关心它的格式,你自己也不做任何格式设置。你需要的是一个javascript漂亮的打印机,如果你在乎的话,但是第一个问题是“你为什么在乎?”
Here's a prettyprinting code from the Javascript Recipes.
下面是来自Javascript食谱的漂亮打印代码。
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.
好了,现在它在做你想做的,让我们问一下你是否做对了。正如一些人指出的,您不需要传输那些额外的换行符、制表符或空格;效率成本很小,可能在2%到5%之间,但是你永远不知道什么时候你可能需要几个百分点。
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.
另一方面,我完全同意,能够将JSON输出作为预打印文本读取更方便。但是还有另外一个解决方案——你仍然可能使用浏览器来查看这些结果,所以不要用预印版来传输,而是使用客户端打印机。我在火狐浏览器中使用JSONView和JSONView。许多调试器也会为您打印JSON结果。