javascript PHP 的 json_encode 和 JS 的 JSON.stringify
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18441180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP's json_encode and JS's JSON.stringify
提问by Didier Sampaolo
I'm using both PHP and Javascript to build some kind of web service. I try to validate a token calculated on post parameters, sent from JS to PHP. Let's say the code is as follows:
我同时使用 PHP 和 Javascript 来构建某种 Web 服务。我尝试验证根据 post 参数计算的令牌,从 JS 发送到 PHP。假设代码如下:
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.
(我尝试\n\r\t
在 PHP 中修剪,在 PHP 中使用斜杠,几个 JS 库) 字符串的 PHP 版本总是有更多的字符。
回答by beunwa
In JavaScript, a JSON key without quote is valid. In PHP, a JSON key without quote is NOT valid. (In fact, the right JSON syntax is with quotes on keys.)
在 JavaScript 中,不带引号的 JSON 键是有效的。在 PHP 中,不带引号的 JSON 键无效。(事实上,正确的 JSON 语法是在键上加上引号。)
So you're right, the difference came from JSON.stringify
who strip the quotes from your integer key.
所以你是对的,区别在于JSON.stringify
谁从你的整数键中去除了引号。
回答by Gegenwind
I was having the same issue where I wanted to compare an encrypted version of the encoded json string. To make the output of json_encode
identical to javascripts JSON.stringify
you can do this:
我遇到了同样的问题,我想比较编码的 json 字符串的加密版本。要使输出json_encode
与 javascripts 相同,JSON.stringify
您可以执行以下操作:
$php_string = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
回答by Didier Sampaolo
Actually, I had an integer which was encapsed in double-quotes in PHP but not in 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.
实际上,我有一个整数,它在 PHP 中用双引号括起来,但在 JS 中没有。因为我只需要验证数据是否相同,而我不关心这些值,所以我去掉了所有的双引号,它就成功了。