解码条纹json json_decode不工作
问题描述:
我有条纹json,我试图解码它json_decode。解码条纹json json_decode不工作
我没有收到错误。只是没有回报。我从条纹中获取数据,我只是无法解码它。
{
"created":1326853478,
"data":{
"object":{
"amount":4500,
"card":{
"country":"US",
"cvc_check":"pass",
"exp_month":7,
"exp_year":2014,
"fingerprint":"9aQtfsI8a17zjEZd",
"id":"cc_00000000000000",
"last4":"9782",
"object":"card",
"type":"Visa"
},
"created":1322700852,
"currency":"usd",
"disputed":false,
"fee":0,
"id":"ch_00000000000000",
"livemode":false,
"object":"charge",
"paid":true,
"refunded":true
}
},
"id":"evt_00000000000000",
"livemode":false,
"type":"charge.refunded"
}
// retrieve the request's body and parse it as JSON
$body = @file_get_contents('php://input');
$event_json = json_decode($body,true);
print_r($event_json);
任何想法?
答
在这里,我跑了这一点:
<?php
$data = '{ "created": 1326853478, "data": { "object": { "amount": 4500, "card": { "country": "US", "cvc_check": "pass", "exp_month": 7, "exp_year": 2014, "fingerprint": "9aQtfsI8a17zjEZd", "id": "cc_00000000000000", "last4": "9782", "object": "card", "type": "Visa" }, "created": 1322700852, "currency": "usd", "disputed": false, "fee": 0, "id": "ch_00000000000000", "livemode": false, "object": "charge", "paid": true, "refunded": true } }, "id": "evt_00000000000000", "livemode": false, "type": "charge.refunded" }';
$arr = json_decode($data, true);
print_r($arr);
?>
和它的工作。所以,理论上你应该能够使用:
<?php
$arr = json_decode(file_get_contents('php://input'), true);
print_r($arr);
?>
正如伊格纳西奥巴斯克斯 - 艾布拉姆斯说,不要因为它掩盖了错误信息,并使其更难调试使用“@”字符。
我也会检查你的PHP版本。 json_decode()仅在5.2.0及更高版本上可用。
答
php://input
流允许您从请求主体读取原始数据。这些数据将是一个字符串,根据什么样的值都在请求,看起来像:
"name=ok&submit=submit"
这是不 JSON,因此不会解码为JSON的方式,你expect.The json_decode()
函数返回null如果它不能被解码。
你从哪里得到上面发布的JSON?这是你需要传递给json_decode()
的价值。
如果在请求中传递JSON,就像在回调的实例中一样,您仍然需要解析该部分才能获得JSON。如果php://input
流为您提供name = ok & submit = submit & json = {“created”:1326853478}然后您必须将其解析出来。您可以使用this function从PHP手册,以单独的值,如$_POST
阵列工作:
<?php
// Function to fix up PHP's messing up POST input containing dots, etc.
function getRealPOST() {
$pairs = explode("&", file_get_contents("php://input"));
$vars = array();
foreach ($pairs as $pair) {
$nv = explode("=", $pair);
$name = urldecode($nv[0]);
$value = urldecode($nv[1]);
$vars[$name] = $value;
}
return $vars;
}
?>
要使用它:
$post = getRealPOST();
$stripe_json = $post['json'];
$event_json = json_decode($stripe_json);
呀。删除隐藏任何错误消息的字符。 –
Igancio指的是@字符。 – Hamish
也可以用'json_last_error()'和/或http://jsonlint.com/来检查,你可能在那里有一个UTF-8 BOM。 – mario