PHP json_encode and javascript functions

后端 未结 9 1402
别跟我提以往
别跟我提以往 2020-12-06 04:28

I need to encode a javascript function into a JSON object in PHP.

This:

$function = \"function(){}\";
$message = \"Hello\";

$json = array(   
               


        
相关标签:
9条回答
  • 2020-12-06 04:43

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

    <?php
        use Balping\JsonRaw\Raw;
        use Balping\JsonRaw\Encoder;
    
        $array = [
            'type' => 'cat',
            'count' => 42,
            'callback' => new Raw('function(a){alert(a);}')
        ];
    ?>
    
    <script>
        let bar = <?php echo Encoder::encode($array); ?>
        bar.callback('hello'); //prints hello
    </script>
    
    0 讨论(0)
  • 2020-12-06 04:46

    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.

    0 讨论(0)
  • 2020-12-06 04:47

    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.

    0 讨论(0)
  • 2020-12-06 04:48

    json_decode parse the given array to json string, so you can play with it as a string. Just use some unique string to indicate the start and the end of the function. Then use str_replace 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:

    {"message":"Hello","func":function(){}}
    
    0 讨论(0)
  • 2020-12-06 04:52

    I write this simple function for all json 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;
    }
    
    0 讨论(0)
  • 2020-12-06 04:53

    The enconding part in PHP is seems to be solved by now. You can use

    json_encode($p, JSON_UNESCAPED_UNICODE)

    this way your function will not be escaped. However

    0 讨论(0)
提交回复
热议问题