5

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?

2
  • So... you don't want the dashes? Commented Mar 6, 2016 at 13:59
  • No I want it to be treated as a string, thanks Commented Mar 7, 2016 at 22:08

4 Answers 4

9

Strings 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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, looks like what I should use
2

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.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString

Comments

1

Can always use toString(). This will work even if it is a string

var data = {
     "phone":  input.toString()
}

1 Comment

Well, not always because things like null or undefined don't have that method, but it'll work if input is guaranteed to be a string or a number.
0
$( 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));

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.