Fei Sun
Fei Sun

Reputation: 518

Convert object string to JS object

Here is a string:

"{aa:function(){},bb:document.body}"

JSON.parse doesn't work for this,how to convert it to JS object?

Upvotes: 0

Views: 97

Answers (3)

Asons
Asons

Reputation: 87191

An option in this case could be to use new Function().

It is less evil than eval(), and here is an answer with an explanation about their difference:

Stack snippet

var string = "{aa:function(){},bb:document.body}",
    object;
    
object = new Function( 'return (' + string + ')' )();

console.log(object);

Upvotes: 1

Felipe Plazas
Felipe Plazas

Reputation: 334

In case you need to treat the string as a json object:

let str = "{\"aa\":\"function() { console.log('Look mama no hands'); }\",\"bb\":\"document.body\"}";
let obj = JSON.parse(str);
let func = null;
eval("func = "+obj.aa);
func();

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386520

You could use eval with a prepended assingment.

Caveat: Why is using the JavaScript eval function a bad idea?

var string = "{aa:function(){},bb:document.body}",
    object;
    
eval('object = ' + string);

console.log(object);

Upvotes: 2

Related Questions