如何输出 JSON parse compatible json with PHP json_encode? JSON.parse - 由于单转义双引号导致意外的标记 h

How to output JSON parse compatible json with PHP json_encode? JSON.parse - Unexpected token h due to single escaped double quotes

我有这个 php:

<?php

    $jsonarr = array("haha" => array("hihi'hih","hu\"huh"));
    print json_encode($jsonarr);

这给了我

{"haha":["hihi'hih","hu\"huh"]}

现在,在 JSON.parse 这打破了

Uncaught SyntaxError: Unexpected token h
    at Object.parse (native)

,除非我像这样双重转义反斜杠

var json = '{"haha":{"hihi\'hih":"hu\\"huh"}}';
JSON.parse(json);

我怎样才能 php 创建一个 JSON 解析兼容的输出?

与此同时,我确实根据这个 PHP's json_encode does not escape all JSON control characters 将 json_encoding 中的字符串双倍 json_encoding 用于 PHP's json_encode does not escape all JSON control characters,但想知道是否还有其他方法。

$jsonarr = array("haha" => array("hihi'hih","hu\"huh"));
        print json_encode(json_encode($jsonarr));

如果您是从 AJAX 获取此内容,则不会发生,所以我相信您正在使用 PHP 生成 JS 代码,如下所示:

var json = '<?php echo $jsonarr; ?>';
var obj = JSON.parse(json);

这是行不通的,因为正如您所指出的,$jsonarr 在打印时将没有所需数量的反斜杠。 \" in JSON 需要在 JS 字符串文字中是 \" 才能被理解为 \".

相反,请记住 JSON 是可执行的 JS:

var obj = <?php echo $jsonarr; ?>;

完成!