Steven Steven - 7 months ago 81
PHP Question

Why is json_encode adding backslashes?

I've been using

for a long time, and I've not had any problems so far.
Now I'm working with a upload script and I try to return some JSON data after file upload.

I have the following code:

print_r($result); // <-- This is an associative array
echo json_encode($result); // <-- this returns valid JSON

This gives me the following results:

// print_r result
[logo_url] =>
[img_id] => 54
[feedback] => Array
[message] => File uploaded
[success] => 1


// Echo result
{"logo_url":"http:\/\/\/uploads\/gallery\/7f\/3b\/f65ab8165d_logo.jpeg","img_id":"54","feedback":{"message":"File uploaded","success":true}}

Can anyone tell me why
adds slashes?


@Quentin said that something is happening between
and he's right.

Doing a
gives me the dollowing result:

({response:"{\"logo_url\":\"http:\\/\\/\\/wp-content\\/uploads\\/gallery\\/7f\\/3b\\/71b9520cfc91a90afbdbbfc9d2b2239b_logo.jpeg\",\"img_id\":\"62\",\"feedback\":{\"message\":\"File uploaded\",\"success\":true}}", status:200})

And this is not valid JSON. It also adds the
and I have no idea where this comes from.

Could it be that the
Plupload bind
does something to my returned data?

This is my js script:

uploader.bind('FileUploaded', function(up, file, data) {
$('#' + + " b").html("100%");


Can anyone tell me why json_encode adds slashes?

Forward slash characters can cause issues (when preceded by a < it triggers the SGML rules for "end of script element") when embedded in an HTML script element. They are escaped as a precaution.

Because when I try do use jQuery.parseJSON(response); in my js script, it returns null. So my guess it has something to do with the slashes.

It doesn't. In JSON "/" and "\/" are equivalent.

The JSON you list in the question is valid (you can test it with jsonlint). Your problem is likely to do with what happens to it between json_encode and parseJSON.