Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); 
like image 929
donald Avatar asked Apr 17 '11 14:04

donald


People also ask

How do I beautify JSON in node JS?

If you just want to pretty print an object and not export it as valid JSON you can use console. dir() . It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets. Under the hood it is a shortcut for console.


2 Answers

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.

like image 58
Peter Lyons Avatar answered Sep 23 '22 20:09

Peter Lyons


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.

like image 22
Charlie Martin Avatar answered Sep 25 '22 20:09

Charlie Martin