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