16

Possible Duplicate:
Convert JS object to JSON string
Store comma separate values into array

I have a string containing values separated with commas:

"1,4,5,11,58,96"

How could I turn it into an object? I need something like this

["1","4","5","11","58","96"]
2
  • I didn't find any information about it in Google... Commented Jan 12, 2013 at 0:16
  • JSON is a textual serialization of data. I have updated the question to reflect needing a JavaScript array. If you need the JSON text representation of this array, that is an additional step (and is achieved as shown in joeltine's answer). Update or clarify the question as needed. Also, remember to "accept" answers. Commented Jan 12, 2013 at 0:34

3 Answers 3

28

This will convert it into an array (which is the JSON representation you specified):

var array = myString.split(',');

If you need the string version:

var string = JSON.stringify(array);
Sign up to request clarification or add additional context in comments.

3 Comments

be aware that JSON.stringify is not in IE6 or 7.
it worked only with end_value=JSON.stringify(start_value); [probably because start_value was parsed from json]. thank you very much :)
wouldn't the string version be var string = array.join(',');
3

In JSON, numbers don't need double quotes, so you could just append [ and ] to either end of the string, resulting in the string "[1,4,5,11,58,96]" and you will have a JSON Array of numbers.

Comments

2

make it an array

var array = myString.split(',');

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.