Return only known properties #729
Unanswered
fredericgboutin-yapla
asked this question in
Q&A
Replies: 1 comment 3 replies
-
This is a bit of BS but ATM I think I can live with a simple filtering method done post validation and based on the schema, function filter($data, \stdClass $schema)
{
if (!isset($schema->type)) {
// We don't support things like https://json-schema.org/understanding-json-schema/structuring#dollarref, only explicit types
throw new \Exception('No type defined in schema');
}
switch ($schema->type) {
case 'object':
if (!is_object($data)) {
throw new \Exception('Unable to filter properties on non-object');
}
$filteredData = new \stdClass();
// Filter all properties
foreach ($schema->properties ?? [] as $propertyName => $propertyDefinition) {
if (property_exists($data, $propertyName)) {
$filteredData->$propertyName = filter($data->$propertyName, $propertyDefinition);
}
}
return $filteredData;
case 'array':
if (!is_array($data)) {
throw new \Exception('Unable to filter items on non-array');
}
$filteredData = [];
// Filter all items
foreach ($data as $item) {
$filteredData[] = filter($item, $schema->items);
}
return $filteredData;
default:
// This includes: string, numeric types, boolean and null
return $data;
}
}
filter(
json_decode($jsonDocument, false),
json_decode($jsonSchema, false),
); |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
One use case I end-up with constantly is that, sure I validate my JSON when parsing it but the code that follows and uses the parsed document might use properties that are not defined in my JSON schema (thus not validated) because I'm trying to keep the JSON schema as short as possible. The reasoning is that I don't want to / I cannot document the entire schema but rather a subset of what I'm using so the validation won't fail on things I don't use anyway.
So, I basically need to filter my JSON document after validating it based on the defined JSON schema properties and I thought, maybe there is something in there for me in
justinrainbow/json-schema
but no luck. There are several very valuable flags / constraint but none that would "filter out not validated data".Do you guys have any experience with this?
Thank you!
Beta Was this translation helpful? Give feedback.
All reactions