javascript string to object
61,378
Solution 1
var str='{"a":"www"}';
var obj = JSON.parse(str);
Solution 2
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.
Related videos on Youtube
Comments
-
Ankit_Shah55 about 4 years
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
-
HellaMad over 11 yearsPossible duplicate of stackoverflow.com/questions/6487167/…
-
Peter O. over 11 yearspossible duplicate of String to object in JS
-
0lukasz0 almost 11 yearspossible duplicate of Safely turning a JSON string into an object
-
Admin about 10 yearsIf at all possible, you should use valid JSON. eval() is rarely a good idea
-
-
Samuel Caillerie over 11 yearsYes but now it does not corresponds to the requirement :)
-
Subir Kumar Sao over 11 yearsFYI It should also work with eval. But it is not recommended to use eval for security reasons.
-
Ankit_Shah55 over 11 years@trebuchet Thanks, why eval is a security risk?
-
IberoMedia almost 11 yearsfor 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]}
-
Michael J. Calkins almost 11 years@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.
-
Dexygen over 8 yearsI 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?
-
BuddhiP over 7 yearsIs there a library to handle this?
-
Pimp Trizkit about 7 years@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.
-
Zachary Raineri over 3 yearsAwesome thank you! This should be the accepted answer