Search code examples
jsonf#type-providers

JSON TypeProvider and null values in arrays


This code

open FSharp.Data

[<Literal>]
let sample = """
    { "foo": [
        10,
        null
       ]
    }
"""
type InputTypes = JsonProvider<sample>

InputTypes.Parse(sample).Foo |> Dump

Results in Foo being type int[] and the containing a single value of 10. I was expecting Foo to be type Nullable<int> [] or int option [] and length of 2.

I had a look through the docs and SO but could find any information on it.

Is there a way to tell the JsonProvider not to ignore nulls, or is it baked in ?


Solution

  • I do not think there is a way to tell JSON provider not to do this, but I agree it would sometimes be useful (in case you wanted to try contributing to the project!)

    In the meantime, if you want to iterate over all the values in the array, including nulls, you can use the low-level underlying JsonValue directly. It is less elegant, but lets you do what you need for this one part of JSON processing:

    [<Literal>]
    let sample = """{ "foo": [ 10, null ] }"""
    type InputTypes = JsonProvider<sample>
    
    InputTypes.Parse(sample).JsonValue.["foo"].AsArray()
    |> Array.map (function 
        | JsonValue.Number n -> Some n 
        | _ -> None)