Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is json_encode adding backslashes?

Tags:

json

php

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%");
  });
like image 399
Steven Avatar asked Apr 25 '12 11:04

Steven


People also ask

Why are there backslashes in JSON?

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.

What does the PHP function json_encode () do?

PHP | json_encode() Function The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation. Parameters: $value: It is a mandatory parameter which defines the value to be encoded.

What is json_encode and Json_decode?

JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.

What is json_encode in JavaScript?

The PHP json_encode function translates the data passed to it to a JSON string which can then be output to a JavaScript variable. We demonstrate on this page with single level arrays. Other pages demonstrate using json_encode with multi-dimensional arrays and scalar values.


5 Answers

Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4).

json_encode($array,JSON_UNESCAPED_SLASHES);
like image 107
reirracon Avatar answered Oct 02 '22 16:10

reirracon


I just came across this issue in some of my scripts too, and it seemed to be happening because I was applying json_encode to an array wrapped inside another array which was also json encoded. It's easy to do if you have multiple foreach loops in a script that creates the data. Always apply json_encode at the end.

Here is what was happening. If you do:

$data[] = json_encode(['test' => 'one', 'test' => '2']);
$data[] = json_encode(['test' => 'two', 'test' => 'four']);
echo json_encode($data);

The result is:

["{\"test\":\"2\"}","{\"test\":\"four\"}"]

So, what you actually need to do is:

$data[] = ['test' => 'one', 'test' => '2'];
$data[] = ['test' => 'two', 'test' => 'four'];
echo json_encode($data);

And this will return

[{"test":"2"},{"test":"four"}]
like image 45
Meezaan-ud-Din Avatar answered Oct 02 '22 16:10

Meezaan-ud-Din


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.

like image 30
Quentin Avatar answered Oct 03 '22 16:10

Quentin


This happens because the JSON format uses ""(Quotes) and anything in between these quotes is useful information (either key or the data).

Suppose your data was : He said "This is how it is done". Then the actual data should look like "He said \"This is how it is done\".".

This ensures that the \" is treated as "(Quotation mark) and not as JSON formatting. This is called escape character.

This usually happens when one tries to encode an already JSON encoded data, which is a common way I have seen this happen.

Try this

$arr = ['This is a sample','This is also a "sample"']; echo json_encode($arr);

OUTPUT:

["This is a sample","This is also a \"sample\""]
like image 20
Mayank Avatar answered Oct 04 '22 16:10

Mayank


Make sure your php script has the right header or it will add the slashes header('Content-Type: application/json');

like image 32
Jon Avatar answered Oct 01 '22 16:10

Jon