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();});
– matheus
I updated the answer. It’s just that in this case you don’t need the
JSON.parse
, jQuery already does it for you.– bfavaretto
Thank you very much.
– matheus