Write formatted JSON in Node.js

donald picture donald · Apr 17, 2011 · Viewed 84.8k times · Source

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();

Answer

Peter Lyons picture Peter Lyons · Jun 30, 2012

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.