10

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.

Dave Chen
  • 10,887
  • 8
  • 39
  • 67
Didier Sampaolo
  • 2,566
  • 4
  • 24
  • 34
  • 3
    can you post the content of both json strings? – Jeroen Ingelbrecht Aug 26 '13 at 09:47
  • 2
    `"a"` and `"\x61"` are same yet both have different characters/length. – Salman A Aug 26 '13 at 09:55
  • Are you sure that params and $_POST are the same? What you are claiming can't be valid, JSON should give the exact same output no matter what language you are in... check that both strings are identical, i.e. one may contain a \t and the other does not kind of thing... – George Violaris Aug 26 '13 at 10:30
  • 1
    A hint is available there : http://stackoverflow.com/questions/710586/json-stringify-bizarreness – Karim Slamani Aug 27 '13 at 08:39

3 Answers3

13

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);
Gegenwind
  • 1,388
  • 1
  • 17
  • 27
  • This did the job for me! Note; in my case i needed to `json_decode($body)` and then the `json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)` worked like a charm. – Robert Sep 01 '21 at 14:48
6

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.

Alex
  • 5,565
  • 6
  • 36
  • 57
beunwa
  • 104
  • 2
  • 7
    No. In JavaScript an object literal property name can be an identifier, which doesn't need to be quoted. However (1) Identifiers cannot be integers, so they must be quoted and (2) when generating JSON, the JSON rules still apply so all property names must be strings and cannot be identifiers. – Quentin Aug 27 '13 at 08:56
0

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.

Didier Sampaolo
  • 2,566
  • 4
  • 24
  • 34