Slinky Slinky - 1 month ago 15
JSON Question

Node Express & JSON Response Format

I am wondering why I am getting my JSON response with escaped double quotes. What is the best practice for sending JSON response back to client?

The code

var express = require('express');
var server = express();
var country = '';
var dataStr = '[{"country_code" : "USA", "country_name" : "United States","bac_limit" : 0.80}, { "country_code" : "CAN", "country_name" : "United States","bac_limit":0.80}]';
connectToMongoDb();

server.get('/', function(req, res){
country = req.query.country;
res.json(dataStr);
});
server.listen(8080);


The Output

"[{\"country_code\" : \"USA\", \"country_name\" : \"United States\",\"bac_limit\" : 0.80}, { \"country_code\" : \"CAN\", \"country_name\" : \"United States\",\"bac_limit\":0.80}]"

Answer

Your dataStr is actually a string, and res.json call is sending the string as such. If you wish to send the data as JSON, don't put it as a string, but a JS object/array (or use JSON.parse):

var dataStr = [{"country_code" : "USA", "country_name" : "United States","bac_limit" : 0.80}, { "country_code" : "CAN", "country_name" : "United States","bac_limit":0.80}]
// alternatively, JSON.parse(dataStr)
connectToMongoDb()

server.get('/', function(req, res){
 country = req.query.country
 res.json(dataStr)
})
Comments