Reputation: 3277
In GitLab web hooks this is the json they give as an example.
{
"before": "95790bf891e76fee5e1747ab589903a6a1f80f22",
"after": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
"ref": "refs/heads/master",
"user_id": 4,
"user_name": "John Smith",
"project_id": 15,
"repository": {
"name": "Diaspora",
"url": "git@localhost:diaspora.git",
"description": "",
"homepage": "http://localhost/diaspora",
},
"commits": [
{
"id": "b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327",
"message": "Update Catalan translation to e38cb41.",
"timestamp": "2011-12-12T14:27:31+02:00",
"url": "http://localhost/diaspora/commits/b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327",
"author": {
"name": "Jordi Mallach",
"email": "[email protected]",
}
},
{
"id": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
"message": "fixed readme",
"timestamp": "2012-01-03T23:36:29+02:00",
"url": "http://localhost/diaspora/commits/da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
"author": {
"name": "Code Solution dev user",
"email": "gitlabdev@dv6700.(none)",
},
},
],
"total_commits_count": 4,
}
I've placed this in a file test.json
.
I'm calling this with file_get_contents() then trying to decode but I'm getting nothing back at all.
$test = file_get_contents('test.json');
$json = json_decode($test);
echo "<pre>";
print_r($json);
echo "</pre>";
returns:
<pre></pre>
Any ideas why json_decode()
is failing to decode?
Upvotes: 1
Views: 5696
Reputation: 3277
Actually it wasn't stray commas as the answerers suggested, JSONLint reported BOM artifacts from UTF-8, I'm assuming from copying and pasting.
Once I ran it through and removed the BOM artifacts it decoded properly.
Thanks to all for your help and suggestions.
Upvotes: 0
Reputation: 13263
It is because of a stray comma. You should check for errors:
if (json_last_error() != JSON_ERROR_NONE) {
die(json_last_error_msg());
}
If you have PHP <5.5.0 then you can use this compatibility function:
if ( ! function_exists('json_last_error_msg')) {
function json_last_error_msg() {
static $errors = array(
JSON_ERROR_NONE => null,
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch',
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
);
$error = json_last_error();
return array_key_exists($error, $errors) ? $errors[$error] : "Unknown error ({$error})";
}
}
Upvotes: 2