I'm setting up an endpoint and I'm expecting to get big JSON requests. Of course, I want to make sure these JSON objects are in the correct format as per my documentation, so that I know when to throw a 400
status code. Here's an example:
{
"name":"John",
"surname":"Smith",
"id_no":82347239,
"residences":[
{
"address":[
"12 Something Road",
"Placeville",
"Countrystan",
"1234"
],
"type":"house"
}
] //etc
}
Currently I'm checking validity by using a massive set of isset()
and is_string()
etc checks. Is there a simpler way to make sure the format matches mine? For instance, can I set up a "template" JSON object and use some function to check that the formats match?
Not the ideal solution, but I wrote a little function that solves about half the problem:
/**
* @param array $testme an assoc array as input to be tested
* @param array $format the format assoc array to be tested against
* @return bool whether or not $testme fits $format
*/
function validate_format(array $testme, array $format){
if ($testme == null or sizeof($testme) == 0)
return false;
$test_keys = array_keys($testme);
foreach (array_keys($format) as $k){
if (!in_array($k, $test_keys))
return false;
else{
switch($format[$k]){
case 'string':
case 'str':
if (!is_string($testme[$k]))
return false;
break;
case 'integer':
case 'int':
if (!is_int($testme[$k]))
return false;
break;
case 'double':
case 'float':
if (!is_double($testme[$k]))
return false;
break;
case 'bool':
case 'boolean':
if (!is_bool($testme[$k]))
return false;
break;
case 'array':
if (!is_array($testme[$k]))
return false;
break;
}
}
}
return true; //all tests passed
}
Example usage:
$input = [
'user_id' => '123',
'password' => 'abc'
];
$format = [
'user_id' => 'int',
'password' => 'string'
];
$valid = validate_format($input, $format);
// false