Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript split and JSON.parse

I want to parse array in JSON format using javascript. I have written following code.

var data = "abc, xyz, pqr";
var data_array = data.split(',');

var data_parsed = JSON.parse(data_array);
alert(data_parsed);

It gives me the error of JSON.parse I have no idea how to resolve this javascript error.

like image 879
gautamlakum Avatar asked Mar 31 '11 06:03

gautamlakum


1 Answers

You don't have any JSON, so don't use JSON.parse. Once you split you already have an array whose elements could be used directly:

var data = "abc, xyz, pqr";
var data_array = data.split(',');
alert(data_array[0]);

and if you want to convert this array to a JSON string you could do this:

var json = JSON.stringify(data_array);
alert(json);
like image 128
Darin Dimitrov Avatar answered Sep 20 '22 23:09

Darin Dimitrov