Reputation: 615
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
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";
}
strtolower()
empty()
meaning all properties existUpvotes: 1
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