Parsing input from Express request body into custom Fsharp record type with Thoth.Json


While converting an existing nodejs API to Fsharp with fable I saw that I need to convert a JS record into an fsharp type. My current problem is that apparently Thoth.Json only works with json strings as input. As far as I’ve searched there’s no parser to convert javascript objects to custom fsharp record types.

My current solution is to JSON.stringify the body and then parse that into my decoders. Is there a better solution?

It sounds like you have a JS object in memory and you want to write a function to convert that into an F# record within Fable code. In that case you don’t need a parser at all. You need a function that takes the raw JS object (type obj) and returns your record.

If you know the JS object is already in the exact Fable representation of your record then you can do an unsafe cast from obj to your record. If your assumption here was wrong then you will probably get a runtime exception later on in your code.

Otherwise, you will need to use JS interop to convert the object into your type. During this conversion you can change the shape of the object and validate the types, and maybe return an error if the object isn’t valid.

Here is some code demonstrating both of these options (without any validation):

open Fable.Core.JsInterop

let jsObj : obj = box {| A = 1; B = "2" |}


type MyRecord = { A : int; B : string }

let casted : MyRecord =
  jsObj :?> MyRecord

Browser.Dom.console.log(casted.A, casted.B)

let converted : MyRecord =
    { A = jsObj?A
      B = jsObj?B }

Browser.Dom.console.log(converted.A, converted.B)

You can run and edit the code here. Note that you might need to open your browser console to see the console output.

1 Like

Thank you for your input @Prash!

I see that probably I’ll have to probably use some glue code to make it work. However, my objective was to delegate all parsing to fsharp, because I want to one day replace the nodejs runtime with dotnet with fsharp.

Of course, I’d like to avoid any runtime errors at all cost, so I’m all in with the safest option.

I guess I could check for property existence with fsharp and some really small js functions to safely parse objects into my fsharp code. However, that’s a lot of work that a framework could do.

Maybe there’s a better tool for this that I don’t know?