2

我正在尝试使用 webclient 模块来查询 couchDB 休息接口(我使用它而不是 opa couchdb api,因为我需要获取特定数量的文档)。

这是用于进行查询的代码:

listmydocs(dburi)=
match  WebClient.Get.try_get(dburi) with
      | { failure = _ } -> print("error\n")
      | {success=s} ->  match WebClient.Result.get_class(s) with
          | {success} -> print("{s.content}")                               
          | _         -> print("Error {s.code}")
      end

s.content 中给出的结果是以下字符串:

{"total_rows":177,"offset":0,"rows":[
{"id":"87dc6b6d9898eff09b1c8602fb00099b","key":"87dc6b6d9898eff09b1c8602fb00099b","value":{"rev":"1-853bd502e3d80d08340f72386a37f13a"}},
{"id":"87dc6b6d9898eff09b1c8602fb000f17","key":"87dc6b6d9898eff09b1c8602fb000f17","value":{"rev":"1-4cb464c6e1b773b9004ad28505a17543"}}
]}

我想知道解析此字符串以获取例如 id 列表或仅行字段的最佳方法是什么?我尝试使用 Json.deserialize(s.content) 但不确定从那里去哪里。

4

1 回答 1

3

您可以在 Opa 中有几种方法两个反序列化 Json 字符串:

1 - 第一个是简单地使用 Json.deserialize,它接受一个字符串并根据 Json 规范生成一个 Json AST。然后您可以匹配生成的 AST 以检索您想要的信息。

match Json.deserialise(a_string) with
| {none} -> /*Error the string doesn't respect json specification*/
| {some = {Record = record}} ->
/* Then if you want 'total_rows' field */
  match List.assoc("total_rows", record) with
  | {some = {Int = rows}} -> rows
  | {none} -> /*Unexpected json value*/

2 - 另一种方法是使用来自 Json 的“神奇” opa 反序列化。首先定义期望值对应的Opa类型。然后使用 OpaSerialize.* 函数。根据你的例子

type result = {
  total_rows : int;
  offset : int;
  rows : list({id:string; key:string; value:{rev:string}})
}
match Json.deserialize(a_string)
| {none} -> /*Error the string doesn't respect json specification*/
| {some = jsast} ->
  match OpaSerialize.Json.unserialize_unsorted(jsast) with
  | {none} -> /*The type 'result' doesn't match jsast*/
  | {some = (value:result) /*The coercion is important, it give the type information to serialize mechanism*/} ->
    /* Use value as a result record*/
    value.total_rows
于 2012-01-09T09:50:06.217 回答