Nikolai Koudelia
Nikolai Koudelia

Reputation: 2639

How to deal with missing properties in FSharp.Data JsonProvider?

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?

Upvotes: 3

Views: 521

Answers (2)

Tomas Petricek
Tomas Petricek

Reputation: 243051

Your solution with TryGetProperty works, but there is much nicer way - you can use a more representative sample with two records where the color property is missing for one of them:

type ColorProvider = JsonProvider<"""[
  { "id": "b35b5bcf", "color": "Red" },
  { "id": "b2542345" } ]""", SampleIsList=true>

Then, the Color property is inferred as option<string> and you can handle it nicely using either pattern matching on options, or using defaultArg:

dataAccess.QueryAsEnumerable<string>("SELECT Data FROM Objects")
|> Seq.map ColorProvider.Parse
|> Seq.iter (fun item -> printfn "%s" (defaultArg item.Color " - "))

Upvotes: 5

Nikolai Koudelia
Nikolai Koudelia

Reputation: 2639

Okay, found it here:

dataAccess.QueryAsEnumerable<string>("SELECT Data FROM Objects")
|> Seq.map ColorProvider.Parse
|> Seq.iter (fun item ->
    match item.JsonValue.TryGetProperty("color") with
    | Some color -> printfn "%A" color
    | None -> printfn "%s" " - "
)

Upvotes: 1

Related Questions