0

I have this data in an input: [16,57.35], [23,56.26], [34,54.57]

and I want to turn it into an array

var data =$('#data').val();
var array = JSON.parse ("["+data+"]");

I'm having this error

Uncaught SyntaxError: Unexpected token.

How I can fix it or I can convert the input value in array?

3
  • 5
    Works here... Commented Jul 9, 2013 at 17:02
  • 2
    Please do a console.log(data) and post here what you are actually passing in. Commented Jul 9, 2013 at 17:13
  • 1
    Also check data.length, maybe there are some non-printing characters in it. Commented Jul 9, 2013 at 17:14

2 Answers 2

5

Your code is working check it here, you may need to include required jQuery library or check some thing else in the code causing it.

data = $('#txt1').val();
arr = JSON.parse ("["+data+"]");
console.log(arr);
Sign up to request clarification or add additional context in comments.

Comments

1

Try using the eval function:

var data = "123, 456, 789";
var array = eval("[" + data + "]");

You'll need to make sure that whatever you're inputting is valid JSON, but the above code will output an array for you. Hope it helps.

11 Comments

It actually is valid JSON, if he's wrapping it in [], which I missed the first time around.
be careful, eval is considered harmful: stackoverflow.com/questions/86513/…
@MarcelSoleraAyala: You're welcome. Please make sure to mark the answer if you're satisfied.
@meagar - I put the data in at JSONLint and it did not validate. Is there a less rigid interpretation of valid JSON that you are using?
@JamesJohnson Regardless, you should be downvoted if you propose a solution that introduces security problems. Downvoting for security concerns is completely valid, whether or not they were explicitly mentioned in the question. However, in this case, such concerns are misguided and unfounded... That said, there is no reason to use eval, when the string is valid JSON. There is some other problem the question's author is ignoring by switch to eval.
|

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.