I am generating JSON with PHP.

我一直在用

$string = 'This string has "double quotes"';

echo addslashes($string);

outputs: This string has \" double quotes\"

Perfectly valid JSON

Unfortunately addslashes also escapes single quotes with catastrophic results for valid JSON

$string = "This string has 'single quotes'";

echo addslashes($string);

输出:This string has \'single quotes\'

简而言之,有没有办法只转义双引号?

推荐答案

虽然如果您可以使用json_encode,您应该使用json_encode,但您也可以使用addcslashes仅为某些字符添加\,例如:

addcslashes($str, '"\\/')

您还可以使用基于正则表达式的替换:

function json_string_encode($str) {
    $callback = function($match) {
        if ($match[0] === '\\') {
            return $match[0];
        } else {
            $printable = array('"' => '"', '\\' => '\\', "\b" => 'b', "\f" => 'f', "\n" => 'n', "\r" => 'r', "\t" => 't');
            return isset($printable[$match[0]])
                   ? '\\'.$printable[$match[0]]
                   : '\\u'.strtoupper(current(unpack('H*', mb_convert_encoding($match[0], 'UCS-2BE', 'UTF-8'))));
        }
    };
    return '"' . preg_replace_callback('/\\.|[^\x{20}-\x{21}\x{23}-\x{5B}\x{5D}-\x{10FFFF}/u', $callback, $str) . '"';
}

Json相关问答推荐

Elasticsearch Go客户端错误:无效的SON格式:在中间件中索引文档时出错

Azure Data Factory JSON输出格式问题

PowerShell:使用JSON原生的Short命令处理JSON?

419(未知状态)使用laravel处理PUT请求

jq 对特定键进行过滤并将值整理到单个 csv 单元格中

从包含 JSON 对象序列的文件中获取第一个 JSON 对象

如何使NiFi将数据库单列中的多个值转化为Solr索引中的数组?

使用不同行数的数据创建嵌套Jolt

如何在jolt中使用shift和modify-overwrite-beta

将 JSON 文件放在哪里以在 Angular 8 应用程序中加载静态 JSON 数据?

为什么在测试 RSPEC 时 JBuilder 不返回 JSON 中的响应正文

如何在golang中获取 struct 的json字段名称?

如何一次加载无限滚动中的所有条目以解析python中的HTML

将 JSON 对象推送到 localStorage 中的数组

在 Android 中使用带有 post 参数的 HttpClient 和 HttpPost

严重:找不到媒体类型 = 应用程序/json、类型 = 类 com.jersey.jaxb.Todo、通用类型 = 类 com.jersey.jaxb.Todo 的 MessageBodyWriter

在 iPhone 上解析 JSON 日期

如果键可能不存在,则从 Python dict 读取

NSURLRequest 中不支持的 URL

如何遍历 JSON 中的条目?