PHP JSON encodes output number as string

I am trying to output a JSON string using PHP and MySQL, but the latitude and longitude are output as a string with quotes around the values. This causes a problem when I try to add markers to a google map.

Here is my code:

$sql = mysql_query('SELECT * FROM markers WHERE address !=""'); $results = array(); while($row = mysql_fetch_array($sql)) { $results[] = array( 'latitude' =>$row['lat'], 'longitude' => $row['lng'], 'address' => $row['address'], 'project_ID' => $row['project_ID'], 'marker_id' => $row['marker_id'] ); } $json = json_encode($results); echo "{\"markers\":"; echo $json; echo "}"; 

Here is the expected result:

 {"markers":[{"latitude":0.000000,"longitude":0.000000,"address":"2234 2nd Ave, Seattle, WA","project_ID":"7","marker_id":"21"}]} 

Here is the result I get:

 {"markers":[{"latitude":"0.000000","longitude":"0.000000","address":"2234 2nd Ave, Seattle, WA","project_ID":"7","marker_id":"21"}]} 

Note the quotes around the latitude and longitude values.

+6
source share
6 answers

You can also try

 echo json_encode( $results, JSON_NUMERIC_CHECK ); 

Some link:

PHP JSON Constants

+17
source
 $results[] = array( 'latitude' => (float)$row['lat'], 'longitude' => (float)$row['lng'], 'address' => $row['address'], 'project_ID' => $row['project_ID'], 'marker_id' => $row['marker_id'] ); 

latitude and longitude should be floating point, but you can try this

+2
source

You may not know here: when receiving data from MySQL to PHP, you will always receive rows back, no matter what the actual value is. A simple cast type for float should fix the problem:

 $sql = mysql_query('SELECT * FROM markers WHERE address !=""'); $results = array(); while($row = mysql_fetch_array($sql)) { $results[] = array( 'latitude' => (float) $row['lat'], 'longitude' => (float) $row['lng'], 'address' => $row['address'], 'project_ID' => $row['project_ID'], 'marker_id' => $row['marker_id'] ); } $json = json_encode($results); echo "{\"markers\":"; echo $json; echo "}"; 

Or, conversely, since floats may not be accurate enough to store lat / long coordinates, save them as strings and remove quotes on the fly using string manipulation functions such as str_replace.

+1
source

Just do:

 echo str_replace('"','',$json); 

That should work.

0
source

valid JSON must have values ​​and keys inside double quotes. What is the problem with double quotes?

0
source

Use javascripts parseInt() on your client side to turn string values ​​into integers if necessary:

 typeof parseInt("56") # returns number typeof "56" # returns string 
0
source

Source: https://habr.com/ru/post/920094/


All Articles