验证JSON数组是否有一个具有固定整数值的关联数组



我正在尝试使用Opis的包验证一些JSON。我正在尝试验证一个数组是否至少有一个值为1id关联数组。这是我得到的代码:

$json = [
[
'id' => 1,
],
[
'id' => 2,
],
[
'id' => 3
]
];
$rules = [
'type' => 'array',
'contains' => [
'type' => 'array',
'properties' => [
'id' => [
'type' => 'integer',
'const' => 1,
],
],
'required' => ['id']
],
'minContains' => 1,
];
$validated = Common::validateJSON($json, json_encode($rules));

这里是validateJSON方法代码:

public static function validateJSON($json, $rules)
{
$validator = new Validator();
// Validate
$result = $validator->validate($json, $rules);
if ($result->isValid()) {
return true;
}
$errorMessages = [];
if ($result->hasError()) {
$formatter = new ErrorFormatter();
$errorMessages[] = $formatter->format($result->error());
}
return $errorMessages;
}

因此,在这种情况下,$validated返回:

array:1 [
0 => array:1 [
"/" => array:1 [
0 => "At least 1 array items must match schema"
]
]
]

$rules更改为:

$rules = [
'type' => 'array',
'contains' => [
'type' => 'array',
],
'minContains' => 1,
];

返回相同的结果,这对我来说很奇怪。

const更改为任何数字都不会更改返回的内容。所以,我的猜测是我做错了什么,但我不知道是什么。

我一直在谷歌上搜索各种各样的东西,没有任何帮助。我一直在研究JSON模式站点,特别是在这里,但我还没有弄清楚。

在验证之前,由于我不是json解码数据,因为它不是来自http请求,请执行以下操作:

$json = json_encode($json);
$json = json_decode($json); // this, I think, will turn associative arrays into objects which makes it work

第二个CCD_ 7必须是CCD_。

最新更新