Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can I convert the string...

"{ name: 'John' }"

...to an actual JavaScript object literal that will allow me to access the data using its keys (I.e. varname["name"] == "John")? I can't use JSON.parse(), since the string is invalid JSON.

share|improve this question
    
I'd prefer avoiding eval and make the source produce proper JSON. –  Thilo 1 hour ago

3 Answers 3

up vote 1 down vote accepted

From the previous question

s="{ name: 'John'}";
eval('x='+s);
share|improve this answer
1  
Ahhh, now I see what you're saying. So sorry that was so difficult for me to understand. Thanks for your help! –  BeachRunnerFred 1 hour ago

You could use eval().

var str = "{ name: 'John' }";
var obj = eval("(" + str + ")");
share|improve this answer

Example with new Function

var str = "{ name: 'John' }";
var fnc = new Function( "return " + str );
var obj = fnc();
console.log(obj.name);

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.