kqlambert
kqlambert

Reputation: 2711

convert string to dynamic array with variables in javascript

How would I take a string (that I got from a page using jQuery's text()) such as:

var myData = "[{name:'xxx',data:[1,2,3,4,5]},{name:'yyy',data:[5,4,3,2,1]}]"; //this is a string :(

And turn it into the actual javascript object that I need, so for example:

var myObject = [{name:'xxx',data:[1,2,3,4,5]},{name:'yyy',data:[5,4,3,2,1]}];

So 'name' and 'data' will be non-dynamic variables, however names value, the data array and the length of myObject will be dynamic.

Not really sure where to start with this one. I am guessing that I will have to do a whole lot of spliting and looping, but I am open to suggestions.

Upvotes: 1

Views: 1681

Answers (2)

Agustin Meriles
Agustin Meriles

Reputation: 4854

You mean,

var myObject = eval('(' + myData + ')');

?

EDIT

Its major con is that you can put any javascript code (not only JSON) to eval (Chrome's F12 lets anyone to exploit this). AS you are using jQuery, best choice will be

var myObject = $.parseJSON(myData);

for cross browser compatibility.

$.parseJSON

Takes a well-formed JSON string and returns the resulting JavaScript object. Passing in a malformed JSON string may result in an exception being thrown. For example, the following are all malformed JSON strings:

{test: 1} (test does not have double quotes around it).

{'test': 1} ('test' is using single quotes instead of double quotes).

Upvotes: 0

Guffa
Guffa

Reputation: 700562

Well, it can be done very easily:

var myObject = eval(myData);

However, you should be aware of the risks of the eval function. As it runs the value as a Javascript expression, it would also run any harmful code that would be in the string, so you should only use it when you have full control over what's in the string.

If you could change the format to be JSON, you could safely parse it without risks of code injection:

var myData = '[{"name":"xxx","data":[1,2,3,4,5]},{"name":"yyy","data":[5,4,3,2,1]}]';

var myObject = $.parseJSON(myData);

Upvotes: 2

Related Questions