如何访问escript json组合子中的解码



试图使用来自重写json组合子库的decode,有人提到解码器已经变得抽象,必须通过decode.decode 运行

let targetValue: JsonCombinators.Json.Decode.decode<Web.Json.t, string>

尝试以这种方式使用会引发以下错误:找不到此类型构造函数JsonCombinators.Json.Decode.decode

这是正确的使用方法吗?如果不知道如何修复这个错误的话?

我不完全确定你在这里试图用targetValue做什么,但解码器的类型构造函数是Json.Decode.t,并且只接受一个参数,即它将产生的类型。还有一个函数Json.Decode.decode,它也可以通过Json.decode获得,它取一个解码器和一个Js.Json.t值,并根据该值运行解码器以产生一个result,如果成功,它将包含解码值。

以下是README示例的缩写版本,带有一些类型注释,希望能更好地说明它:

type point = {
x: int,
y: int,
}
module Decode = {
open Json.Decode
let point: t<point> = object(field => {
x: field.required(. "x", int),
y: field.required(. "y", int),
})
}
let result: result<point, string> =
Json.decode(json, Decode.point)
switch result {
| Ok(point) => 
let {x, y} = point
Js.log(`Got point - x: ${x}, y: ¢{y}`)
| Error(err) => Js.log(err)
}

最新更新