jtourlamain
jtourlamain

Reputation: 169

F# JSON Typeprovider crashes on missing data

How can I handle missing data in a JSON file? With lists of data you can simply use a map function. But what about an object

Say I have sample data:

{
    "Person":{
    "FirstName":"John",
    "LastName":"Doe",
    "Age": 42,
    "Address": {
        "Street": "SomeStreet",
        "City" : "Some City"
        }
    }
} 

And my actual data comes in like:

{
    "Person":{
    "FirstName":"John",
    "Age": 42
    }
} 

I can't figure out how to make the address optional:

type personJson = JsonProvider<"Data/personSample.json">
let personData = testJson.Load("Data/personData.json")

let address = personData.Person.Addres // gives an exception

Also trying to convert it to an optional fails let p = personData.Person.Address |> Option.ofObj

System.Exception: Operation could not be completed due to earlier error  The type 'JsonProvider<...>.Address' does not have 'null' as a proper value at 2,35

I can't imagine I should change the code for each file with some missing data.

So what should I do to solve this?

Upvotes: 2

Views: 141

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36375

You can use SampleIsList = true when setting up your type provider to offer multiple variations on how your objects are shaped.

open FSharp.Data

type personJson = JsonProvider<"Data/personsSample.json", SampleIsList = true>

let personData = personJson.Load("Data/personData.json")

The contents of personsSample.json could look like this, which includes both your original json and a variation of that json without an address:

[
    {
        "Person":{
            "FirstName":"John",
            "LastName":"Doe",
            "Age": 42,
            "Address": {
                "Street": "SomeStreet",
                "City" : "Some City"
                }
        }
    }, 
    {
        "Person":{
            "FirstName":"John",
            "LastName":"Doe",
            "Age": 42
        }
    } 
]

Now when you load a single personData example, referencing the address field will handle a null value correctly instead of crashing.

Upvotes: 5

Related Questions