1

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.

2
  • I'd prefer avoiding eval and make the source produce proper JSON. Commented Oct 3, 2014 at 1:25
  • Starting with JSON is best, as @Thilo suggested. Parsing strings with 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. Commented Jun 30, 2020 at 1:32

3 Answers 3

2

Example with new Function

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

Sign up to request clarification or add additional context in comments.

4 Comments

@QuinnComendant new Function is evaluating it so not as safe as you think.
Yikes! You're correct: var f = new Function("return " + "alert(1);"); f(); does execute alert(1). 😵
Weird you pick my answer to post that comment and the real solution is, return proper JSON.
Sorry, it just followed from learning new Function isn't safe. I've moved my comment to the OP's question. 😳
1

From the previous question

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

1 Comment

Ahhh, now I see what you're saying. So sorry that was so difficult for me to understand. Thanks for your help!
1

You could use eval().

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.