0

I have following JSON incoming data (note it have comma in it).

var data = '["QUAIL, TX","QUAKER CITY, OH","QUAKER, CT","QUAKER STREET, NY"]';

Now I want to convert it into JavaScript array but not sure what is the best approach to do this? I have tried JSON.parse(data) which throws exception and I have tried to split data by '",' but it gets the wrong value at first and in end. Any idea what is the best strategy here?

     data = JSON.stringify(data);
     data = data.split('",');

PS: I have looked at most of the questions but none of them was relevant here.

4
  • Try this to convert your data to javascript array: var data = data. Now data is going to be an array. Commented Apr 27, 2014 at 8:15
  • What's the exception? Commented Apr 27, 2014 at 8:15
  • What is your issue actually about? Commented Apr 27, 2014 at 8:17
  • Your original data variable is already an array, please provide the JSON string that you are working on Commented Apr 27, 2014 at 8:18

2 Answers 2

1

Commas in JSON string won't cause JSON.parse() to throw exception. See this code:

var a = '["QUAIL, TX","QUAKER CITY, OH","QUAKER, CT","QUAKER STREET, NY"]';
var b = JSON.parse( a );
alert( b[0] );

Fiddle: http://jsfiddle.net/sTuSV/

It is about something different being wrong with your code.

Comments

0

this seems to work - but I am assuming what you have given 'is' your data structure. If your JSON is different, then what I have below will not work.

var data = ["QUAIL, TX","QUAKER CITY, OH","QUAKER, CT","QUAKER STREET, NY"].toString().split(',');

 //returns ["QUAIL", " TX", "QUAKER CITY", " OH", "QUAKER", " CT", "QUAKER STREET", " NY"]

if you want to get rid of the white space:

var data = ["QUAIL, TX","QUAKER CITY, OH","QUAKER, CT","QUAKER STREET, NY"].toString().replace(/\s/g,'').split(',');
     // returns ["QUAIL", "TX", "QUAKERCITY", "OH", "QUAKER", "CT", "QUAKERSTREET", "NY"]

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.