1

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}]"
3
  • Try JSON.stringify('[{"country_code" : "USA"}]') - as long as you are trying to stringify a string the result is what you get. The best response it just stringified array Commented Oct 17, 2016 at 14:24
  • @KrzysztofSafjanowski you stringify a string that already contains data encoded as JSON. Commented Oct 17, 2016 at 14:47
  • @t.niese As same as dataStr covers Commented Oct 17, 2016 at 14:59

1 Answer 1

1

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)
})
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.