28

How to apply string object value to a variable Ex.

var str='{a:"www"}'

Now how to set

var obj={a:"www"}

I try eval() but not working

4

2 Answers 2

45

eval should work, and it's actually a MDN solution, not to mention that your string is not a valid JSON, so eval is your only option (if you don't want to include a library for that).

var str='{a:"www"}';
var obj=eval("("+str+")");
console.log(obj);

Quick test in Chrome Dev Tool:

eval("("+'{a:"www"}'+")")
Object
    a: "www"
    __proto__: Object

Just remember to wrap your string in parenthesis and assign it outside eval and it'll be (relatively) safe.

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

4 Comments

I wasn't wrapping mine in parentheses and I was getting an error. Wrapping the object's string representation in parentheses before calling eval() worked for me too, but why are the parentheses necessary?
Is there a library to handle this?
@GeorgeJempty - According to the MDN Those are needed to declare a function, which I guess is the same for an object. If you are passing a string containing a list of statements, it should work.
Awesome thank you! This should be the accepted answer
27
var str='{"a":"www"}';
var obj = JSON.parse(str);

5 Comments

Yes but now it does not corresponds to the requirement :)
FYI It should also work with eval. But it is not recommended to use eval for security reasons.
@trebuchet Thanks, why eval is a security risk?
for strings that were stored as JSON_stringify trebuchet solution works. I had string "{"1":["2013-05-10","3","#f70707"]}" and after JSON.parser I got Object {1: Array[3]}
@Ankit_Shah55 The only time eval becomes a problem is when User1's input is interpreted as javscript on User2. User2 is then taken to a horrible pornography site and his wife walks in. User2 then goes through a terrible divorce and never sees his children again. But that's just one way.

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.