[ACCEPTED]-PHP json_encode and javascript functions-json

Accepted answer
Score: 24

As Jani said, this is not possible directly 1 with JSON, but this might help you: http://web.archive.org/web/20080828165256/http://solutoire.com/2008/06/12/sending-javascript-functions-over-json/

Score: 9

No. JSON spec does not support functions. You 3 can write your own code to output it in 2 a JSON-like format and it should work fine 1 though.

Score: 9

json_decode parse the given array to json 4 string, so you can play with it as a string. Just 3 use some unique string to indicate the start 2 and the end of the function. Then use str_replace 1 to remove the quotes.

$function = "#!!function(){}!!#"; 
$message = "Hello";

$json = array(   
  'message' => $message,
  'func' => $function
$string = json_encode($json);
$string = str_replace('"#!!','',$string);
$string = str_replace('!!#"','',$string);
echo $string;

The output will be:

Score: 8

If don't want to write your own JSON encoder 3 you can resort to Zend_Json, the JSON encoder for 2 the Zend Framework. It includes the capability 1 to cope with JSON expressions.

Score: 3

I wrote a small library that allows to do this. It's 5 similar to Zend framworks's solution, but 4 this library is much more lightweight as 3 it uses the built-in json_encode function. It is also 2 easier to use with external libraries, where 1 json_encode is buried deeply in vendor code.

    use Balping\JsonRaw\Raw;
    use Balping\JsonRaw\Encoder;

    $array = [
        'type' => 'cat',
        'count' => 42,
        'callback' => new Raw('function(a){alert(a);}')

    let bar = <?php echo Encoder::encode($array); ?>
    bar.callback('hello'); //prints hello
Score: 0

I write this simple function for all json 1 function based help my myabe help someone:

function json_encode_ex($array) {
    $var = json_encode($array);
    preg_match_all('/\"function.*?\"/', $var, $matches);
    foreach ($matches[0] as $key => $value) {
        $newval = str_replace(array('\n', '\t','\/'), array(PHP_EOL,"\t",'/'), trim($value, '"'));
        $var = str_replace($value, $newval, $var);
    return $var;

More Related questions