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?

user229044
  • 232,980
  • 40
  • 330
  • 338
Marztres
  • 460
  • 8
  • 15

2 Answers2

4

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);
Adil
  • 146,340
  • 25
  • 209
  • 204
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.

James Johnson
  • 45,496
  • 8
  • 73
  • 110
  • 2
    It actually *is* valid JSON, if he's wrapping it in `[]`, which I missed the first time around. – user229044 Jul 09 '13 at 17:03
  • 2
    be careful, eval is considered harmful: http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – cfs Jul 09 '13 at 17:05
  • @MarcelSoleraAyala: You're welcome. Please make sure to mark the answer if you're satisfied. – James Johnson Jul 09 '13 at 17:05
  • @meagar - I put the data in at [JSONLint](http://jsonlint.com/) and it did not validate. Is there a less rigid interpretation of valid JSON that you are using? – Karl Anderson Jul 09 '13 at 17:10
  • @Downvoter: Care to explain? I hope this wasn't downvoted because of security concerns as that was not part of the question. – James Johnson Jul 09 '13 at 17:17
  • @Karl It validates, if you wrap it in `[]` as the question indicates: `[[16,57.35], [23,56.26], [34,54.57]]` – user229044 Jul 09 '13 at 17:18
  • @meagar - Ah, I did not put the outer brackets. Thanks. :-) – Karl Anderson Jul 09 '13 at 17:19
  • @cfs Eval is not harmful in this particular use. – user229044 Jul 09 '13 at 17:21
  • Of course there's no security concern (assuming the value was generated by the user). But `eval` is just bad practise, and for what it is used here `JSON.parse` would be better (and work just as well). – Bergi Jul 09 '13 at 17:26
  • 2
    @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`. – user229044 Jul 09 '13 at 17:26
  • @meagar: I agree that a downvote is valid when code *will* introduce a vulnerability. I disagree with downvoting based on precedent alone. – James Johnson Jul 09 '13 at 17:29