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 仕様に従って Json AST を生成する単純な Json.deserialize を使用する最初のもの。次に、生成された 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 - もう 1 つのアプローチは、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 に答える