Introducing FSharp.Data.JsonValidation
A nifty little DSL for validating that JSON matches an expected schema.
First things first...
Let's include the library (use #r
if you're writing an fsx), also include FSharp.Data
1: 2: 3: 4: |
|
Define your schemas
Next define some schemas that describe how the JSON you're expecting should look. Schemas are just values and can easily be combined.
1: 2: 3: 4: 5: 6: 7: 8: 9: |
|
where looksLikeAnEmail
is a silly little helper for illustrative purposes (i.e. you probably
don't want to use this in production code) that looks like
1: 2: |
|
Validate some JSON!
Lastly let's try some actual JSON!
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: |
|
What's going on here?
We're defining two different schemas
1: 2: 3: |
|
someNumbers
is a simple schema that describes a JSON array whose items are any number.
It will only be valid if, well, it's exactly that: an array containing number (or perhaps none).
person
is a slightly more complicated schema. It says that a person must be a JSON object
that must have a "name"
key whose value is a non-empty string. ( .= )
indicates a required key
whose value matches another schema.
The person
object must also have "favoriteNumbers"
which can be someNumbers
(here we're re-using
our other schema).
Finally, we're saying that person
may have an "email"
key with a value that meets some criteria.
( .?= )
indicates an optional key and MeetsCriteria
takes a description of the expectation and an
actual function (a predicate) to check whether it matches.