F # Data: JSON Parser. Using JsonExtensions

This is my first question about SO ... so don't judge strictly =)

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

Recently, we are talking about RosettaCode . And I would like to add some of the task codes to F #

One of them is JSON .

One possible solution is to use "F # Data: JSON Parser". So my question is related to this.

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 he

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

It doesn’t look very good.

This is what I read about JsonExtensions,

but when i use

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

I get compilation errors:

  • Field, Constructor, or "AsInteger" Not Defined

  • Field, Constructor, or "AsString" Not Defined

Strange, the fact is that I see accessibility through "open FSharp.Data.JsonExtensions"

enter image description here

So the question is: how to use JsonExtensions?

+5
source share
1 answer

I tried to reproduce this using a minimal example, but I am not getting an 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 autocomplete on a?ID. (which is an editor’s limitation), but it compiles fine.

The only reason I think this might not work is if you had another open declaration that would import a different implementation of the statement ? which does not return JsonValue .

The JsonValue API, of course, is not as good as just using a type provider, so if you could, I would probably go for a type provider (a low-level API is good if you need to iterate over everything in JSON recursively).

+3
source

Source: https://habr.com/ru/post/1233422/


All Articles