解码json树结构
在bs json库中,提供了一个使用解码json树结构,json,reason,bucklescript,Json,Reason,Bucklescript,在bs json库中,提供了一个使用和组合器将json结构转换为树的示例。原始示例可以在ML接口文件中找到。将函数decodeTree从此文件复制到浏览器“原因工具”显示语法错误 如果有人能给我指点,我会非常感激的 我试图将其转换为Reason3,结果导致了一个类型错误。代码如下: type tree('a) = | Node('a, list(tree('a))) | Leaf('a); let json = {| { "type": "node", "value": 9
和组合器将json结构转换为树的示例。原始示例可以在ML接口文件中找到。将函数decodeTree
从此文件复制到浏览器“原因工具”显示语法错误
如果有人能给我指点,我会非常感激的
我试图将其转换为Reason3,结果导致了一个类型错误。代码如下:
type tree('a) =
| Node('a, list(tree('a)))
| Leaf('a);
let json = {| {
"type": "node",
"value": 9
"children": [{
"type": "leaf",
"value": 5,
"children": [{
"type": "leaf",
"value": 3
}, {
"type": "leaf",
"value": 2
}]
}, {
"type": "leaf",
"value": 4
}]
} |};
let decodeTree = (decodeValue, json) =>
Json.Decode.(
field("type", string)
|> andThen(type_ =>
switch type_ {
| "node" =>
Node(
field("value", decodeValue),
field("children", children =>
children |> array(decodeTree) |> map(Array.to_list)
)
)
| "leaf" => Leaf(field("value", decodeValue))
}
)
);
let myTree = json |> Json.parseOrRaise |> decodeTree(Json.Decode.int);
这是类型错误
This has type:
tree('a)
But somewhere wanted:
Json.Decode.decoder('b) (defined as (Js.Json.t) => 'b)
很抱歉。不完全确定这个例子到底是怎么回事。这里有一个应该有效的方法:
/*解码JSON树结构*/
类型树('a)=
|节点('a,列表(树('a)))
|叶('a);
模块解码={
打开Json.Decode;
让rec tree=解码器=>
字段(“类型”,字符串)|>然后(
乐趣|“节点”=>节点(解码器)
|“叶”=>叶(解码器)
|\=>failwith(“未知节点类型”)
)
和节点=(解码器,json)=>
节点(
json |>字段(“值”,解码器),
json |>field(“children”,数组(树(解码器))|>map(array.to_列表))
)
和叶=(解码器,json)=>
叶(json |>字段(“值”,解码器));
};
设json={|{
“类型”:“节点”,
“价值”:9,
“儿童”:[{
“类型”:“节点”,
“价值”:5,
“儿童”:[{
“类型”:“叶”,
“价值”:3
}, {
“类型”:“叶”,
“价值”:2
}]
}, {
“类型”:“叶”,
“价值”:4
}]
} |};
让我的树=
json |>json.parseOrRaise
|>Decode.tree(Json.Decode.int);
Edit:您遇到的特定错误是由于和需要解码器,但被赋予树('a)
(节点
或叶
)。要将其转换为解码器,只需添加一个json参数,然后将其传递给字段解码器:
|> andThen((type_, json) =>
switch type_ {
| "node" =>
Node(
json |> field("value", decodeValue),
json |> field("children", children =>
children |> array(decodeTree) |> map(Array.to_list)
)
)
| "leaf" => json |> Leaf(field("value", decodeValue))
}
)