Reputation: 18558
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.
Upvotes: 1
Views: 100
Reputation: 207501
Example with new Function
var str = "{ name: 'John' }";
var fnc = new Function( "return " + str );
var obj = fnc();
console.log(obj.name);
Upvotes: 2
Reputation: 923
You could use eval().
var str = "{ name: 'John' }";
var obj = eval("(" + str + ")");
Upvotes: 1