json_decode无法解码json数据

时间:2014-04-04 23:02:01

标签: php json

在GitLab web钩子中,这是他们给出的json作为例子。

{
  "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": "jordi@softcatala.org",
      }
    },
    {
      "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,
}

我已将此信息放在test.json文件中。

我用file_get_contents()调用它然后尝试解码,但我什么都没有回来。

$test = file_get_contents('test.json');

$json = json_decode($test); 

echo "<pre>";
print_r($json);
echo "</pre>";

返回:

<pre></pre>

为什么json_decode()无法解码的任何想法?

2 个答案:

答案 0 :(得分:1)

这是因为一个流浪逗号。你应该检查错误:

if (json_last_error() != JSON_ERROR_NONE) {
    die(json_last_error_msg());
}

如果你有PHP <5.5.0,那么你可以使用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})";
    }
}

答案 1 :(得分:0)

实际上,回答者建议不是流浪逗号,JSONLint报告了UTF-8的BOM工件,我假设是复制和粘贴。

一旦我完成并删除了BOM工件,它就会正确解码。

感谢大家的帮助和建议。