15

I have an ajax request that returns a list of values like this:

"[-5, 5, 5], [-6, 15, 15], [7, 13, 12]"

I need it to be a javascript array with numbers:

[[-5, 5, 5], [-6, 15, 15], [7, 13, 12]]

I tried to replace the '[' and ']' for a '|' and then split by '|' and foreach item split by ',' and add them to an array, but this is not elegant at all.

Do you guys have any suggestions?

2
  • 3
    Define elegant? Most string manipulations aren't really pretty. Commented Oct 17, 2013 at 4:24
  • Using split + for loop where perhaps match would do is likely not elegant or pretty. ;-) Commented Oct 17, 2013 at 4:32

5 Answers 5

29

You can use JSON.parse() to convert that string into an array, as long as you wrap it in some brackets manually first:

var value = "[-5, 5, 5], [-6, 15, 15], [7, 13, 12]";
var json = JSON.parse("[" + value + "]");

console.log(json);

I would suggest correcting the output at the server if possible, though.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for the fast & elegant response!
that is pretty, :)
This does not accept string like this "[Name, 26], [Name2, 45]" Any idea how to do it?
@Kishan Depends greatly on the context and what can appear in place of Name - probably in this case you just want to do something like create a 2D array by extracting all the contents of [ ] pairs and then exploding on commas.
Yes, name can be a string value which is giving me an error with JSON.parse. I am using eval as last resort but I heard that eval is not a good choice?
|
2

This solution is stupid in practice -- absolutely use JSON.parse as others have said -- but in the interest of having fun with regular expressions, here you go:

function getMatches(regexp, string) {
  var match, matches = [];
  while ((match = regexp.exec(string)) !== null)
    matches.push(match[0]);
  return matches;
}

function parseIntArrays(string) {
  return getMatches(/\[[^\]]+\]/g, string)
    .map(function (string) {
      return getMatches(/\-?\d+/g, string)
        .map(function (string) { 
          return parseInt(string); 
        });
    });
}

parseIntArrays("[-5, 5, 5], [-6, 15, 15], [7, 13, 12]");

Comments

1

If you're generating the data, and you trust it, just use eval:

var string = "[-5, 5, 5], [-6, 15, 15], [7, 13, 12]"

var arrays = eval('[' + string + ']');

Alternatively, start returning well-formed JSON.

2 Comments

In before 'eval is evil'.
@upvoter There's really no good reason to use eval when the string is also valid JSON, please downvote me instead.
1

In a function

var strToArr = function(string){ return JSON.parse('[' + string + ']')}

console.log(strToArr("[-5, 5, 5], [-6, 15, 15], [7, 13, 12]"));

2 Comments

Shouldn't that function be named stringToArr?
@Jashwant Don't look at me.
1
var string = "[-5, 5, 5], [-6, 15, 15], [7, 13, 12]";
var arr = [];
var tmp = string.split('], ');

for (var i=0; i<tmp.length; i++) {
    arr.push(tmp[i].replace(/\[|\]/g, '').split(', '));
}

Typing on my iPad so I apologize in advance for any typos.

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.