How to convert this javascript string to javascript array / object

Possible duplicate:
How to easily parse JSON?

I have this line:

[{text: 'First Option', value: 'first'},{text: 'Second Option', value: 'second'},{text: 'Third Option', value: 'third'}] 

How to convert it to an array / object in the same form in javascript?

+8
javascript
source share
5 answers

Can var data = JSON.parse(yourString); or var data = eval('(' + yourString+ ')');

+24
source share

This is one of the cases where eval really useful:

 var x = eval(yourString); 

But it is definitely safer to use JSON.parse , as suggested by other answers.

Here's a working example of the eval version.

+9
source share

Use JSON.parse

 var obj = JSON.parse(str); 
+1
source share

Just set the variable exactly to this line.

 var new_object = [{text: 'First Option', value: 'first'},{text: 'Second Option', value: 'second'},{text: 'Third Option', value: 'third'}] 
0
source share

If you are jave jQuery, you can use jQuery.parseJSON . If you do not, you can pull the function from the source code and place it on your page and have the same benefits.

0
source share

All Articles