Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
add comment

4 Answers

up vote 8 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
add comment

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
add comment

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
add comment

you cannot do it with json_encode but u can do it afterwards in javascript

json = {"message":"Hello","func":"function(){ alert(this.message) }"}

javascript:

eval('json.func = '+json.func);

call:

json.func();
share|improve this answer
add comment

Your Answer

 
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.