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)
becomes
"{ ["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!
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"}
I, likewise was reading from a DB (PostgreSQL) and everything was a string. We loop over each row and do things with it to build up our final results array, so I used
$result_arr[] = array($db_row['name'], (int)$db_row['count']);
within the loop to force it to be an integer value. When I do json_encode($result_arr)
now, it correctly formats it as a number. This allows you to control what is and is not a number coming from your database.
EDIT:
The json_encode()
function also has the ability to do this on the fly using the JSON_NUMERIC_CHECK
flag as a second argument to it. You need to be careful using it though as shown in this users example in the documentation (copied below): http://uk3.php.net/manual/en/function.json-encode.php#106641
<?php
// International phone number
json_encode(array('phone_number' => '+33123456789'), JSON_NUMERIC_CHECK);
?>
And then you get this JSON:
{"phone_number":33123456789}