5

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.

1

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

+1 very true. also alert(data == JSON.parse(json)) will be true only.
0

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.

Comments

0

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(',');

Comments

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.