7

I try to add a row of mysql query into JSON whit php. I use this code:

public function lugaresCercanos($lng, $lat, $distance){
$result=mysql_query("SELECT nombre, distancia FROM Lugar ORDER BY distancia ASC");
$info=array();
    while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
        array_push($info,$row);
    }
    return json_encode($info);

This returns a JSONObject, but I'm not sure.

    class resultado_final {
public $logstatus = "";
public $lugares_cercanos = "";}

$result_final = new resultado_final();
if($db->login($usuario,$passw)){
$result_final->logstatus = "0";}else{
$result_final->logstatus = "1";}
$result_final->lugares_cercanos = $lista;
echo json_encode($result_final);

This code print this:

{"logstatus":"1","lugares_cercanos":"[{\"nombre\":\"Rio Amazonas\",\"distancia\":\"5119.000\"},{\"nombre\":\"Swissotel \",\"distancia\":\"5823.000\"},{\"nombre\":\"Laguna de Yaguarcocha\",\"distancia\":\"71797.000\"}]"}

why the rows of the query are separated by backslashes? how remove the backslashes? Thanks alot!

user1957012
  • 103
  • 1
  • 2
  • 6

5 Answers5

16

The \ is to escape the quotes (") that are part of the response.

Use stripslashes() to strip these out.

When a string wrapped in quotes contains quotes, they have to be escaped. The escape character in php is \.

Nick Perkins
  • 1,327
  • 2
  • 12
  • 25
13

Try

json_encode($arr, JSON_UNESCAPED_SLASHES);

or

echo str_replace('\/','/',json_encode($mydatas));

(if unescape doesn't work) http://php.net/manual/en/function.json-encode.php

Mike
  • 72
  • 1
  • 2
  • 9
sk8terboi87 ツ
  • 3,396
  • 3
  • 34
  • 45
6

Stop double-encoding your data. Put everything together in one large structure and then encode only that.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

If anyone wants to remove the backslashes and also pretty print the JSON data, the following can be used:

json_encode($my_array, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
Devner
  • 6,825
  • 11
  • 63
  • 104
0

Thanks, I resolve it.

$info=array();
    while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
        array_push($info,$row);
    }
    $info;
$result_final->lugares_cercanos = $info;

Print this:

{"logstatus":"1","lugares_cercanos":[{"nombre":"Rio Amazonas","distancia":"5119.000"}{"nombre":"Swissotel Quito","distancia":"5823.000"}{"nombre":"Laguna de Yaguarcocha","distancia":"71797.000"}]}
Boann
  • 48,794
  • 16
  • 117
  • 146
user1957012
  • 103
  • 1
  • 2
  • 6