0

Lets say I have a string like so:

var myStr = "[1,2,3,4,5]";

How can I convert it to something like this:

[1, 2, 3, 4, 5]

I'm trying to do this using the following command:

JSON.parse(myStr)

However, I get an error. What's the right way to do this? Moreover, can the same method be used for structured strings containing non-numbers? Like the following:

var myStr2 = "[cats, dogs, elephants]"

EDIT:

To be specific, I get this error:

SyntaxError: JSON.parse: expected ',' or ']' after array element at line 1 column 5 of the JSON data

The string part is something like this:

[16 Sep,16 Sep,16 Sep,16 Sep,16 Sep,16 Sep,16 Sep]

So I dont really understand why I get this error.

2
  • 4
    I don’t get an error. myStr2 needs to look like '["cats", "dogs", "elephants"]' in order for JSON.parse to work. Commented Sep 16, 2016 at 19:24
  • The string should be in a proper JSON format. In your first case you could not have such error. Only in case 2 and 3 you have problems, as the strings should be quoted as Nour Yasein suggested. Commented Sep 16, 2016 at 19:33

4 Answers 4

2

You should write it like so

var myStr2 = '["cats","dogs","elephants"]' ; 
obj = JSON.parse(myStr2);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use this code to convert the string to array.Remove the brackets and split the string with comma.

var myStr = "[1,2,3,4,5]";
var arr = myStr.replace(/^\[|\]$/g,'').split(','); // converted array 

Comments

1

Try var array = JSON.parse("[" + myStr + "]"); This will give you an array [1,2,3,4,5]

Comments

0

For an array with number this works:

var myStr = "[1,2,3,4,5]";
var array = JSON.parse(myStr);

console.log(array);

output:

[1, 2, 3, 4, 5]

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.