G
G
ganjo8882019-09-16 13:29:52
PHP
ganjo888, 2019-09-16 13:29:52

How to validate jsonShema?

For validation, I use the justinrainbow/json-schema library

$pathSchema = file_get_contents('/source/test.json');

 $validator = new Validator();
            $validator->check(json_decode($data),
                (object)$pathSchema);

if ($validator->isValid()) {
              echo  "valid";
            } else {
                echo  "not valid";
            }

The content of $data
array (size=8)
  0 => 
    object(stdClass)[175]
      public 'id' => int 1
      public 'name' => string 'Москва' (length=12)
  1 => 
    object(stdClass)[194]
      public 'id' => int 2
      public 'name' => string 'Республика Коми' (length=29)

contents of $pathSchema
{
  "id": {
    "type": "number",
  },
  "name": {
    "type": "number",
  }
}

deliberately trying to form incorrect data,
for some reason I get 'valid' all the time, although the scheme is not correct

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Romashkan, 2019-09-16
@EvgeniiR

To prohibit sending extra fields, you need to describe objects in the schema, declare their properties (properties) and specify the parameter in the schemaadditionalProperties => false

{
  "type": "object",
  "properties": {
    "number":      { "type": "number" },
    "street_name": { "type": "string" }
  },
  "additionalProperties": false
}

https://json-schema.org/understanding-json-schema/...

H
hesy, 2019-09-16
@hesy

function is_valid_json($str) 
{
    json_decode($str);
    return (json_last_error() == JSON_ERROR_NONE);
}

if (is_valid_json($str)) {
    echo 'valid';
} else {
    echo 'invalid';
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question