How to create a Js.Json.t from a record? (without libs or ppx)

I would like to create Json from a record so I can send it in a fetch or graphql request.
Ideally would be something like this

type params = { purchaseOrderId: string }
let params2 = { purchaseOrderId: "44" }

let json = params2->Js.Json.object_ // fails

My current workaround is to do this

let params1 =
        list{("purchaseOrderId", "44"->Js.Json.string)}
        ->Js.Dict.fromList
        ->Js.Json.object_

but I wonder if there is a better way

If you don’t need the intermediate Js.Json.t, you can use Js.Json.stringifyAny

Playground example

@Minnozz I tried it but it throws the following error

This has type: option<string>
Somewhere wanted: Js.Json.t (defined as Js_json.t)

You can call Js.Json.parseExn after stringifying. But it would be safer to use dict as you do it right now.

1 Like

I’d go for:

external recordAsJson: 'a => Js.Dict.t<Js.Json.t> = "%identity"

let json = params2->recordAsJson→Js.Json.object_
1 Like

very cool [playground]

One thing to beware of, records can contain functions or self-recursive values, but JSON cannot.

5 Likes

Absolutely, only use that when confident your structure only contains serializable values :+1:

2 Likes