views:

746

answers:

3

I need to encode a javascript function into a JSON object in PHP.

This:

$function = "function(){}";
$message = "Hello";

$json = array(   
      'message' => $message,
      'func' => $function
);
echo json_encode($json);

outputs:

{"message":"Hello","func":"function(){}"}

What I want is:

{"message":"Hello","func":function(){}}

Can I do this with json_encode?

+5  A: 

No. JSON spec does not support functions. You can write your own code to output it in a JSON-like format and it should work fine though.

Jani Hartikainen
+3  A: 

As Jani said, this is not possible directly with JSON, but this might help you : http://solutoire.com/2008/06/12/sending-javascript-functions-over-json/

Fabien Ménager
That works, although it's not really JSON anymore.
Matthew Crumley
It is a valid JavaScript/Jscript/ECMAScript object, right?
David Murdoch
Yes, as long as you parse it with `eval` instead of using a strict JSON parser.
Matthew Crumley
+1  A: 

If don't want to write your own JSON encoder you can resort to Zend_Json, the JSON encoder for the Zend Framework. It includes the capability to cope with JSON expressions.

Stefan Gehrig
Good Lord, this is awesome.
Stephen J. Fuhry