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.

Share:
61,378

Related videos on Youtube

Ankit_Shah55
Author by

Ankit_Shah55

Hello

Updated on March 13, 2020

Comments

  • Ankit_Shah55
    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

  • Samuel Caillerie
    Samuel Caillerie over 11 years
    Yes but now it does not corresponds to the requirement :)
  • Subir Kumar Sao
    Subir Kumar Sao over 11 years
    FYI It should also work with eval. But it is not recommended to use eval for security reasons.
  • Ankit_Shah55
    Ankit_Shah55 over 11 years
    @trebuchet Thanks, why eval is a security risk?
  • IberoMedia
    IberoMedia almost 11 years
    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]}
  • Michael J. Calkins
    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
    Dexygen over 8 years
    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?
  • BuddhiP
    BuddhiP over 7 years
    Is there a library to handle this?
  • Pimp Trizkit
    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
    Zachary Raineri over 3 years
    Awesome thank you! This should be the accepted answer