我正在尝试使用 webclient 模块来查询 couchDB Rest 接口(interface)(我使用它而不是 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) 但不知道从哪里开始。
最佳答案
您可以在 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
关于couchdb - 解析 OPA 中的 webclient.Result 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8776647/