【问题标题】:PHP json_decode failed when value contains single quote (')当值包含单引号(')时,PHP json_decode 失败
【发布时间】:2017-01-07 01:43:42
【问题描述】:

当字符串值包含单引号 (') 时,我无法使 json_decode() 工作,如下例所示:

$result = "{\"message\":\"test \' \",\"report\":[{\"1\":[{\"port\":\"gsm-1.2\",\"phonenumber\":\"XXXXXXXXXXX\",\"time\":\"2016-08-31 00:22:57\",\"result\":\"success\"}]}]}";
$resp = json_decode($result, true);
echo $resp;

【问题讨论】:

  • 你为什么要逃避它?只需使用'。此外,您不能echo 数组。
  • 如果没有必要,不要手动构建 JSON 字符串。构建正确的对象/数组,然后让json_encode() 处理其余部分。
  • @AbraCadaver 你是对的。单引号的转义会导致问题。
  • @Sammitch 我并没有真正手工构建它。结果来自我们的 gsm 网关 api 的结果。但是那个特定的字符串值会导致 json_decode 的错误。但 abracadaver 指出这是单引号的转义。

标签: php json


【解决方案1】:

您的 $result json 格式不正确,因此我认为您需要使用 stripslashes() 对其进行格式化,然后使用 json_decode()。它会工作:)。

<?php
$result = "{\"message\":\"test \'\",\"report\":[{\"1\":[{\"port\":\"gsm-1.2\",\"phonenumber\":\"XXXXXXXXXXX\",\"time\":\"2016-08-  31 00:22:57\",\"result\":\"success\"}]}]}";
$result=stripslashes($result);
$resp = json_decode($result, true);
var_dump($resp);
?>

检查 phpfiddle => http://phpfiddle.org/main/code/4e7n-vjxa

【讨论】:

    【解决方案2】:

    在您的代码中,单引号(')被斜杠()跳过,因此它破坏了 JSON 格式。

    尝试删除斜线并尝试。它应该工作。

    您应该检查生成此 JSON 的代码。

    【讨论】:

      猜你喜欢
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      相关资源
      最近更新 更多