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.
Example with new Function
var str = "{ name: 'John' }";
var fnc = new Function( "return " + str );
var obj = fnc();
console.log(obj.name);
var f = new Function("return " + "alert(1);"); f(); does execute alert(1). 😵new Function isn't safe. I've moved my comment to the OP's question. 😳From the previous question
s="{ name: 'John'}";
eval('x='+s);
evaland make the source produce proper JSON.eval(…),require(…),new Function(…),document.createElement('script'), etc, will cause the code in the string to be executed, which is probably dangerous if the string comes from outside your program. If your only source of data is JS object literals, the best way may be to use an AST parser such as Esprima as suggested here.