[笔记] json去除正斜杠转义

JSON为何有正斜杠’/’转义?

JSON doesn't require you to do that, it allows you to do that. It also allows you to use "\u0061" for "A", but it's not required. Allowing \/ helps when embedding JSON in a <script> tag, which doesn't allow </ inside strings, like Seb points out.


Some of Microsoft's ASP.NET Ajax/JSON API's use this loophole to add extra information, e.g., a datetime will be sent as "\/Date(milliseconds)\/". (Yuck)



https://www.cnblogs.com/feixiablog/articles/8075354.html

如何让json_encode不转义斜杠

当服务器返回一些数据时需要返回一些地址,但是默认的json_code是会对 / 转义成 \/ 的处理。。。

解决办法:

1. 正则替换:  echo str_replace("\\/", "/",  json_encode("2013/4/21"));

2. 若是php版本是5.4的话:   echo json_encode("2011/7/11", JSON_UNESCAPED_SLASHES);

php格式化json的函数@json_encode($value,$options)

其中有2个比较常用到的参数:

JSON_UNESCAPED_UNICODE中文不转为unicode ,对应的数字 256)

JSON_UNESCAPED_SLASHES不转义反斜杠,对应的数字 64

通常json_encode只能传入一个常量,如果同时使用2个常量怎么办?

JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES = 320

使用方法:json_encode($arr,320);即可完成同时使用2个常量。

例如:

<?php
$arr = array('key'=>'中文/同时生效'); json_encode($arr,320);

 结果:


猜你喜欢

转载自blog.csdn.net/m0_37962554/article/details/81012181