Walidowanie poprawności JSON-a

Tomasz Tybulewicz
October 28, 2015 | Spotkania

Przykładowa specyfikacja

{
    "id": 1,
    "title": "Hello World!",
    "content": "First post",
    "author_id": 123,
    "is_visible": true,
    "is_deleted": false,
    "tags": ["post", "sample", "test"]
}
{
    "$schema": "http://json-schema.org/draft-04/schema#",
    “type”: “object”,
    "properties": {
        "id": {
            "type": "integer"
        },
        "title": {
            "type": "string"
        },
        "content": {
            "type": "string"
        },
        "author_id": {
            "type": "integer"
        },
        "is_visible": {
            "type": "boolean"
        },
        "is_deleted": {
            "type": "boolean"
        },
        "tags": {
            "type": "array",
            "elements": "string"
        }
    },
    "required": ["id", "title", "content", "author_id", "is_visible", "is_deleted", "tags"]
}

Walidacja JSON Schema z poziomu PHP

composer require justinrainbow/json-schema
    require_once('vendor/autoload.php');

    $retriever = new JsonSchemaUriUriRetriever;
    $schema = $retriever->retrieve('file://' . realpath('schema.json'));
    $data = json_decode(file_get_contents('data.json'));

    $validator = new JsonSchemaValidator();
    $validator->check($data, $schema);

    if ($validator->isValid()) {
        echo "The supplied JSON validates against the schema.n";
    } else {
        echo "JSON does not validate. Violations:n";
        foreach ($validator->getErrors() as $error) {
            echo sprintf("[%s] %sn", $error['property'], $error['message']);
        }
    }

Chcesz poznać nas lepiej? Dowiedz się, co nas wyróżnia.