2012-01-08 2 views
2

webclient 모듈을 사용하여 couchDB 나머지 인터페이스를 쿼리하려고합니다. 특정 수의 문서를 가져와야하므로 opa couchdb api 대신 사용하고 있습니다.OPA에서 웹 클라이언트를 파싱합니다. 결과물

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)를 사용하려고했지만 거기에서 어디로 가야할지 확실하지 않았습니다. - 그것은 단순히 문자열을 받아 JSON 사양에 따라 JSON의 AST를 생산 Json.deserialize를 사용하는의 하나의 첫 번째

1 :

답변

3

당신은 몇 가지 접근 방식을 오파 두 때 unserialize JSON 문자열을 가질 수 있습니다. 그러면 생성 된 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 deserilization을 사용하는 것입니다. 우선 기대 값에 해당하는 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 
+1

감사합니다. "마법"opa 직렬화 방식이 확실히 내가 찾고 있었던 것입니다. – jeant

관련 문제