user3704920
user3704920

Reputation: 615

JSON Data - Validate Properties in PHP

I'm trying to validate a simple schema against large JSON data. I only need to find if the properties I'm using in my PHP code are present in the JSON data. I've looked at several libraries but they seem overkill since they even validate the data type and I only need the presence of properties.

For example: PHP variables I use: name, age, gender JSON Data:

{
  "Location": "10.2.00",
  "Name": "Foo",
  "Age": "30",
  "Race": "NA",
  "Gender": "Male"
}

So there could be extra data in JSON.

How can I check for the presence of JSON variables in my PHP code or another JSON schema?

Upvotes: 1

Views: 133

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 79014

So with the addition of the case-insensitivity:

$props = array('name', 'age', 'gender');
$array = array_map('strtolower', array_keys(json_decode($json, true)));

if(empty(array_diff($props, $array))) {
    echo "All properties exist";
}
  • Use an array of lowercase property names
  • Get the keys from the JSON and map to strtolower()
  • Check if the difference is empty() meaning all properties exist

Upvotes: 1

Don't Panic
Don't Panic

Reputation: 41820

If you just need to verify that the keys from your simple schema are present, you can use array_diff_key.

Define your simple schema (keep in mind that the keys are case sensitive.)

$simple_schema = ['Name', 'Age', 'Gender'];

Decode your large JSON data (be sure to use the second argument of json_decode to get an array for comparison.)

$json = json_decode($large_json_data, true);

Then get the difference using array_diff_key.

$missing_keys = array_diff_key(array_flip($simple_schema), $json);

The array_flip converts the values of your simple schema to keys for the comparison.

if $missing_keys is empty, then all the keys in your schema were present in the large JSON data.

Upvotes: 1

Related Questions