How to run a javascript function from a json file

Asked

Viewed 1,854 times

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 perform the function that is in the file?

1 answer

6


Technically, this is not a function, as JSON does not contain functions. It is a string with the source code of a function inside. What you can do to run is to use the 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();

http://jsbin.com/qonesiluyolo/1/edit

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

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

See also: Javascript usage of Eval(): what are the pros and cons?

  • did not give when I used $.getJSON("meuendereco.com/json.json", Function (data){var obj = JSON.parse(data); // Stores the function in an object var function = Eval('(' + obj.action + ')'); // Executes the function function();});

  • I updated the answer. It’s just that in this case you don’t need the JSON.parse, jQuery already does it for you.

  • Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.