parsing a webclient.Result content in OPA

核能气质少年 提交于 2019-12-13 12:37:01

问题


I am trying to use the webclient module to query the couchDB rest interface (I am using it instead of the opa couchdb api because I need to get a specific number of documents).

Here is the code used to make the query:

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

the result given in s.content is the following string:

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

I was wondering what would be the best approach to parse this string to get for example the list of ids, or only the rows field? I tried to use Json.deserialize(s.content) but not sure where to go from there.


回答1:


You can have several approach two unserialize Json strings in Opa:

1 - The first of one it's to use simply Json.deserialize that takes a string and produces a Json AST in accordance to Json specification. Then you can match the produced AST to retreive the informations you want.

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 - Another approach it's to use the "magic" opa deserilization from Json. First of all define the Opa type corresponding to the expected value. Then use OpaSerialize.* function. According to your example

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


来源:https://stackoverflow.com/questions/8776647/parsing-a-webclient-result-content-in-opa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!