Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP's json_encode and JS's JSON.stringify

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:

JS :

token = JSON.stringify(params);

PHP :

token = json_encode($_POST);

Can somebody please explain me why the two resulting JSON strings doesn't have the same length ?

(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.

like image 273
Didier Sampaolo Avatar asked Aug 26 '13 09:08

Didier Sampaolo


2 Answers

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:

$php_string = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
like image 95
Gegenwind Avatar answered Sep 18 '22 14:09

Gegenwind


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.)

So you’re right, the difference came from JSON.stringify who strip the quotes from your integer key.

like image 38
beunwa Avatar answered Sep 19 '22 14:09

beunwa