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条回答
Explosion°爆炸
2楼-- · 2020-01-29 07:52

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"
查看更多
家丑人穷心不美
3楼-- · 2020-01-29 07:55
json_encode($response, JSON_UNESCAPED_SLASHES);
查看更多
祖国的老花朵
4楼-- · 2020-01-29 07:56

Simpler way would be

$mystring = json_encode($my_json,JSON_UNESCAPED_SLASHES);
查看更多
家丑人穷心不美
5楼-- · 2020-01-29 07:59

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.

查看更多
仙女界的扛把子
6楼-- · 2020-01-29 07:59

Yes it's possible. Look!

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

But why would you want to?

查看更多
▲ chillily
7楼-- · 2020-01-29 08:01

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

查看更多
登录 后发表回答