Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP JSON encode output number as string

Tags:

json

jquery

php

I am trying to output a JSON string using PHP and MySQL but the latitude and longitude is outputting as a string with quotes around the values. This causes an issue when I am trying to add the 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 output:

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

Here is the output that I am getting:

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

Notice the quotes around the latitude and longitude values.

like image 930
m_gunns Avatar asked Jul 10 '12 02:07

m_gunns


People also ask

How can I get JSON encoded data in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

What is JSON encoded string?

The method JSON. stringify(student) takes the object and converts it into a string. The resulting json string is called a JSON-encoded or serialized or stringified or marshalled object.

What does json_encode return?

The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.

What is Json_decode?

The json_decode() function is used to decode or convert a JSON object to a PHP object.


2 Answers

You could also try

echo json_encode( $results, JSON_NUMERIC_CHECK );

Some reference:

PHP JSON constants

like image 177
Kris.Mitchell Avatar answered Oct 05 '22 18:10

Kris.Mitchell


$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 a float number, but you could try this

like image 26
Allen Chak Avatar answered Oct 05 '22 17:10

Allen Chak