Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how remove the backslash ("\") in the json response using php?

Tags:

json

php

mysql

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!

like image 631
user1957012 Avatar asked Jan 08 '13 05:01

user1957012


People also ask

Why does my JSON have backslash?

Those backslashes are escape characters. They are escaping the special characters inside of the string associated with JSON response. You have to use JSON. parse to parse that JSON string into a JSON object.

Should Slash be escaped in JSON?

JSON escapes the forward slash, so a hash {a: "a/b/c"} is serialized as {"a":"a\/b\/c"} instead of {"a":"a/b/c"} .


1 Answers

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 \.

like image 194
Nick Perkins Avatar answered Nov 04 '22 05:11

Nick Perkins