How to execute a javascript function from a json file

5

I have a json file that is generated by php and it looks like this:

{
     "status":200,
     "command":"faca algo",
      "action":"function (){document.write('quer que eu faça algo?');}",
      "type":"acao"
}

How to execute the function that is in the file?

    
asked by anonymous 07.10.2014 / 02:23

1 answer

6

Technically, this is not a function because JSON does not have functions. It is a string with the source code of a function inside. What you can do to execute is to use eval ( worth reading the content of the link to understand the dangers associated with it):

var json = '{"status":200,"command":"faca algo","action":"function (){document.write(\'quer que eu faça algo?\'); }","type":"acao"}';
var obj = JSON.parse(json);
// Guarda a função num objeto
var funcao = eval('(' + obj.action + ')');
// Executa a função
funcao();

link

If you are using jQuery to get JSON, jQuery itself already takes care of parse :

$.getJSON("meuendereco.com/json.json", function (data){
    var funcao = eval('(' + data.action + ')'); 
    // Executa a função 
    funcao();
}); 

See also: Using eval () in javascript: what are the pros and cons?     

07.10.2014 / 02:37