PHP json_encode encoding numbers as strings


I am having one problem with the PHP json_encode function. It encodes numbers as strings, e.g.

array('id' => 3)


"{ ["id": "3", ...)

When js encounters these values, it interprets them as strings and numeric operations fail on them. Does anyone know some way to prevent json_encode from encoding numbers as strings? Thank you!

10/22/2013 8:39:11 AM

Accepted Answer

I've done a very quick test :

$a = array(
    'id' => 152,
    'another' => 'test',
    'ananother' => 456,
$json = json_encode($a);
echo $json;

This seems to be like what you describe, if I'm not mistaken ?

And I'm getting as output :


So, in this case, the integers have not been converted to string.

Still, this might be dependant of the version of PHP we are using : there have been a couple of json_encode related bugs corrected, depending on the version of PHP...

This test has been made with PHP 5.2.6 ; I'm getting the same thing with PHP 5.2.9 and 5.3.0 ; I don't have another 5.2.x version to test with, though :-(

Which version of PHP are you using ? Or is your test-case more complex than the example you posted ?

Maybe one bug report on could be related ? For instance, Bug #40503 : json_encode integer conversion is inconsistent with PHP ?

Maybe Bug #38680 could interest you too, btw ?

9/7/2009 9:50:39 PM

Note that since PHP 5.3.3, there's a flag for auto-converting numbers (the options parameter was added in PHP 5.3.0):

$arr = array( 'row_id' => '1', 'name' => 'George' );
echo json_encode( $arr, JSON_NUMERIC_CHECK ); // {"row_id":1,"name":"George"}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow