9

Possible Duplicate:
How to parse JSON easily?

I have this string:

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

How do I convert it into an array/object in the same form in javascript?

Community
  • 1
  • 1
user991987
  • 213
  • 1
  • 3
  • 7

5 Answers5

25

Could either use var data = JSON.parse(yourString); or var data = eval('(' + yourString+ ')');

Ritesh Mengji
  • 6,000
  • 9
  • 30
  • 46
9

This is one of the times that eval actually comes in useful:

var x = eval(yourString);

But it's definitely safer to use JSON.parse as suggested by other answers.

Here's a working example of the eval version.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • 4
    To properly eval a string like this, you will actually need to wrap it in parentheses, e.g. `var x = eval('(' + yourString + ')')`, otherwise you will get a `SyntaxError`. – Jon Newmuis Oct 12 '11 at 18:09
  • @BradChristie - Yup, I agree! But if jQuery can't be used, and you need to support older browsers... – James Allardice Oct 12 '11 at 18:09
  • 1
    DO NOT USE EVAL .... its the root of all evil ... along with mushrooms !!! – Manse Oct 12 '11 at 18:10
1

Use JSON.parse

var obj = JSON.parse(str);
Clive
  • 36,918
  • 8
  • 87
  • 113
0

Just set a variable to exactly that string.

var new_object = [{text: 'First Option',  value: 'first'},{text: 'Second Option', value: 'second'},{text: 'Third Option',  value: 'third'}]
Brian Hoover
  • 7,861
  • 2
  • 28
  • 41
  • 2
    Something tells me it's not a matter of "how do I copy/paste this in javascript and get an object" (though I may be wrong). – Brad Christie Oct 12 '11 at 18:11
0

If you jave jQuery, you can use jQuery.parseJSON. If you don't you can pull the function from the source code and place it on your page and have the same advantages.

Brad Christie
  • 100,477
  • 16
  • 156
  • 200