BeachRunnerFred
BeachRunnerFred

Reputation: 18558

How can I convert the string of a JavaScript object literal to a JavaScript object literal?

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

Answers (3)

epascarello
epascarello

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

Leo
Leo

Reputation: 4428

From the previous question

s="{ name: 'John'}";
eval('x='+s);

Upvotes: 1

svanryckeghem
svanryckeghem

Reputation: 923

You could use eval().

var str = "{ name: 'John' }";
var obj = eval("(" + str + ")");

Upvotes: 1

Related Questions