Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node and express send json formatted

Tags:

I'm trying to send formatted json with express.

Here is my code:

var app = express();  app.get('/', function (req, res) {   users.find({}).toArray(function(err, results){     // I have try both     res.send(JSON.stringify(results, null, 4));     // OR     res.json(results);   }); }); 

I get the json in my browser but it's a string. How can I send it so it's readable in the browser?

like image 357
BoumTAC Avatar asked Sep 20 '15 12:09

BoumTAC


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.

Does Express automatically parse JSON?

Express doesn't automatically parse the HTTP request body for you, but it does have an officially supported middleware package for parsing HTTP request bodies. As of v4. 16.0, Express comes with a built-in JSON request body parsing middleware that's good enough for most JavaScript apps.

How do you return data in JSON format in node JS?

stringify() to return JSON data): We will now use http. createServer() and JSON. stringify() to return JSON data from our server.


1 Answers

try to set the "secret" property json spaces on the Node app.

app.set('json spaces', 2) 

This statement above will produce indentation on json content.

like image 87
Alexis Diel Avatar answered Oct 02 '22 14:10

Alexis Diel