JSON schema validation failure: The data ({type}) must match the type: object

Viewed 114

I'm trying to use Opis JSON Schema to validate some JSON in PHP.

I wrote a very basic schema user-data.schema.json:

{
  "$id": "https://www.example.com/user-data.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "User Data",
  "type": "object",
  "required": [ "regIpAddress" ],
  "properties": {
    "regIpAddress": {
      "type": "string"
    }
  },
  "additionalProperties": true
}

Then I attempted to validate the JSON with this code:

$validator = new Validator();
$resolver = $validator->loader()->resolver();
$resolver->registerPrefix('https://www.example.com/', '/app/web/modules/custom/mymodule/schema');
$result = $validator->validate($json_array, 'https://www.example.com/user-data.schema.json');
if ($result->isValid()) {
  $encoded_preferences = json_encode($json_array);
  $this->set('myfield', json_encode($json_array));
} else {
  $error = $result->error();
  $formatter = new ErrorFormatter();

  // Print helper.
  $print = function ($value) {
    return json_encode(
      $value,
      JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
    );
  };
  $user_id = $this->id();
  $error_message = "User id: $user_id " . $print($formatter->formatOutput($error, "verbose"));
  $encoded_preferences = json_encode($json_array);
  throw new InvalidJsonException("JSON user data failed to validate! $error_message, $encoded_preferences");

When I pass JSON data as a PHP associative array:

{
   "regIpAddress":"host.docker.internal",
   "emailVerifyCode":"965",
}

Then I get the following error:

 { "keywordLocation": "#/type", "instanceLocation": "#", "error": "The data ({type}) must match the type: object", "valid": false, "absoluteKeywordLocation": "https://www.example.com/user-data.schema.json#/type" },

I don't understand why I am getting this error because the only required property is regIpAddress, which I am providing in an array.

What is wrong with my schema or input that is causing this error?

Edit

I can fix this error by modifying $json_array before validation by encoding and decoding it:

$json_array = json_decode(json_encode($json_array));
$result = $validator->validate($json_array, 'https://www.example.com/user-data.schema.json');

So what's the right way to fix this?

0 Answers
Related