Reputation: 5832
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}]"
Upvotes: 1
Views: 3383
Reputation: 80657
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)
})
Upvotes: 1