Is there a simple way to deal with this example situation
var data = {
"phone": input
}
var payload = JSON.stringify(data);
In the situation where the payload is used in an API call and the API demands that phone value is a string, however, phone numbers can just be entered as numbers or strings e.g. 123777777 or 1237-77777 etc
I tried adding quotes, but JSON.stringify escape them so the end up being part of the final data.
The 'hack' solution I found was to add a trailing space i.e.
var data = {
"phone": input + " "
}
But want to know if there is a simple and neat way to deal with this scenario?
Is there a simple way to deal with this example situation
var data = {
"phone": input
}
var payload = JSON.stringify(data);
In the situation where the payload is used in an API call and the API demands that phone value is a string, however, phone numbers can just be entered as numbers or strings e.g. 123777777 or 1237-77777 etc
I tried adding quotes, but JSON.stringify escape them so the end up being part of the final data.
The 'hack' solution I found was to add a trailing space i.e.
var data = {
"phone": input + " "
}
But want to know if there is a simple and neat way to deal with this scenario?
Share Improve this question asked Mar 6, 2016 at 13:55 Alan FullerAlan Fuller 4916 silver badges13 bronze badges 2- So... you don't want the dashes? – Sumner Evans Commented Mar 6, 2016 at 13:59
- No I want it to be treated as a string, thanks – Alan Fuller Commented Mar 7, 2016 at 22:08
4 Answers
Reset to default 9Strings don't have to have anything in them, so you could do:
var data = {
"phone": input + ""
};
or "" + input
would work as well. But in this situation I usually use the String
function:
var data = {
"phone": String(input)
};
Note: Not new String(...)
, just String(...)
.
There's nothing wrong with the input.toString()
option others have suggested either, provided you know that input
will be something other than null
or undefined
. (If it were null
or undefined
, it would cause an error.)
If you want to make sure it's a string call toString()
which ensures numbers are parsed as strings.
var data = {
"phone": input.toString()
}
Best thing is, that even if you have a string this won't throw an error. It will always be a string. See here for more: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString
Can always use toString()
. This will work even if it is a string
var data = {
"phone": input.toString()
}
$( document ).ready(function(){
var input=1234567890;
var data = {
"phone": input.toString()
}
console.log("inputType---->"+$.type(input));
var payload = JSON.stringify(data);
console.log("payload----afterstringify--->"+payload);
console.log("dataType------->"+$.type(data.phone));
console.log("payloadType-------->"+$.type(payload));
});