dongmeng1868 2015-01-28 21:38
浏览 53

由于PHP中的领先括号,无法解析JSON字段

I'm trying to create a webhook for Mandrill that will send an e-mail to the sender when a previously sent e-mail bounces. I'm able to receive the JSON data from Mandrill, but am unable to parse that data to send to the original sender:

<?php
require_once 'mandrill-api-php/src/Mandrill.php'; //Not required with Composer
$mandrill = new Mandrill('*myapikey*');

$json = stripslashes($_POST['mandrill_events']);
$jsondata = json_decode($json,true);

$subject = $jsondata['event'];
$message = "STRIPSLASHES: ".$json."----JSONDATA----".$jsondata;

$emailAddress = "*me@mydomain.com*";
mail($emailAddress, $subject, $message);
?>

Here is what the $json data looks like in the $message variable. It is a literal copy and paste from the test e-mail I receive:

STRIPSLASHES: [{"event":"spam","msg":{"ts":1365109999,"subject":"This an example webhook message","email":"example.webhook@mandrillapp.com","sender":"example.sender@mandrillapp.com","tags":["webhook-example"],"opens":[{"ts":1365111111}],"clicks":[{"ts":1365111111,"url":"http://mandrill.com"}],"state":"sent","metadata":{"user_id":111},"_id":"exampleaaaaaaaaaaaaaaaaaaaaaaaaa","_version":"exampleaaaaaaaaaaaaaaa"},"_id":"exampleaaaaaaaaaaaaaaaaaaaaaaaaa","ts":1422475458},{"event":"spam","msg":{"ts":1365109999,"subject":"This an example webhook message","email":"example.webhook@mandrillapp.com","sender":"example.sender@mandrillapp.com","tags":["webhook-example"],"opens":[{"ts":1365111111}],"clicks":[{"ts":1365111111,"url":"http://mandrill.com"}],"state":"sent","metadata":{"user_id":111},"_id":"exampleaaaaaaaaaaaaaaaaaaaaaaaaa1","_version":"exampleaaaaaaaaaaaaaaa"},"_id":"exampleaaaaaaaaaaaaaaaaaaaaaaaaa1","ts":1422475458}]----JSONDATA----Array

I notice that the $json is outputting the json data, but has a leading and ending bracket, as opposed to starting with a squiggly bracket. So I decided to call the data as if it were an array, but to no avail.

In a test, instead of doing $json = stripslashes(... I copy and pasted the json data above as a literal string. Once I removed the leading/ending brackets, I was able to parse some data.

  • 写回答

2条回答 默认 最新

  • douzhiling3166 2015-01-28 21:43
    关注

    Why don't you try removing the brackets using PHP?

    $json = ltrim($json, "[");
    $json = rtrim($json, ']");
    

    And then pass it to the decoder?

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料