views:

53

answers:

2

I have this code converting a mysql query to json:

$sth = mysql_query('SELECT * FROM `staff` ORDER BY `id` DESC LIMIT 20') or die(mysql_error());
$rows = array();
while($r = mysql_fetch_array($sth)) {
    $rows[] = $r;
}
print json_encode($rows);

Works great, but i have in my database, a url field, here is a sample json row:

{"0":"4","id":"4","1":"Noter 2","name":"Noter 2","2":null,"desc":null,"3":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","iconurl":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","4":"1262032317","date":"1262032317","5":"dBelement, LLC","company":"dBelement, LLC","6":"http:\/\/dbelement.com\/","companyurl":"http:\/\/dbelement.com\/","7":"http:\/\/noter2.dbelement.com","appurl":"http:\/\/noter2.dbelement.com"},

How can i get around this?

+1  A: 

I suppose the "problem" is the presence of backslashed in the URLs ?

Like :

http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg

Well, that's not a problem for Javascript : try to assign your JSON data to a Javascript object, and display one of those URL :

var data = {"0":"4","id":"4","1":"Noter 2","name":"Noter 2","2":null,"desc":null,"3":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","iconurl":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","4":"1262032317","date":"1262032317","5":"dBelement, LLC","company":"dBelement, LLC","6":"http:\/\/dbelement.com\/","companyurl":"http:\/\/dbelement.com\/","7":"http:\/\/noter2.dbelement.com","appurl":"http:\/\/noter2.dbelement.com"};
alert(data[3]);

The URL is displayed correctly :

http://images.apple.com/webapps/productivity/images/noter2_20091223182720-thumb.jpg

So, the backslashes are not a "problem" ;-)


And, in fact, if you take a look at the "string" section of json.org, you'll see that slashes have to be backslashed for your string to be valid.

Pascal MARTIN
it already is, perhaps it is nothing to do with this :/ ok thanks.
tarnfeld
A: 

I don't see a problem here. If you're wondering why the URLs look like this:

http:\/\/www.example.com\/

Instead of like this:

http://www.example.com/

It's because the / characters are being appropriately escaped. When you unserialize the JSON object in javascript, the URLs will look as they do in your database.

Asaph