I am using the JSON type provider from the F# Data library to access JSON documents from an API. The documents contain a property (let's call it 'car') that sometimes is an array of objects and sometimes a single object. It is either this:
'car': [
{ ... },
{ ... }
]
or this:
'car': { ... }
The object in { ... }
has the same structure in both cases.
The JSON type provider indicates that the property is of type:
JsonProvider<"../data/sample.json">.ArrayOrCar
where sample.json
is my sample document.
My question is then: How can I figure out whether the property is an array (so that I can process it as an array) or a single object (so that I can process it as an object)?
UPDATE: A simplified sample JSON would look like this:
{
"set": [
{
"car": [
{
"brand": "BMW"
},
{
"brand": "Audi"
}
]
},
{
"car": {
"brand": "Toyota"
}
}
]
}
And with the following code it will be pointed out that the type of doc.Set.[0].Car
is JsonProvider<...>.ArrayOrCar
:
type example = JsonProvider<"sample.json">
let doc = example.GetSample()
doc.Set.[0].Car
If the type of the JSON value in the array is the same as the type of the directly nested JSON value, then JSON type provider will actually unify the two types and so you can process them using the same function.
Using your minimal JSON document as an example, the following works: