How to remove backslash on json_encode() function?

2020-01-29 07:22发布

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?

10条回答
叛逆
2楼-- · 2020-01-29 08:03

I use the following to remove the slashes

echo json_decode($mystring, JSON_UNESCAPED_SLASHES);
查看更多
手持菜刀,她持情操
3楼-- · 2020-01-29 08:10

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

查看更多
趁早两清
4楼-- · 2020-01-29 08:11

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

查看更多
Deceive 欺骗
5楼-- · 2020-01-29 08:13

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.

查看更多
登录 后发表回答