[英]Is there a way to enumerate JSON properties using F# JsonProvider?
I parse some data in JSON format using F# and JSON Type Provider.我使用 F# 和 JSON 类型提供程序以 JSON 格式解析一些数据。
example.json:示例.json:
{
"contracts": {
"11": {
"id": 11,
"date": "08.01.2021"
},
"12": {
"id": 12,
"date": "09.01.2021"
},
"13": {
"id": 13,
"date": "11.01.2021"
}
}
}
My F# code:我的 F# 代码:
namespace Analyse
open Microsoft.FSharp.Reflection
module AnalyserExample =
open System
open FSharp.Data
let [<Literal>] SampleFile = @"example.json"
type ContractsProvider = JsonProvider<SampleFile>
let contracts () =
let data = ContractsProvider.Parse("example.json")
let contracts = data.Contracts
contracts.``11``
contracts.``12``
contracts.``13``
JsonProvider works as expected, every contract is parsed as a field, but I want to enumerate them. JsonProvider 按预期工作,每个合同都被解析为一个字段,但我想枚举它们。 I have some options.我有一些选择。 Using reflection to get a list of fields or transform JSON using some custom transformation before type provider initialization runs, but I like neither of them.在类型提供程序初始化运行之前,使用反射来获取字段列表或使用一些自定义转换来转换 JSON,但我不喜欢它们。
Is there a way to transform this structure into a sequence using JsonProvider, or some F# sorcery?有没有办法使用 JsonProvider 或一些 F# 巫术将此结构转换为序列?
You can do this via the underlyingJsonValue
, which is what JsonProvider
is built on:您可以通过底层的JsonValue
来做到这一点,这是JsonProvider
的基础:
let data = ContractsProvider.Parse(sample)
let contracts = data.Contracts
for _, value in contracts.JsonValue.Properties() do
printfn "%A" value
There's little value in using JsonProvider
at all in this scenario, though.不过,在这种情况下使用JsonProvider
几乎没有什么价值。 You'd be better off skipping it, and running the parser dynamically instead:你最好跳过它,而是动态运行解析器:
let data = JsonValue.Load("example.json")
for _, value in data.["contracts"].Properties() do
printfn "%A" value
That way, you're not relying on the JSON to always consist exactly of contracts 11
, 12
and 13
.这样,您就不会依赖 JSON 始终完全由合约11
、 12
和13
组成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.