【问题标题】:parsing a webclient.Result content in OPA在 OPA 中解析 webclient.Result 内容
【发布时间】:2012-01-08 09:52:18
【问题描述】:

我正在尝试使用 webclient 模块来查询 couchDB REST 接口(我使用它而不是 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) 但不确定从那里去哪里。

【问题讨论】:

    标签: couchdb opa


    【解决方案1】:

    你可以有几种方法在 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
    

    【讨论】:

    • 谢谢,“神奇”的 opa 反序列化方法绝对是我想要的。
    猜你喜欢
    • 2012-06-11
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 2017-08-01
    • 2021-06-18
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    相关资源
    最近更新 更多