Why is json_encode adding backslashes?

json, php

Solution

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

Problem

I've been using `json_encode` 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 Array ( [logo_url] => http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg [img_id] => 54 [feedback] => Array ( [message] => File uploaded [success] => 1 ) ) // Echo result {"logo_url":"http:\/\/mysite.com\/uploads\/gallery\/7f\/3b\/f65ab8165d_logo.jpeg","img_id":"54","feedback":{"message":"File uploaded","success":true}} ``` Can anyone tell me why `json_encode` adds slashes? update @Quentin said that something is happening between `json_encode` and `.parseJSON` and he's right. Doing a `alert(data.toSource());` gives me the dollowing result: ``` ({response:"{\"logo_url\":\"http:\\/\\/storelocator.com\\/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 `status:200` 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) { alert(data.toSource()); $('#' + file.id + " b").html("100%"); }); ```

Original source

Related problems