用双引号在PHP上解析JSON

用双引号在PHP上解析JSON,php,json,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'}->{

我正在使用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_解码总是失败

但是,当打印json_警报时,格式似乎是正确的

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的解决方案是什么


EDIT:我删除了
stripslashes()
,但问题仍然存在

请考虑一个有效的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\u decode()
失败


除非你的PHP安装是一个可怕的/愚蠢的老版本和/或配置不好,否则你不应该删除任何斜杠,因为magic\u quotes\u gpc应该关闭和/或完全从PHP中删除。

我使用
Base64
解决了这个问题

便笺内容在
Base64上编码,要获得便笺,我需要
$this->note=base64_decode($json->{'alerte'}->{'note'})

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


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

不要试图解决另一个问题。解决最初的问题为什么不直接使用HTML字符呢?这里->你正在破坏你的json数据,用stripslashes破坏json字符串。@nickc:stripslashes对json一无所知。它只会删除一组斜线。一个有效的json字符串
{“foo”:“this has a\”quote in it”}
将被简化为
{“foo”:“this has a”quote in it”}
和boom。现在它不是json。这只是随机垃圾。但是当我在之后使用
echo$json\u alert
时,我有一个正确的json格式,如果我不使用
stripslashes()
echo内容为空,直接回显$\u POST值,将其与stripslashes之后得到的值进行比较。您可能会发现您的系统禁用了magic_引号,这意味着您的原始json数据中没有额外的斜杠,并且您正在通过执行stripslashes来销毁它。仅供参考,我使用MAMP模拟我的服务器。我尝试
echo
原始值,然后我告诉你结果。原始值是:“alerte”:{“note”:“What up \“dad\”,“expeditor”:{“id_user”:“5”},“location”:{“lat”:“37.178181”,“long”:“-96.054581”},“id_type”:“4”}所以是的,这里只有JSON所需的转义,而stripslashes正在删除它们,留下无效的JSON。