JSON (JavaScript Object Notation) is a versatile and widely used format for exchanging and storing data in a structured and human-readable way.
Its simplicity and flexibility make it an ideal choice for data interchange, APIs and Web Services, configuration files, data storage, and serialization.
However, this flexibility can lead to issues if the data structure is not properly validated.
This is where JSON Schema comes into play. It provides a powerful way to validate the structure and content of JSON data.
What is JSON Schema?
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. JSON Schema provides a contract for what a JSON document should look like, defining the expected structure, types, and constraints of the data.
This ensures that the data exchanged between systems adheres to a specific format, reducing the likelihood of errors and improving data integrity.
Why Validate JSON with JSON Schema?
Ensuring Data Integrity: JSON Schema ensures that the JSON data received is syntactically correct and adheres to a predefined structure. This is crucial for maintaining data integrity and preventing errors from unexpected data formats.
Clear Documentation: JSON Schemas serve as clear and precise documentation of the expected JSON structure, making it easier for developers to understand and work with the data.
Enhanced Debugging: By validating JSON against a schema, you can catch errors early in the development process, making debugging easier and more efficient.
Improved Security: Validating JSON data helps prevent common security issues, such as injection attacks, by ensuring the data conforms to the expected format.
JSON syntax validation in PHP
PHP provides built-in support for JSON validation through the json_validate()
function, introduced in PHP 8.3.
Validate JSON with json_validate()
Let's validate a JSON string using PHP's json_validate()
method to check for syntax errors:
$fruitsArray = [
[
'name' => 'Avocado',
'fruit' => '🥑',
'wikipedia' => 'https://en.wikipedia.org/wiki/Avocado',
'color' => 'green',
'rating' => 8,
],
[
'name' => 'Apple',
'fruit' => '🍎',
'wikipedia' => 'https://en.wikipedia.org/wiki/Apple',
'color' => 'red',
'rating' => 7,
],
[
'name' => 'Banana',
'fruit' => '🍌',
'wikipedia' => 'https://en.wikipedia.org/wiki/Banana',
'color' => 'yellow',
'rating' => 8.5,
],
[
'name' => 'Cherry',
'fruit' => '🍒',
'wikipedia' => 'https://en.wikipedia.org/wiki/Cherry',
'color' => 'red',
'rating' => 9,
],
];
if (json_validate($jsonString)) {
echo "Valid JSON syntax.";
} else {
echo "Invalid JSON syntax.";
}
Using json_validate()
function with older versions of PHP
The Symfony Polyfill project brings features from the latest PHP versions to older ones and offers compatibility layers for various extensions and functions. It's designed to ensure portability across different PHP versions and extensions.
Specifically, the Polyfill PHP 8.3 Component brings json_validate()
function to PHP versions before PHP 8.3.
To install the package:
composer require symfony/polyfill-php83
The Poylfill PHP 8.3 official page is: https://symfony.com/components/Polyfill%20PHP%208.3
JSON schema validation in PHP
Syntax VS Schema validation
While this code checks if the JSON string is syntactically correct, it does not ensure the JSON data conforms to the desired structure.
However, json_validate()
only checks if the JSON string is syntactically correct. It does not validate the structure or content of the JSON data.
To achieve comprehensive validation, you can use the swaggest/json-schema
package, which validates JSON data against a specified schema.
Let's walk through a basic example to demonstrate the difference between json_validate()
and validating with JSON Schema using the swaggest/json-schema
package.
Step 1: Install the Package
First, you need to install the swaggest/json-schema package
via Composer:
composer require swaggest/json-schema
Step 2: Define Your JSON Schema
In the example, we will create a JSON schema that defines the expected structure of your data. Let's define a schema for a simple user object, in this case, as a PHP string:
$schemaJson = <<<'JSON'
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "array",
"items" : {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"fruit": {
"type": "string"
},
"wikipedia": {
"type": "string"
},
"color": {
"type": "string"
},
"rating": {
"type": "number"
}
}
}
}
JSON;
Step 3: Validate JSON with JSON Schema
To validate the structure of the JSON data, use the swaggest/json-schema
package
require 'vendor/autoload.php';
use Swaggest\JsonSchema\Schema;
try {
$schemaObject = Schema::import(
json_decode($schemaJson),
)->in(
json_decode($jsonString),
);
echo "JSON is valid according to the schema.";
} catch (\Swaggest\JsonSchema\Exception\ValidationException $e) {
echo "JSON validation error: " . $e->getMessage();
} catch (\Swaggest\JsonSchema\Exception\TypeException $e1) {
echo "JSON validation Type error: " . $e1->getMessage();
}
In this example, the JSON data is validated against the defined schema. An error message is displayed if the data does not conform to the schema.
Conclusion
Validating JSON data is important to ensuring the reliability and security of your applications. While PHP's built-in json_validate()
function is useful for checking JSON syntax, it does not provide comprehensive validation to ensure data structure integrity.
By using JSON Schema and the swaggest/json-schema
package, you can enforce strict validation rules, catch errors early, and maintain a robust and secure application.
Top comments (1)
Thank you very much!