任何人都可以使用json_encode和json_decode解释这个PHP代码吗?

时间:2023-01-04 20:06:24
  $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.

当你认为它会输出完全输入时。由于某种原因,json_encode添加了额外的斜杠。

4 个解决方案

#1


18  

Because it's part of the JSON standard

因为它是JSON标准的一部分

http://json.org/

char

any-Unicode-character-
    except-"-or-\-or-
    control-character
\"
\\
\/ <---- see here?
\b
\f
\n
\r
\t
\u four-hex-digits

#2


3  

use this:

echo json_encode($a,JSON_HEX_TAG)

Result will be:

结果将是:

["\u003C\u003E"]

You can read this article to improve your knowledge about JSON_ENCODE http://php.net/manual/en/function.json-encode.php

您可以阅读本文以提高您对JSON_ENCODE的了解http://php.net/manual/en/function.json-encode.php

#3


2  

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.

这可能是一个安全功能。转义版本(例如输出)将被解析为与未转义版本类似,通过Javascript(例如\ /成为/)。像这样逃避了斜线,浏览器错误解释Javascript字符串的可能性很小。当然,如果你对数据的处理是正确的,那么就不需要这样做,所以它更能防止一个无能为力的程序员为自己弄乱。

#4


2  

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

您的输入不是有效的JSON,但PHP的JSON解析器(像大多数JSON解析器一样)无论如何都会解析它。

#1


18  

Because it's part of the JSON standard

因为它是JSON标准的一部分

http://json.org/

char

any-Unicode-character-
    except-"-or-\-or-
    control-character
\"
\\
\/ <---- see here?
\b
\f
\n
\r
\t
\u four-hex-digits

#2


3  

use this:

echo json_encode($a,JSON_HEX_TAG)

Result will be:

结果将是:

["\u003C\u003E"]

You can read this article to improve your knowledge about JSON_ENCODE http://php.net/manual/en/function.json-encode.php

您可以阅读本文以提高您对JSON_ENCODE的了解http://php.net/manual/en/function.json-encode.php

#3


2  

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.

这可能是一个安全功能。转义版本(例如输出)将被解析为与未转义版本类似,通过Javascript(例如\ /成为/)。像这样逃避了斜线,浏览器错误解释Javascript字符串的可能性很小。当然,如果你对数据的处理是正确的,那么就不需要这样做,所以它更能防止一个无能为力的程序员为自己弄乱。

#4


2  

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

您的输入不是有效的JSON,但PHP的JSON解析器(像大多数JSON解析器一样)无论如何都会解析它。