Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP json_encode and javascript functions

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?

like image 301
David Murdoch Avatar asked Nov 16 '09 22:11

David Murdoch


People also ask

What is json_encode function in PHP?

The json_encode() function is used to encode a value to JSON format.

What is json_encode and Json_decode in PHP?

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.

How can I get JSON encoded data in PHP?

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.

What does json_encode return?

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.


2 Answers

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/

like image 183
Fabien Ménager Avatar answered Oct 16 '22 02:10

Fabien Ménager


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.

like image 27
Jani Hartikainen Avatar answered Oct 16 '22 01:10

Jani Hartikainen