Why is json_encode adding backslashes?

Why is json_encode adding backslashes?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Why is json_encode adding backslashes?

You are seeing the backslashes because you are likely running into a classic encoding mismatch, specifically involving PHP's default serialization behavior or how your browser interprets the string before it reaches the JSON parser. The code snippet provided shows json_encode outputting "http:\/\/mysite.com\/...". While this looks like escaped characters in a terminal, valid JSON strings must use backslashes to escape forward slashes if the encoding format demands it, though modern parsers often handle raw slashes fine.

However, the real issue described in your update—the toSource() output showing double-escaped strings and extra fields—is a symptom of how the data is being handled between the server and the client. The PHP function json_encode outputs a string containing valid JSON. When you print this directly to the browser (e.g., via echo), the browser receives it as text.

The confusion often stems from mixing up two different concepts: raw output versus string parsing. If your PHP script echoes the JSON directly, the browser renders it as plain text or HTML content depending on the headers sent. It does not automatically parse it into an object until JavaScript explicitly calls JSON.parse().

The Double-Escaping Problem

In your update, you mention seeing response:"{\"logo_url\":\"...\"}" inside a JSON structure returned to Plupload. This indicates that the data is being wrapped in another layer of stringification before it hits the client-side handler.

When you see { "response": "{\"key\":\"value\"}" }, the inner quotes are escaped because the outer value is intended to be a string, not a nested object. If your server returns this structure instead of raw JSON, your JavaScript parser will fail or interpret the content incorrectly. This often happens when an API wrapper or a framework like Plupload intercepts the response, wraps it in a status object (like status:200), and then stringifies that wrapper before sending it back up the chain.

Plupload's FileUploaded event handler receives a raw response object. If your backend is returning JSON, but the client-side code expects a specific format, or if there is a proxy layer adding metadata, you end up with invalid JSON structures. The toSource() method in JavaScript returns the native representation of the object, which includes escaped quotes for strings that contain quotes. This is normal behavior for toSource(), but it confirms that the data inside data.response is indeed a string, not a parsed JSON object.

Ensuring Correct Output

To resolve this, ensure your PHP script sends the correct headers and returns raw JSON without any additional wrapping. If you are using Laravel (or similar frameworks), be aware of how middleware handles responses. Sometimes, debugging output or logging mechanisms inadvertently capture the response string and re-serialize it.

Here is a robust pattern for returning JSON in PHP to ensure no accidental escaping occurs before the data leaves the server:

<?php
$result = [
    'logo_url' => 'http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg',
    'img_id'   => 54,
    'feedback' => [
        'message' => 'File uploaded',
        'success' => true
    ]
];

header('Content-Type: application/json');
echo json_encode($result, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);

The JSON_UNESCAPED_SLASHES option is a crucial flag. By default, json_encode escapes forward slashes (/) as \/. While this is technically valid JSON, it increases file size and can confuse older parsers or developers expecting raw URLs. Removing the slash escaping makes the output cleaner and easier to read in browser developer tools.

Client-Side Handling

On the client side, Plupload passes the response to your callback. You must ensure you are accessing the correct property. If the server returns raw JSON, data.response should be a string containing that JSON. You need to parse it manually if the API doesn't return the object directly:

uploader.bind('FileUploaded', function(up, file, data) {
    // Check if data is a string or an object
    let responseContent = '';
    
    if (typeof data === 'string') {
        responseContent = data;
    } else if (data.response) {
        // If wrapped in a status object, extract the raw JSON string
        responseContent = data.response; 
    }

    try {
        const parsedData = JSON.parse(responseContent);
        
        console.log(parsedData.feedback.message);
        // Proceed with logic using parsedData
    } catch (e) {
        console.error("Invalid JSON received:", e);
    }

    $('#' + file.id + " b").html("100%");
});

Summary of the Root Cause

The backslashes you see are either a result of JSON_UNESCAPED_SLASHES not being used in PHP (which is harmless but verbose) or, more critically, a sign that your data is being double-stringified on the client side. The presence of status:200 and the nested response key confirms that Plupload (or an intermediary layer) is wrapping your raw JSON payload into a success object.

To fix the "invalid JSON" error in your alert, you must parse the inner string contained within data.response. If you control the server response, strip away any wrapper logic and return only the associative array encoded as raw JSON with appropriate headers. This ensures the client receives exactly what it expects without needing to handle complex nested string parsing.

For further reading on handling file uploads and secure JSON responses in modern PHP stacks, resources like https://laravelcompany.com offer insights into building robust upload handlers that manage these edge cases gracefully.

Our network