oferei / json-gate

A friendly, fast JSON schema validator
MIT License
100 stars 16 forks source link

Add sanitize attribute to clean object #25

Closed andersonba closed 10 years ago

andersonba commented 10 years ago

Cleans object, removing non-matching properties.

See bellow:

// Schema
{
   str: { type: 'string' },
   sanitize: true
}
// Object
{
   str: 'hi',
   extra: 'unimportant data, discard this',
   extra1: 'discard this'
}
// Result object (after validate):
{
   str: 'hi'
}
// Getting result object
newObject = schema.validate(Object);

// or
schema.validate(Object, function(err, obj) {
   newObject = obj;
});
oferei commented 10 years ago

interesting feature. is the additionalProperties not enough?

andersonba commented 10 years ago

Thanks!

No, because additionalProperties throws an error when it finds an non-matching property. The "sanitize" attribute just filters out, removing from object or just silently ignored.

oferei commented 10 years ago

ok. but let's discuss the interface a bit, as this would be the 1st time that I deviate from the "standard". one thing that tickles me the wrong way is the use of the 'sanitize' attribute. specifically 2 things:

  1. right now it can be 'true' or 'false' or 'la la la' and always be considered trueish (activate sanitization)
  2. it does not play nice with additionalProperties - it overrides it. for example, if sanitize is 'true' and additionalProperties is set to some schema (which means additional properties are allowed)

possible solutions:

  1. sanitize must be true or false. and it can only be true if additionalProperties is false
  2. additionalProperties can be set to a special value: sanitize/clear/remove ("additionalProperties": "remove")

what do you think?

andersonba commented 10 years ago

Good idea! :thumbsup:

The second solution seems better.

I had to use sanitize because I needed implement in a company's project where I work. Your solution is a better way to simplify this feature.

andersonba commented 10 years ago

Done.

additionalProperties: 'remove'

What do you think?

andersonba commented 10 years ago

I moved this feature to new branch: https://github.com/oferei/json-gate/pull/27