I have a string that contains all the characters for a javascript object:

string_object = "{question_text: 'q 1', ans_1: 'yes', ans_2: 'no'},
{question_text: 'q 2', ans_1: 'United', ans_2: 'City'},
{question_text: 'q 3', ans_1: 'over', ans_2: 'under'},
{question_text: 'q 4', ans_1: 'over', ans_2: 'under'},
{question_text: 'q 5', ans_1: 'over', ans_2: 'under'},
{question_text: 'q 6', ans_1: 'over', ans_2: 'under'},"

I want to convert this to a javascript object, so I can do all sorts of useful things with it like object[0].question_text.

Is there a way of converting this directly to an object? The answers I've seen involve basically regex'ing the string to change it to perfect JSON, and then JSON.parse() it.

1 Answers

-2
Shridhar Sharma On Best Solutions

Check this out

var string_object = "{question_text: 'q 1', ans_1: 'yes', ans_2: 'no'},{question_text: 'q 2', ans_1: 'United', ans_2: 'City'},{question_text: 'q 3', ans_1: 'over', ans_2: 'under'},{question_text: 'q 4', ans_1: 'over', ans_2: 'under'},{question_text: 'q 5', ans_1: 'over', ans_2: 'under'},{question_text: 'q 6', ans_1: 'over', ans_2: 'under'},"

var obj = eval('(['+string_object+'])')

console.log(obj)