I need to encode a javascript function into a JSON object in PHP.
This:
$function = \"function(){}\";
$message = \"Hello\";
$json = array(
As Jani said, this is not possible directly with JSON, but this might help you: http://web.archive.org/web/20080828165256/http://solutoire.com/2008/06/12/sending-javascript-functions-over-json/
You can try this:
var json_string = '{"message":"Hello","myfunc":"function(){ alert(this.message) }"}';
var json_string = JSON.parse(json_string, function(k,v){
if(typeof v == 'string' && /function\(\)\{/.test(v)){
return eval(k+' = '+v);
}else{
return v
}
});
This function can also help:
function jsonify($var){
return str_ireplace(array("'function",'"function',"}'",'}"'),array("function",'function',"}",'}'),json_encode($var));
}
Taken from here: http://network.convergenceservices.in/forum/105-uknowva-development/4710-introducing-convhelperjsonify-in-uknowva-251.html#4710