在 ocaml 中解析 json

parsing json in ocaml

我有一个 json 文件,我正试图将其解析为 ocaml/reasonml。我想做的是将 json 文件解析为 OCaml 数据类型,以便它可以在 OCaml 编写的程序中使用。

[
  {
    "context": "str.substr,str.substr",
    "rule": [
      "C_1"
    ],
    "prob": [
      1.0
    ]
  },
  {
    "context": "Var,C_1",
    "rule": [
      "C_0"
    ],
    "prob": [
      1.0
    ]
  },
  {
    "context": "0,str.substr",
    "rule": [
      "2"
    ],
    "prob": [
      1.0
    ]
  },
  {
    "context": "str.++,C_1",
    "rule": [
      "C_1"
    ],
    "prob": [
      1.0
    ]
  },
  {
    "context": "Var,str.replace",
    "rule": [
      "C_2"
    ],
    "prob": [
      1.0
    ]
  },
  {
    "context": "str.replace,_",
    "rule": [
      "str.replace",
      "Var"
    ],
    "prob": [
      0.8571428571428571,
      0.14285714285714285
    ]
  },

但我收到“某些记录字段未定义”错误 代码是

是我的代码问题还是json文件问题?

type json = {
  context : string;
  rule : string;
  prob : int;
}

let context_json c = 
  {
    context = c |> member "context" |> to_string;
  }

let rule_json r = 
  {
    rule = r |> member "rule" |> to_string;
  }
let parse_context c =
  try context_json c
  with Type_error (s, _) -> failwith ("Parsing error: " ^ s)

let load () =
  let e = Yojson.Basic.from_file "sorted.json" in
  e |> member "context" |> to_list |> List.map context_json

考虑这个函数:

let context_json c =
  {
    context = c |> member "context" |> to_string;
  }

我在您的代码中没有看到 member 的定义。然而,如果我们假设表达式 c |> member "context" |> to_string 是有效的,那么这个函数的结果是一条只有一个字段名为 context 的记录。但是您的记录类型具有三个字段。您需要为记录的所有字段定义值。这就是编译器告诉你的。

如果其他字段始终相同,您可以大致这样定义函数:

let context_json c = 
  { rule = "";
    context = c |> member "context" |> to_string;
    prob = 0;
  }

请注意,您已经使用不可变字段定义了记录类型。因此您以后将无法更改这些值。