PHP json_encode encoding numbers as strings
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 :
{"id":152,"another":"test","ananother":456}
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 http://bugs.php.net/ could be related ? For instance, Bug #40503 : json_encode integer conversion is inconsistent with PHP ?
Maybe Bug #38680 could interest you too, btw ?
How can I force PHP's json_encode integer values to be encoded as String?
In the link posted by Thomas in comments, one user suggests that you do this:
$data = json_encode(array_map('strval', $data));
This might not be the most efficient in terms of performace though, since every entry on the array will pass through the strval
function.
PHP - JSON_ENCODE Number converted to string. How to fix it?
You'll need to convert them from string
to float
. So we simply map the array with a float conversion
$coor = array_map('floatval', $coor);
PHP JSON encode output number as string
You could also try
echo json_encode( $results, JSON_NUMERIC_CHECK );
Some reference:
PHP JSON constants
Numbers in quotes using json_encode()
If you're building your json data from a one-dimensional array, you can use
echo json_encode(array_map('strval', $data));
This technique will unconditionally convert all values to strings (including objects, nulls, booleans, etc.).
If your data might be multidimensional, then you'll need to call it recursively.
Force json_encode to create strings of numeric values in a flat array
It would be nice if there was the opposite of JSON_NUMERIC_CHECK
but it doesn't look like there is.
Why can't you ensure the data is of the correct type in your php, before encoding it?
This might mean you have to cast it manually to strings...
Related Topics
How to Remove File Extension from a Website Address
Remove All Attributes from HTML Tags
Create Array Tree from Array List
Select Count(*) from Table of MySQL in PHP
PHP Function to Get the Subdomain of a Url
Pdo Binding Values For MySQL in Statement
Can Png Image Transparency Be Preserved When Using PHP'S Gdlib Imagecopyresampled
Returning Json from PHP to JavaScript
Secure Random Number Generation in PHP
How to Check Whether an Array Is Empty Using PHP
Global or Singleton For Database Connection
PHP Multi-Dimensional Array Remove Duplicate
How to Echo a Variable With Single Quotes
How to Create an Array For Json Using PHP