问题
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