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?

share|improve this question

3 Answers

up vote 6 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/

share|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

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.

share|improve this answer

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.

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

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

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