PHP's json_encode does not escape all JSON control characters

后端 未结 12 1021
旧时难觅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:37

    Converting to and fro from PHP should not be an issue. PHP's json_encode does proper encoding but reinterpreting that inside java script can cause issues. Like

    1) original string - [string with nnn newline in it] (where nnn is actual newline character)

    2) json_encode will convert this to [string with "\\n" newline in it] (control character converted to "\\n" - Literal "\n"

    3) However when you print this again in a literal string using php echo then "\\n" is interpreted as "\n" and that causes heartache. Because JSON.parse will understand a literal printed "\n" as newline - a control character (nnn)

    so to work around this: -

    A) First encode the json object in php using json_enocde and get a string. Then run it through a filter that makes it safe to be used inside html and java script.

    B) use the JSON string coming from PHP as a "literal" and put it inside single quotes instead of double quotes.


    title = $title ;
            $book->description = $description ;
            $strBook = json_encode($book);
            $strBook = form_safe_json($strBook);
    
            ?>
    
    
        
        
    
            
                 title
    
                
    
    
                
    
    
                
    
            
    
             
    
                 

    Json parsing test page

    Put the string inside single quote in java script. Putting JSON string inside double quotes would cause the parser to fail at attribute markers (something like { "id" : "value" } ). No other escaping should be required if you put the string as "literal" and let JSON parser do the work.

提交回复
热议问题