【发布时间】:2014-09-23 09:01:20
【问题描述】:
我正在尝试将 FSharp.Data 示例转换为我正在处理的问题的解决方案,但我并没有走得太远。
问题
给定一个返回 json 的端点,类似于:
{
Products:[{
Id:43,
Name:"hi"
},
{
Id:45,
Name:"other prod"
}
]
}
如何加载数据,然后只从真实的现有数据中获取Ids?
我不明白如何“模式匹配”以下可能性:
- 它不会返回任何东西
-
root.Products可能不存在/为空 -
Id可能不存在
尝试通过空匹配
namespace Printio
open System
open FSharp.Data
open FSharp.Data.JsonExtensions
module PrintioApi =
type ApiProducts = JsonProvider<"https://api.print.io/api/v/1/source/widget/products?recipeId=f255af6f-9614-4fe2-aa8b-1b77b936d9d6&countryCode=US">
let getProductIds url =
async {
let! json = ApiProducts.AsyncLoad url
let ids = match json with
| null -> [||]
| _ ->
match json.Products with
| null -> [||]
| _ -> Array.map (fun (x:ApiProducts.Product)-> x.Id) json.Products
return ids
}
【问题讨论】: