Skip to content

Benejson js couchdb example

codehero edited this page Feb 21, 2011 · 1 revision

The following code will parse a CouchDB view response.

    /* The root object of the response is a map, so our parser will also be a map at the root. */
    var couchViewParser = {
/* Force distinct callback for beginning of map. */
"{":function(key){
      /* Note, key will be null since we are at the root! */
      sys.puts("Begin parsing response");
},

/* The "*" string indicates that its associated context will be used for all
     * keys that are not specifically matched by another rule. The parser accumulates all non matched values
     * in an object buffer until it reaches the end of a map or a special key.
     * At this point, if at least one accumulated value exists, then all those values are pushed to "*".
     * CouchDB view responses include summary information, which will be pushed to this cb.
 * In this we have an expectation of the couchdb view format, we know
 * that the "rows" key will be last. */
"*":function(data){
	sys.puts("Total Rows: " + data.total_rows);
	sys.puts("Offset : " + data.offset);
},

/* The '.' character is a prefix to single out a key for special processing.
 * In this case, just match key "rows". CouchDB will return an array at this key.
     * Likewise, we will specify an array context.
 *
 * -When specifying an array context:
 *  The first element is the callback when the array starts (before 0th elem).
 *  The second element is the context for each element in the array
 *  The third callback is for the array end. */
".rows":[
	function(){
		sys.puts("Starting Rows:");
	},
	function(row){
		sys.puts(row);
	},
	function(){
		sys.puts("Ended Rows.");
	}
],

/* Specify callback for end of response. */
"}":function(){
      sys.puts("Parsed view response.");
}
    };
Clone this wiki locally