How to validate JSON in PHP?
$ob = json_decode($json);
if($ob === null) {
// $ob is null because the json cannot be decoded
}
$data = json_decode($json_string);
if (is_null($data)) {
die("Something dun gone blowed up!");
}
If you want to check if your input is valid JSON, you might as well be interested in validating whether or not it follows a specific format, i.e a schema. In this case you can define your schema using JSON Schema and validate it using this library.
Example:
person.json
{
"title": "Person",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": ["firstName", "lastName"]
}
Validation
<?php
$data = '{"firstName":"Hermeto","lastName":"Pascoal"}';
$validator = new JsonSchema\Validator;
$validator->validate($data, (object)['$ref' => 'file://' . realpath('person.json')]);
$validator->isValid()