js string转json有斜杠_处理JSON字符串中的转义斜杠

I'm trying to get the json of the database and the code goes like this

$path["file_name"] = "www.119.com\/assets\/demo\/large\/".$row["file_name"];

While I convert to a json object and it shows like this.

www.119.com\\\/assets\\\/demo\\\/large\\\/demo1.png

I just applied \ to print special character /, but it's not working. I applied many things to print the special character. Is it a problem in converting special character to JSON?

解决方案

As has been mentioned by others, a forward slash is not a special character inside a string, in PHP or in Javascript (and since JSON is derived from Javascript it follows the same rules for string interpolation). However if you were reading some JSON, you could be forgiven for thinking that it is (although you should always RTM ;-) ).

The reason you think you need to escape the slash is due to a subtle difference in the way PHP and Javascript interpolate superfluous forward slashes. Consider the following string declaration, valid in both PHP and Javascript:

"AC\/DC"

In PHP, the extra backslash is treated as a literal, so:

echo "AC\/DC"; // outputs AC\/DC

In Javascript, the extra backslash is dropped, so:

console.log("AC\/DC"); // logs AC/DC

JSON mandates the escaping of forward slashes, but json_encode() will take care of this escaping for you. You do not need to add the backslashes to the string yourself. And because of the difference in the way these additional backslashes are interpolated, you cannot simply take a JSON string and drop it into your PHP source - because it will will be interpretted as a different value.

Since PHP 5.4.0 you can supply the JSON_UNESCAPED_SLASHES flag to json_encode() in PHP to prevent it from adding the backslashes. However this is unnecessary and may cause a strict JSON parser to reject the data.

So to sum up, the correct way to declare your string in PHP is:

$path["file_name"] = "www.119.com/assets/demo/large/".$row["file_name"];

As a side note, you probably also what to include http:// at the beginning of the string and pass $row['file_name'] through urlencode() as well, since the data appears to be a URL:

$path["file_name"] = "http://www.119.com/assets/demo/large/".urlencode($row["file_name"]);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值