0

We get a daily feed downloaded which is in JSON file format. From there a series of scripts parse the JSON file. However, I want to make the process more robust and have it check to make sure the downloaded file is indeed in JSON format before it proceeds. It might not be in JSON format for several reasons such as a data transmission problem or someone put the wrong file in there for us to download. Either way, I would like to be able to check the file and verify it is in JSON file format before proceeding with the parsing scripts.

Is there a PHP method to verify that a file is in JSON format? Thanks!

Would this do?

// 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";
}
4

2 回答 2

5

json_decode已经验证了输入:如果它无效,则返回null.

在您想要区分无效输入和"null"(即 的 JSON 表示null)之间的不太可能的情况下,您可以手动执行额外的检查:

if(stricmp(trim($input), "null") == 0) {
    // $input is a json representation of null
}
于 2013-05-01T10:41:56.603 回答
0

我会尝试使用 jsonlint:https ://github.com/zaach/jsonlint 它可以做更多事情,但也是一个验证器

于 2013-05-01T10:45:27.453 回答