【问题标题】:Validate that JSON array has one associative array with fixed integer value验证 JSON 数组是否有一个具有固定整数值的关联数组
【发布时间】:2022-01-22 20:59:12
【问题描述】:

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

    $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 架构站点,尤其是 here,但我还没有弄清楚。

【问题讨论】:

    标签: php arrays json validation


    【解决方案1】:

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

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

    第二个type 必须是object

    【讨论】:

      猜你喜欢
      • 2010-12-02
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 2021-02-26
      • 2020-05-30
      相关资源
      最近更新 更多