用双引号解析PHP上的JSON

时间:2013-10-01 15:57:57

标签: php json

我正在使用 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(),但问题仍然存在

2 个答案:

答案 0 :(得分:3)

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

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

stripslashes()知道关于JSON语法的 NOTHING 。它只是完成它的工作并删除一层斜线,给你:

{"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中删除。

答案 1 :(得分:0)

我使用Base64解决了这个问题。

注释内容在Base64上编码并获取我的注释 $this->note = base64_decode($json->{'alerte'}->{'note'});

知道我可以在 note内容中编写所有内容而无需担心语法。 这是一种替代解决方案,而不是真正的修正。

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