note 105892 deleted from function.json-decode by salathe
| From: | salathe@php.net | Date: | Mon, 21 Sep 2020 15:00:56 +0000 |
| Subject: | note 105892 deleted from function.json-decode by salathe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-215429@lists.php.net to get a copy of this message | ||
Note Submitter: alexvonweiss at googlemail dot com
----
Consider that JSON can differ between int and string. So
<?php
var_dump(json_decode('{"foo": 12}'));
// array(1) { ["foo"]=> int(12) }
var_dump(json_decode('{"foo": "12"}'));
// array(1) { ["foo"]=> string(12) }
?>
Numbers that cannot be handled by integer seems to become float casted. This can be a problem if you
transfer big numbers like facebook ids over JSON. Either you avoid numbers by cast everything to
string before JSON.stringify or you have to use number_format if the value bacome a float value.
<?php
// test
$x = json_decode('{"foo": 123456789012345}');
echo sprintf('%1$f', $x->foo).PHP_EOL;
echo sprintf('%1$u', $x->foo).PHP_EOL;
echo sprintf('%1$s', $x->foo).PHP_EOL;
echo strval($x->foo).PHP_EOL;
echo (string) $x->foo.PHP_EOL;
echo number_format($x->foo, 0, '', '').PHP_EOL;
// output
123456789012345.000000 // printf %f
2249056121 // printf %u
1.2345678901234E+14 // printf %s
1.2345678901234E+14 // strval()
1.2345678901234E+14 // cast (string)
2249056121 // cast (int)
123456789012345 // number_format()
?>