1

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?

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Don't Panic this is a gorgeous solution. The only down-side I see is the case sensitivity. Anyway to make insensitive?
It's possible to do it case-insensitively, but I don't think it would be possible with array_diff_key. You'd probably need to loop and convert both keys to a common case. If you knew that all the keys in the large data would be in a certain case, you could convert your simple schema keys to that case beforehand.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.