Javascript – PHP json_encode encoding numbers as strings

javascriptjsonPHP

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!

Best Answer

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"}