RobGMiller
RobGMiller

Reputation: 33

Javascript: How to convert AJAX returned string representation of an array to an array

I must convert a string representation of an array of objects returned from AJAX to an array of objects in JavaScript.

ajaxret = "[{a:'a', b:'b', c: 1},{a:'aa', b:'ab', c: 2},{a:'aaa', b:'bbb', c: 3}]"

strResult = [{a:'a', b:'b', c: 1},{a:'aa', b:'ab', c: 2},{a:'aaa', b:'bbb', c: 3}]

Upvotes: 0

Views: 468

Answers (1)

Oriol
Oriol

Reputation: 287980

When you serialize your objects into strings, you should produce valid JSON, using

var string = JSON.stringify(object);

To parse to an object again, then you can use

var object = JSON.parse(string);

In your case, since you have invalid JSON, the simple way is

var object = eval(string);

Warning!!!

  • eval is evil
  • Use it only if the source is completely trusted
  • A malicious source could execute arbitrary code. So bad!
  • JSON.parse is probably faster

Upvotes: 1

Related Questions