【问题标题】:PHP json_encode and javascript functionsPHP json_encode 和 javascript 函数
【发布时间】:2023-03-31 14:11:01
【问题描述】:

我需要在 PHP 中将 javascript 函数编码为 JSON 对象。

这个:

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

$json = array(   
      'message' => $message,
      'func' => $function
);
echo json_encode($json);

输出:

{"message":"Hello","func":"function(){}"}

我想要的是:

{"message":"Hello","func":function(){}}

我可以用 json_encode 做到这一点吗?

【问题讨论】:

    标签: php javascript json


    【解决方案1】:

    正如 Jani 所说,直接使用 JSON 是不可能的,但这可能会对您有所帮助:http://web.archive.org/web/20080828165256/http://solutoire.com/2008/06/12/sending-javascript-functions-over-json/

    【讨论】:

    • 可以,只要你用eval解析它而不是使用严格的JSON解析器。
    • Eval=你知道的邪恶
    【解决方案2】:

    没有。 JSON 规范不支持函数。您可以编写自己的代码以类似 JSON 的格式输出它,但它应该可以正常工作。

    【讨论】:

      【解决方案3】:

      json_decode 将给定的数组解析为 json 字符串,因此您可以将其作为字符串使用。只需使用一些唯一的字符串来指示函数的开始和结束。然后使用 str_replace 删除引号。

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

      输出将是:

      {"message":"Hello","func":function(){}}
      

      【讨论】:

      • 一个可以使用字符的小变种:preg_match_all('/\#([^\#]*)\#/', json_encode($json), $unescape); foreach ($unescape['0'] as $key => $fn) { $string = str_replace($fn, json_decode($unescape['0'][$key]), $string); }
      【解决方案4】:

      如果不想编写自己的 JSON 编码器,您可以求助于 Zend_Json,这是 Zend 框架的 JSON 编码器。它包括处理JSON expressions 的能力。

      【讨论】:

      【解决方案5】:

      我写了一个small library 允许这样做。它类似于 Zend 框架的解决方案,但是这个库更轻量级,因为它使用了内置的 json_encode 函数。它也更容易与外部库一起使用,其中json_encode 深埋在供应商代码中。

      <?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>
      

      【讨论】:

      • 看起来不错的实现,但主要限制是 "require": {"php": "&gt;=7.0"}, "require-dev": {"phpunit/phpunit": "^7.1"}zend-json 不同,zend-json 具有 "require": {"php": "^5.6 || ^7.0"}, "require-dev": {"phpunit/phpunit": "^5.7.23 || ^6.4.3", "zendframework/zend-coding-standard": "~1.0.0", "zendframework/zend-stdlib": "^2.7.7 || ^3.1"} 的依赖项。简而言之,您的库不适用于php 5.6
      • @Fr0zenFyr PHP 5.6 一直支持到 2017 年 1 月,并在 2018 年底之前收到了安全更新。关键是你不应该使用 PHP 5.6,因为它已经到了生命的尽头。
      • 同意 100%。但有时企业出于多种不同原因决定支持旧版应用程序。
      【解决方案6】:

      我为所有基于 json 函数的帮助我的 myabe 帮助某人编写了这个简单的函数:

      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;
      }
      

      【讨论】:

      • @luky 我在一些项目和工作中使用了这个功能,为什么兄弟?
      • 嗨兄弟,因为我想试试哈哈。但我以mirmidon的回答结束。谢谢
      【解决方案7】:

      你可以试试这个:

      var json_string = '{"message":"Hello","myfunc":"function(){ alert(this.message) }"}';
      var json_string = JSON.parse(json_string, function(k,v){
          if(typeof v == 'string' && /function\(\)\{/.test(v)){
              return eval(k+' = '+v); 
          }else{
              return v
          }
      });
      

      【讨论】:

        【解决方案8】:

        PHP 中的结尾部分似乎现在已经解决了。你可以使用

        json_encode($p, JSON_UNESCAPED_UNICODE)

        这样你的函数就不会被转义。不过

        【讨论】:

        【解决方案9】:

        这个功能也有帮助:

        function jsonify($var){
        return str_ireplace(array("'function",'"function',"}'",'}"'),array("function",'function',"}",'}'),json_encode($var));
        }
        

        取自这里:http://network.convergenceservices.in/forum/105-uknowva-development/4710-introducing-convhelperjsonify-in-uknowva-251.html#4710

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-04
          • 2011-10-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多