Car*_*uez 3 f# json type-providers f#-data fsharp.data.typeproviders
我正在使用F#Data库中的JSON类型提供程序从API访问JSON文档.文档包含一个属性(让我们称之为'car'),有时候是一个对象数组,有时候是一个对象.这是:
'car': [
{ ... },
{ ... }
]
Run Code Online (Sandbox Code Playgroud)
或这个:
'car': { ... }
Run Code Online (Sandbox Code Playgroud)
{ ... }在两种情况下,对象具有相同的结构.
JSON类型提供程序指示属性的类型为:
JsonProvider<"../data/sample.json">.ArrayOrCar
Run Code Online (Sandbox Code Playgroud)
sample.json我的样本文件在哪里.
我的问题是:我怎样才能弄清楚属性是一个数组(以便我可以将它作为数组处理)还是单个对象(以便我可以将它作为一个对象处理)?
更新: 简化的示例JSON将如下所示:
{
"set": [
{
"car": [
{
"brand": "BMW"
},
{
"brand": "Audi"
}
]
},
{
"car": {
"brand": "Toyota"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
并且使用以下代码将指出类型doc.Set.[0].Car是JsonProvider<...>.ArrayOrCar:
type example = JsonProvider<"sample.json">
let doc = example.GetSample()
doc.Set.[0].Car
Run Code Online (Sandbox Code Playgroud)
如果数组中JSON值的类型与直接嵌套的JSON值的类型相同,那么JSON类型提供程序实际上将统一这两种类型,因此您可以使用相同的函数处理它们.
以最小的JSON文档为例,以下工作原理:
type J = JsonProvider<"sample.json">
// The type `J.Car` is the type of the car elements in the array
// but also of the car record directly nested in the "car" field
let printBrand (car:J.Car) =
printfn "%s" car.Brand
// Now you can use pattern matching to check if the current element
// has an array of cars or just a single record - then you can call
// `printBrand` either on all cars or on just a single car
let doc = J.GetSample()
for set in doc.Set do
match set.Car.Record, set.Car.Array with
| Some c, _ -> printBrand c
| _, Some a -> for c in a do printBrand c
| _ -> failwith "Wrong input"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
927 次 |
| 最近记录: |