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?

0

5 Answers 5

25

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

1
  • 1
    JSON.parse() will not work with this string! Commented Jun 6, 2018 at 12:20
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.

3
  • 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. Commented Oct 12, 2011 at 18:09
  • @BradChristie - Yup, I agree! But if jQuery can't be used, and you need to support older browsers... Commented Oct 12, 2011 at 18:09
  • 1
    DO NOT USE EVAL .... its the root of all evil ... along with mushrooms !!! Commented Oct 12, 2011 at 18:10
1

Use JSON.parse

var obj = JSON.parse(str);
2
  • 2
    invalid JSON, that string won't parse Commented Oct 12, 2011 at 18:08
  • 1
    JSON is an Object but Object isn't necessarily JSON..therefore this way is not the intended path to go. Commented Sep 4, 2015 at 18:04
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'}]
1
  • 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). Commented Oct 12, 2011 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.

1
  • That is the same as JSON.parse() ... Commented Sep 4, 2015 at 18:06

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.