Didier Sampaolo
Didier Sampaolo

Reputation: 2813

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.

Upvotes: 12

Views: 26964

Answers (3)

Gegenwind
Gegenwind

Reputation: 1428

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

Upvotes: 15

beunwa
beunwa

Reputation: 104

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.

Upvotes: 6

Didier Sampaolo
Didier Sampaolo

Reputation: 2813

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.

Upvotes: 0

Related Questions