[php] How to remove backslash on json_encode() function?

How to remove the (\)backslash on a string? when using echo json_encode() ?

For example:

<?php
$str = "$(\"#output\").append(\"<p>This is a test!</p>\")";

echo json_encode($str);
?>

note: When you echo $str, there will be no problem... but when you echo out using json_encode(), the (\)backslash will show up.

Is there a way to solve this?

This question is related to php ajax json function backslash

The answer is


the solution that does work is this:

$str = preg_replace('/\\\"/',"\"", $str);

However you have to be extremely careful here because you need to make sure that all your values have their quotes escaped (which is generally true anyway, but especially so now that you will be stripping all the escapes from PHP's idiotic (and dysfunctional) "helper" functionality of adding unnecessary backslashes in front of all your object ids and values).

So, php, by default, double escapes your values that have a quote in them, so if you have a value of My name is "Joe" in your DB, php will bring this back as My name is \\"Joe\\".

This may or may not be useful to you. If it's not you can then take the extra step of replacing the leading slash there like this:

$str = preg_replace('/\\\\\"/',"\"", $str);

yeah... it's ugly... but it works.

You're then left with something that vaguely resembles actual JSON.


Simpler way would be

$mystring = json_encode($my_json,JSON_UNESCAPED_SLASHES);

You do not want to delete it. Because JSON uses double quotes " " for strings, and your one returns

"$(\"#output\").append(\"
This is a test!<\/p>\")"

these backslashes escape these quotes


I use the following to remove the slashes

echo json_decode($mystring, JSON_UNESCAPED_SLASHES);

As HungryDB said the easier way for do that is:

$mystring = json_encode($my_json,JSON_UNESCAPED_SLASHES);

Have a look at your php version because this parameter has been added in version 5.4.0

json_encode documentation


Yes it's possible. Look!

$str = str_replace('\\', '', $str);

But why would you want to?


Since PHP 5.4 there are constants which can be used by json_encode() to format the json reponse how you want.

To remove backslashes use: JSON_UNESCAPED_SLASHES. Like so:

json_encode($response, JSON_UNESCAPED_SLASHES);

View the PHP documentation for more constants and further information:

http://php.net/manual/en/function.json-encode.php

List of JSON constants:

http://php.net/manual/en/json.constants.php


If you using PHP 5.2, json_encode just expect only 1 parameter when call it. This is an alternative to unescape slash of json values:

stripslashes(json_encode($array))

Don't use it if your data is complicated.


I just figured out that json_encode does only escape \n if it's used within single quotes.

echo json_encode("Hello World\n");
// results in "Hello World\n"

And

echo json_encode('Hello World\n');
// results in "Hello World\\\n"

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to backslash

How to print a single backslash? python replace single backslash with double backslash Escaping backslash in string - javascript File path issues in R using Windows ("Hex digits in character string" error) Replace "\\" with "\" in a string in C# How to remove backslash on json_encode() function? Java replace issues with ' (apostrophe/single quote) and \ (backslash) together How do I add slashes to a string in Javascript? String.replaceAll single backslashes with double backslashes Escaping Strings in JavaScript