alex
alex

Reputation: 235

JSON object creation error

I am trying to create a JSON object in the particular format

{ "id": 12234 , "name": "Alex" , "gender": "Male"}

 // My code starts here

var number = userid;         // alert(userid) is 12345
var name=  nameuser;         // alert(nameuser)  is  Alex
var g= gender;                 // alert(gender) is male

var userObj = { "id": number , "name": name , "gender":g}

I tried `JSON.stringify(userObj); , that returns the object type as

{"id":"12345" , "name":"Alex" , "gender":"Male"}

but this is not what I want as I want the number to be 12345 and not "12345".

also tried stringifying the fields inside the object like

{ "id": number , "name":JSON.stringify(name) ,gender: JSON.stringify(g)} 

but when I do alert(userObj) my object type is Object object and this is not a format the server recognises. I am sure there is a workaround for this but I am unable to figure one out

Upvotes: 3

Views: 201

Answers (4)

Amareswar
Amareswar

Reputation: 2064

store the object type as one of the property and use it to convert the way you want.

Upvotes: 0

Aaron Kurtzhals
Aaron Kurtzhals

Reputation: 2036

The below code from your question is valid JSON.

{ "id": 12234 , "name": "Alex" , "gender": "Male"}

I am guessing that the problem you have is that your userid variable is a string, not a number. If so, try

var number = parseInt(userid, 10);

(The 10 parameter indicates that you are using base 10 numbers as opposed to something like binary or hex).

Upvotes: 0

LetterEh
LetterEh

Reputation: 26696

I think that your solution will come down to what you want to DO with the JSON, rather than how you want it to be formatted.

If you're using it in other JavaScript code, then the JSON.parse method is going to take care of most of your issue on the other side (with automatic type-casting dealing with the rest).

If you're using it on the server-side, again, PHP or similar will decode the object appropriately.

And if it's a more-strict language on your server, all you need to do is remember which parameters need to be cast to boolean or to int/float.

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

JSON works with strings exclusively. It's invalid to have anything other than a string, array, or other JSON object in JSON. That said, a "number" is not allowed; it needs to be a string. Whatever you are working with with the JSON later needs to be able to change the string back it to a number, if necessary. JavaScript usually does a good job of coercing these.

On the server side you can just do something like

obj = json_decode(source)
obj.id = (int)obj.id

Upvotes: 2

Related Questions