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?

link|improve this question

80% accept rate
feedback

3 Answers

up vote 4 down vote accepted

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/

link|improve this answer
1  
That works, although it's not really JSON anymore. – Matthew Crumley Nov 17 '09 at 3:12
It is a valid JavaScript/Jscript/ECMAScript object, right? – David Murdoch Nov 17 '09 at 18:26
Yes, as long as you parse it with eval instead of using a strict JSON parser. – Matthew Crumley Nov 18 '09 at 2:53
feedback

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.

link|improve this answer
1  
Good Lord, this is awesome. – Stephen J. Fuhry Dec 3 '09 at 19:15
feedback

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.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.