php - json_encode() 转义正斜杠

我正在从 Instagram 中提取 JSON:

$instagrams = json_decode($response)->data;

然后将变量解析成PHP数组来重构数据,然后重新编码和缓存文件:

file_put_contents($cache,json_encode($results));

当我打开缓存文件时,我所有的正斜杠“/”都被转义了:

http:\/\/distilleryimage4.instagram.com\/410e7...

我从搜索中收集到 json_encode() 会自动执行此操作...有没有办法禁用它?

最佳答案

is there a way to disable it?

是的,您只需要使用 JSON_UNESCAPED_SLASHES 标志(PHP 5.4+)。

!important read before: https://stackoverflow.com/a/10210367/367456 (know what you're dealing with - know your enemy: DO NOT USE in web/html context - CLI, unless CGI, might be fine thought, if they think they need it in JSON HTTP context for readability purposes, they have a different problem)

json_encode($str, JSON_UNESCAPED_SLASHES);

如果您手头没有 PHP 5.4(您肯定已经声明了上面的警告),请从众多现有函数中选择一个并根据您的需要对其进行修改,例如http://snippets.dzone.com/posts/show/7487 (archived copy) .

Example Demo

<?php
/*
 * Escaping the reverse-solidus character ("/", slash) is optional in JSON.
 *
 * This can be controlled with the JSON_UNESCAPED_SLASHES flag constant in PHP.
 *
 * @link http://stackoverflow.com/a/10210433/367456
 */    

$url = 'http://www.example.com/';

echo json_encode($url), "\n";

echo json_encode($url, JSON_UNESCAPED_SLASHES), "\n";

示例输出:

"http:\/\/www.example.com\/"
"http://www.example.com/"

https://stackoverflow.com/questions/10210338/

相关文章:

python - Python 中的元类是什么?

javascript - 将对象字符串转换为 JSON

python - 如何将网页中的 JSON 转换为 Python 脚本

python - 如何在 Python 中检查字符串是否是有效的 JSON?

ios - 如何将 JSON 字符串反序列化为 NSDictionary? (适用于 iOS 5+)

python - Python有三元条件运算符吗?

jquery - TypeError : $. ajax(...) 不是函数?

python - 如何检查文件是否存在无异常?

python - 如果 __name__ == "__main__": do? 会怎样

python - 存储 Python 字典