PHP's json_encode does not escape all JSON control characters

后端 未结 12 950
旧时难觅i
旧时难觅i 2020-11-28 12:08

Is there any reasons why PHP\'s json_encode function does not escape all JSON control characters in a string?

For example let\'s take a string which spans two rows a

相关标签:
12条回答
  • 2020-11-28 12:15

    I don't fully understand how var_export works, so I will update if I run into trouble, but this seems to be working for me:

    <script>
        window.things = JSON.parse(<?php var_export(json_encode($s)); ?>);
    </script>
    
    0 讨论(0)
  • 2020-11-28 12:16

    Maybe I'm blind, but in your example they ARE escaped. What about

    <script type="text/javascript">
    
    JSON.parse("<?php echo $s ?>");  // Will throw SyntaxError 
    
    </script>
    

    (note different quotes)

    0 讨论(0)
  • 2020-11-28 12:20

    This is what I use personally and it's never not worked. Had similar problems originally.

    Source script (ajax) will take an array and json_encode it. Example:

    $return['value'] = 'test';
    $return['value2'] = 'derp';
    
    echo json_encode($return);
    

    My javascript will make an AJAX call and get the echoed "json_encode($return)" as its input, and in the script I'll use the following:

    myVar = jQuery.parseJSON(msg.replace(/&quot;/ig,'"'));
    

    with "msg" being the returned value. So, for you, something like...

    var msg = '<?php echo $s ?>';
    myVar = jQuery.parseJSON(msg.replace(/&quot;/ig,'"'));
    

    ...might work for you.

    0 讨论(0)
  • 2020-11-28 12:23

    I still haven't figured out any solution without str_replace..

    Try this code.

    $json_encoded_string = json_encode(...);
    $json_encoded_string = str_replace("\r", '\r', $json_encoded_string);
    $json_encoded_string = str_replace("\n", '\n', $json_encoded_string);
    

    Hope that helps...

    0 讨论(0)
  • 2020-11-28 12:29
    function escapeJsonString($value) {
        # list from www.json.org: (\b backspace, \f formfeed)    
        $escapers =     array("\\",     "/",   "\"",  "\n",  "\r",  "\t", "\x08", "\x0c");
        $replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t",  "\\f",  "\\b");
        $result = str_replace($escapers, $replacements, $value);
        return $result;
      }
    

    I'm using the above function which escapes a backslash (must be first in the arrays) and should deal with formfeeds and backspaces (I don't think \f and \b are supported in PHP).

    0 讨论(0)
  • 2020-11-28 12:30

    Just an addition to Greg's response: the output of json_encode() is already contained in double-quotes ("), so there is no need to surround them with quotes again:

    <script type="text/javascript">
        JSON.parse(<?php echo $s ?>);
    </script>
    
    0 讨论(0)
提交回复
热议问题