1

If I have this response -

{
  type: "2",
  userId: "123"
}

While sending the response, I want the values to convert to numeric. Is there any way in node/express to do this?

nirvair
  • 4,001
  • 10
  • 51
  • 85

3 Answers3

0

var _ = require('underscore');

var data = { type: "2", userId: "123" };

var result = _.keys(data);

result.forEach(function (key) { data[key] = Number(data[key]) });

console.log(data);

Meena
  • 97
  • 2
0

we can use parseInt() to convert string to int type.

var data = { type: parseInt("2"), userId:  parseInt("2") };

response.send(data);
shan kulkarni
  • 849
  • 7
  • 18
0

Directly answer is

var a = {type: "2", userId: "123", text: "ABC"};
res.send(JSON.stringify(a, function(key, value) { return parseInt(value) || value}));

Express have special method to stringify object and send it - res.json, but this method doesn't support replacer function.

Aikon Mogwai
  • 4,954
  • 2
  • 18
  • 31