Tuesday, February 8, 2011

Can anyone explain this PHP code using json_encode and json_decode?

  $a = '{ "tag": "<b></b>" }';
  echo json_encode( json_decode($a) );

This outputs:

{"tag":"<b><\/b>"}

when you would think it would output exactly the input. For some reason json_encode adds an extra slash.

  • Because it's part of the JSON standard

    http://json.org/

    char

    any-Unicode-character-
        except-"-or-\-or-
        control-character
    \"
    \\
    \/ <---- see here?
    \b
    \f
    \n
    \r
    \t
    \u four-hex-digits
    
  • That's probably a security-feature. The escaped version (Eg. the output) would be parsed as similar to the unescaped-version, by Javascript (Eg. \/ becomes /). Having escaped the slash like that, there is a lesser chance of the browser misinterpreting the Javascript-string as HTML. Of course, if you treat the data correct, this shouldn't be needed, so it's more a safeguard against a clueless programmer messing things up for himself.

    From troelskn
  • Your input is not valid JSON, but PHP's JSON parser (like most JSON parsers) will parse it anyway.

    John Millikin : What's invalid about it?

0 comments:

Post a Comment