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"]
Community
  • 1
  • 1
  • I didn't find any information about it in Google... – Mindaugas Jakubauskas Jan 12 '13 at 00: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. –  Jan 12 '13 at 00:34

3 Answers3

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);
joeltine
  • 1,610
  • 17
  • 23
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.

tiffon
  • 5,040
  • 25
  • 34
2

make it an array

var array = myString.split(',');
kevin
  • 328
  • 4
  • 15
  • 33