Json_encode Adds Backslashes: Unveiling the Mystery
In the realm of JavaScript, json_encode has long been a trusted ally for encoding data into JSON format. However, some developers have encountered an unexpected phenomenon where json_encode introduces backslashes into the output.
The Uploading Conundrum
One such instance occurs when using json_encode to return JSON data after a file upload. Consider the following code:
print_r($result); // Associative array $encoded_result = json_encode($result); // Valid JSON echo $encoded_result;
The Unexplained Backslashes
To the surprise of the developer, the resulting JSON includes unwanted backslashes:
{"logo_url":"http:\/\/mysite.com\/uploads\/gallery\/7f\/3b\/f65ab8165d_logo.jpeg","img_id":"54","feedback":{"message":"File uploaded","success":true}}
Pinpointing the Culprit
Initial investigations revealed that the backslashes were being added somewhere between json_encode and the browser's parsing of the JSON data.
alert(data.toSource()); // Result: invalid JSON with added "status:200"
The Hidden Variable
Closer examination uncovered an unexpected culprit: the Plupload bind event.
uploader.bind('FileUploaded', function(up, file, data) { alert(data.toSource()); $('#' + file.id + " b").html("100%"); });
Plupload, a popular file upload library, appeared to be manipulating the returned data, adding the "status:200" property and encoding the slashes.
The Solution: Escaping the Slashes
To thwart the unwanted backslashes, the code was modified to include the "JSON_UNESCAPED_SLASHES" option in the json_encode function call:
$encoded_result = json_encode($result, JSON_UNESCAPED_SLASHES);
This option effectively disables the escaping of forward slashes, resulting in the desired JSON output:
{"logo_url":"http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg","img_id":"54","feedback":{"message":"File uploaded","success":true}}
Unveiling the Truth
In conclusion, the addition of backslashes in json_encode output was attributed to the unintended manipulation of data by the Plupload bind event. By incorporating the "JSON_UNESCAPED_SLASHES" option, developers can prevent this unwanted escape character from interfering with their JSON data.
The above is the detailed content of Why does `json_encode` add backslashes and how can I prevent it?. For more information, please follow other related articles on the PHP Chinese website!