Let's say there is a provider like this:
type ColorProvider = JsonProvider<"""
{
"id": "b35b5bcf-761a-4e50-9ff0-4c7de7dd0e5d",
"color": "Red"
}
""">
Trying to print colors from a collection will fail if one of these object doesn't have the color property at all:
dataAccess.QueryAsEnumerable<string>("SELECT Data FROM Objects")
|> Seq.map ColorProvider.Parse
|> Seq.iter (fun item -> printfn "%A" item.Color)
There is a JsonValue.Null to compare to but in this case it's not null, the property is just missing.
How to filter out items without the color property?
Your solution with
TryGetPropertyworks, but there is much nicer way - you can use a more representative sample with two records where thecolorproperty is missing for one of them:Then, the
Colorproperty is inferred asoption<string>and you can handle it nicely using either pattern matching on options, or usingdefaultArg: