我们下载了一个JSON文件格式的每日提要。从那里,一系列脚本解析JSON文件。但是,我想使这个过程更加健壮,并在继续之前检查以确保下载的文件确实是JSON格式的。它可能不是JSON格式,因为一些原因,比如数据传输问题,或者有人把错误的文件放在那里供我们下载。无论哪种方式,我都希望能够在继续解析脚本之前检查文件并验证它是JSON文件格式。
是否有一个PHP方法来验证文件是JSON格式?谢谢!
这样行吗?
// Returns True if JSON data is good, false if bad.
function isJson($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
// invalid JSON data
$json = 'blablabla{"user_id":14,"username":"flow"}]foobar';
if(isJson($json))
{
echo "good" . "'n";
}
else {
echo "bad" . "'n";
}
json_decode
已经验证了输入:如果它无效,它返回null
。
在不太可能的情况下,您想要区分无效输入和"null"
(即null
的JSON表示),您可以手动执行额外的检查:
if(stricmp(trim($input), "null") == 0) {
// $input is a json representation of null
}
我会尝试使用jsonlint: https://github.com/zaach/jsonlint它可以做更多的事情,但也是一个验证器