F# Data: JSON Parser. Using JsonExtensions

核能气质少年 提交于 2019-12-23 16:19:17

问题


It is my first question on SO...so do not judge strictly =)

Usually all my questions techout in chat rooms (believe me, a lot of them =)).

Recently, we are talking about the RosettaCode. And I wondered to complement some of the tasks code to F#

One of them is JSON.

One of the possible solutions is the use of "F# Data: JSON Parser". So my question is linked with it.

This code works well:

open FSharp.Data
open FSharp.Data.JsonExtensions

type Person = {ID: int; Name:string}

let json = """[ { "ID": 1, "Name": "First"  }, { "ID": 2, "Name": "Second" }]"""
json |> printfn "%s"

match JsonValue.Parse(json) with
| JsonValue.Array(x) ->
    x |> Array.map(fun x -> {ID = System.Int32.Parse((x?ID).ToString()); Name = (string x?Name)})
| _ -> failwith "fail json"
|> Array.iter(fun x -> printfn "%i  %s" x.ID x.Name)

Print:

[ { "ID": 1, "Name": "First"  }, { "ID": 2, "Name": "Second" }]
1  "First"
2  "Second"

But it

{ID = System.Int32.Parse((x?ID).ToString()); Name = (string x?Name)}

doesn't look good.

This I read about JsonExtensions,

but when I use

{ID = (x?ID.AsInteger()) ; Name = (x?Name.AsString()) } 

I get compile errors:

  • The field, constructor or "AsInteger" is not defined

  • The field, constructor or "AsString" is not defined

Strangely, thing is that I see accessibility through "open FSharp.Data.JsonExtensions"

So, question: How to use JsonExtensions?


回答1:


I tried to reproduce this using a minimal example, but I do not get the error - can you try the following minimal sample?

#r "...../FSharp.Data.dll"
open FSharp.Data.JsonExtensions
open FSharp.Data

JsonValue.Parse("A").AsArray()
|> Array.map (fun a -> a?ID.AsInteger())

I do not get auto-completion on a?ID. (which is a limitation of the editor), but it compiles fine.

The only reason why I think this could be not working is if you had another open declaration that would import another implementation of the ? operator that is not returning JsonValue.

The JsonValue API is certainly not as nice as just using the type provider - so if you can, I'd probably go for the type provider instead (the low-level API is good if you need to iterate over everything in JSON recursively).



来源:https://stackoverflow.com/questions/33056348/f-data-json-parser-using-jsonextensions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!