开发者

javascript split and JSON.parse

开发者 https://www.devze.com 2023-02-21 03:34 出处:网络
I want to parse array in JSON format using javascript. I have written fo开发者_开发问答llowing code.

I want to parse array in JSON format using javascript. I have written fo开发者_开发问答llowing 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.


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);


That's because "abc, xyz, pqr" isn't valid JSON. Plus, JSON.parse() is meant to parse JSON strings, not arrays. What are you trying to do, perhaps we can better assist.


This is actually a convenient short cut to json processing if you only need a smaller set of variables.

PHP:

return $var1 .','. $var2 .',some_string_value.';

Javascript:

var myReturnArray = returnValue.split(',');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号