2

我正在使用json将数据从 iOS/Android 发布到我的服务器

我用这些行处理 Post 数据:

//$json_alert = stripslashes(utf8_decode($_POST["json_alert"]));
$json_alert = $_POST["json_alert"]);
echo $json_alert;
$json = json_decode($json_alert);

$this->id_type = $json->{'alerte'}->{'id_type'};
        $this->note = $json->{'alerte'}->{'note'};
        $this->coordinate = $json->{'alerte'}->{'location'}->{'lat'} . ";" . $json->{'alerte'}->{'location'}->{'long'};
        $this->id_user = $json->{'alerte'}->{'expediteur'}->{'id_user'};

问题是:当我发送带有报价的 json 时,json_decode 不断失败。

但是,当打印 json_alert 格式似乎是正确的。

echo $json_alert;

**** print ****

{
  "alerte": {
  "note":"It's not \"working\"", //double quote fails in json_decode
  "expediteur":{
  "id_user":"5"
 },
  "location":{
  "lat":"37.785834",
  "long":"-122.406417"
 },
  "id_type":"3"
 }
}

即使我写双引号,解析 json 的解决方案是什么?

编辑:我删除了stripslashes()但问题仍然存在

4

2 回答 2

3

考虑一个有效的 JSON 字符串:

{"foo":"this string has a single \" double quote in it and a \\ backslash"}

stripslashes()对JSON语法一无所知。它只是完成了它的工作并删除了一层斜线,从而为您提供:

{"foo":"this string has a single " double quote in it and a \ backslash"}
                                 ^--- bare quote, now terminating the string early
                                                            ^--- bare escape

并且繁荣,你不再有一个 JSON 字符串。你有一些随机的“垃圾”会导致json_decode()失败。

除非您的 PHP 安装是一个可怕/愚蠢的古老和/或错误配置,否则您应该删除任何斜杠,因为 magic_quotes_gpc 应该关闭和/或从 PHP 中完全删除。

于 2013-10-01T16:24:23.877 回答
0

我通过使用解决了这个问题Base64

笔记内容被编码Base64并得到我做的笔记 $this->note = base64_decode($json->{'alerte'}->{'note'});

知道我可以在笔记内容中写下所有内容,而不必担心语法。这是一种替代解决方案,而不是真正的更正。

我仍然很好奇,我想知道错误发生在哪里。

于 2013-10-01T17:56:20.617 回答