Write formatted JSON in Node.js
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();
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.
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.
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")
You should check out underscore-cli - it's a command-line tool for inspecting and processing JSON data.