PHP 在 $_POST['myjsonitem'] 时添加双反斜杠,导致 json_decode 结果为 JSON_ERROR_SYNTAX

flo*_*flo 3 php json

不敢相信,数以百万计的帖子涵盖了这个主题,但我无法让它发挥作用。

在我的 Android 应用程序中,我向服务器发送齐射 POST 请求。该请求是一个普通的 StringRequest,它包含一个序列化的 json 对象。

在服务器上,POST 请求中的项目像这样到达,我通过提取原始正文数据

$entityBody = file_get_contents('php://input');
Run Code Online (Sandbox Code Playgroud)

=>

myjsonitem=%5B%7B%22description%22%3A%22Back%22%2C%22freeText%22%3A%22%22%2C%22isRated%22%3Atrue%2C%22priceSingle%22%3A12.0%2C%22ratingStar%22%3A4.0%7D%2C%7B%22description%22%3A%22SoronA%22%2C%22freeText%22%3A%22%22%2C%22isRated%22%3Atrue%2C%22priceSingle%22%3A3.5%2C%22ratingStar%22%3A5.0%7D%5D
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,该项目在相应的 json 元素周围带有双引号,对我来说,到目前为止这似乎是正确的。

当我想通过以下方式对字符串进行 json_decode 时,问题就开始了:

$itemList = json_decode($_POST['myjsonitem'], true); 
Run Code Online (Sandbox Code Playgroud)

此命令返回 json_decode 错误 JSON_ERROR_SYNTAX。我不明白为什么,所以我通过以下方式将 json 写入日志:

error_log("Json String: " .$_POST['myjsonitem']);
Run Code Online (Sandbox Code Playgroud)

日志中的结果显示:

Json String: [{\\"description\\":\\"Back\\",\\"freeText\\":\\"\\",\\"isRated\\":true,\\"priceSingle\\":12.0,\\"ratingStar\\":4.0},{\\"description\\":\\"SoronA\\",\\"freeText\\":\\"\\",\\"isRated\\":true,\\"priceSingle\\":3.5,\\"ratingStar\\":4.0}]
Run Code Online (Sandbox Code Playgroud)

如您所见,双引号前面添加了双反斜杠。将此字符串放入 JSON 验证器会返回无效的 json。删除双反斜杠会返回有效的 json。

Magic Quotes 不可能是问题,因为我运行的是 php 7+。

这里发生了什么?如何正确解析PHP?我想,只是简单地删除双反斜杠不会有帮助,在我的 freeText 字段中,我可以有带双引号的字符串,因此在这种情况下转义应该仍然有效。

编辑:这是上下文的关键部分。也许我应该提到,我在 WordPress 安装上运行它,并且在 php 文件的开头,我包含了 wp-load.php。

if($_SERVER['REQUEST_METHOD']=='POST'){

    //getting some other data from request  
    $dateString = $_POST['date'];   
    $date = date('Y-m-d H:i:s', strtotime($dateString));        
    $userId = intval($_POST['userId']); 
    $sentUniqueId = $_POST['uniqueId']; 

    //crucial part goes here:   
    $itemsList = json_decode($_POST['myjsonitem'], true);   

    //output 
    error_log("Json String: " .$itemsList);
Run Code Online (Sandbox Code Playgroud)

我发布的输出(带有双反斜杠的输出)位于我的 error_log 文件中。

flo*_*flo 6

我终于找到了答案。最重要的是:我尝试在Wordpress上下文中运行此 php 代码。 在 WordPress 函数参考的深处,我发现了这一点:

无论 get_magic_quotes_gpc() 返回什么,WordPress 都会向 $_POST/$_GET/$_REQUEST/$_COOKIE 添加斜杠。因此,在 WordPress 上下文中,使用这些变量时应始终使用 stripslashes() 或 stipslashes_deep()。

好的,现在解决方案很简单:

$my_value = stripslashes($_POST['myjsonitem']); 
$itemsList = json_decode($my_value, true); 
Run Code Online (Sandbox Code Playgroud)

它删除了转义 json 元素双引号的斜杠,但没有删除相应文本字符串中的斜杠,这正是我所需要的。