[英]PHP's json_encode and JS's JSON.stringify
I'm using both PHP and Javascript to build some kind of web service. 我正在使用PHP和Javascript来构建某种Web服务。 I try to validate a token calculated on post parameters, sent from JS to PHP. 我尝试验证从JS发送到PHP的post参数计算的令牌。 Let's say the code is as follows: 假设代码如下:
JS : JS:
token = JSON.stringify(params);
PHP : PHP:
token = json_encode($_POST);
Can somebody please explain me why the two resulting JSON strings doesn't have the same length ? 有人可以解释一下为什么两个生成的JSON字符串长度不一样吗?
(I tried to trim \\n\\r\\t
in PHP, stripslashes in PHP, several JS libs) The PHP version of the string always have some more characters. (我试图修剪PHP中的\\n\\r\\t
,PHP中的stripslashes,几个JS库)字符串的PHP版本总是有更多的字符。
In JavaScript, a JSON key without quote is valid. 在JavaScript中,没有引号的JSON密钥是有效的。 In PHP, a JSON key without quote is NOT valid. 在PHP中,没有引号的JSON密钥无效。 (In fact, the right JSON syntax is with quotes on keys.) (事实上,正确的JSON语法是键上的引号。)
So you're right, the difference came from JSON.stringify
who strip the quotes from your integer key. 所以你是对的,不同之处JSON.stringify
从整数键中删除了引号。
I was having the same issue where I wanted to compare an encrypted version of the encoded json string. 我有同样的问题,我想比较编码的json字符串的加密版本。 To make the output of json_encode
identical to javascripts JSON.stringify
you can do this: 要使json_encode
的输出与javascripts JSON.stringify
相同,您可以这样做:
$php_string = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
Actually, I had an integer which was encapsed in double-quotes in PHP but not in JS. 实际上,我有一个整数,在PHP中用双引号括起来但不包含在JS中。 As I only need to validate that the data are the same, and I don't care about the values, I striped all the double quotes, and it did the trick. 因为我只需要验证数据是否相同,而且我不关心这些值,所以我对所有双引号进行了条带化处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.