0

Here is a string:

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

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

11
  • 3
    aa:function(){} , this not json Commented Apr 18, 2018 at 9:02
  • eventually eval, if you are sure about the content. Commented Apr 18, 2018 at 9:02
  • eval doesn't work for it too. Commented Apr 18, 2018 at 9:04
  • 1
    This is not a valid JSON string Commented Apr 18, 2018 at 9:04
  • 1
    @MarioMurrent: OP didn't say it was valid JSON though... Commented Apr 18, 2018 at 9:14

3 Answers 3

2

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);

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

1 Comment

To complete your answer, it can also be achieved with var obj = eval('(' + string + ')'). (Using parantheses so that the object is not parsed as a block)
1

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);

Comments

0

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();

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.