PHP的json_encode不会转义所有JSON控制字符 [英] PHP's json_encode does not escape all JSON control characters
问题描述
PHP的json_encode函数不能不对字符串中的所有 JSON 控制字符进行转义吗?
Is there any reasons why PHP's json_encode function does not escape all JSON control characters in a string?
例如,让我们以一个跨越两行并包含控制字符(\ r \ n"/\)的字符串为例:
For example let's take a string which spans two rows and has control characters (\r \n " / \) in it:
<?php
$s = <<<END
First row.
Second row w/ "double quotes" and backslash: \.
END;
$s = json_encode($s);
echo $s;
// Will output: "First row.\r\nSecond row w\/ \"double quotes\" and backslash: \\."
?>
请注意,回车符和换行符不转义.为什么?
Note that carriage return and newline chars are unescaped. Why?
我使用jQuery作为JS库,并且当您完全100%信任传入的数据时,它的$ .getJSON()函数可以正常工作.否则,我像其他人一样使用JSON.org的库json2.js. 但是,如果您尝试解析该编码字符串,则会引发错误:
I'm using jQuery as my JS library and it's $.getJSON() function will do fine when you fully, 100% trust incoming data. Otherwise I use JSON.org's library json2.js like everybody else. But if you try to parse that encoded string it throws an error:
<script type="text/javascript">
JSON.parse(<?php echo $s ?>); // Will throw SyntaxError
</script>
您无法获取数据!如果您在该字符串中删除或转义\ r \ n和\,则JSON.parse()不会引发错误.
And you can't get the data! If you remove or escape \r \n " and \ in that string then JSON.parse() will not throw error.
是否存在任何用于转义控制字符的良好PHP功能.带有搜索和替换数组的简单str_replace无效.
Is there any existing, good PHP function for escaping control characters. Simple str_replace with search and replace arrays will not work.
推荐答案
D'oh-您需要进行双重编码:JSON.parse当然需要一个字符串:
D'oh - you need to double-encode: JSON.parse is expecting a string of course:
<script type="text/javascript">
JSON.parse(<?php echo json_encode($s) ?>);
</script>
这篇关于PHP的json_encode不会转义所有JSON控制字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!