最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - javascript split and JSON.parse - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Mar 31, 2011 at 6:25 gautamlakumgautamlakum 12k23 gold badges69 silver badges90 bronze badges 1
  • 1 always worth a look. developer.mozilla.org/En/Using_native_JSON – codeandcloud Commented Mar 31, 2011 at 6:41
Add a comment  | 

3 Answers 3

Reset to default 13

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)

  1. 暂无评论