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?
The json_encode() function is used to encode a value to JSON format.
JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.
To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.
Syntax. The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With