-
Notifications
You must be signed in to change notification settings - Fork 14
Server Side JsonPath example
edwardcapriolo edited this page Jan 22, 2013
·
1 revision
IntraVert does not have any specific JSON verbs at this point however the Processing and Filtering system already make server side processing possible.
Imagine we have a JSON array of data as a string:
String array = "[{\"value\": 1},{\"value\": 2}, {\"value\": 3},{\"value\": 4}]";
Our goal is to run a JSONPath query $.[1].value
on the data. The example will use a post-processor to process the slice results.
IntraReq req = new IntraReq();
req.add( Operations.setKeyspaceOp("myks") ); //0
req.add( Operations.setColumnFamilyOp("mycf") ); //1
req.add( Operations.setAutotimestampOp() ); //2
req.add( Operations.assumeOp("myks", "mycf", "value", "UTF-8")); //3
req.add( Operations.assumeOp("myks", "mycf", "column", "UTF-8")); //4
Map row1 = new HashMap();
row1.put("rowkey", "jsonkey");
row1.put("name", "data");
row1.put("value", array);
List<Map> rows = new ArrayList<Map>();
rows.add(row1);
req.add( Operations.batchSetOp(rows));//5
req.add( Operations.sliceOp("jsonkey", "a", "z", 100));//6
We will create a processor named JsonPathEx. JsonPath included with intravert but it would be just as easy to have groovy @GRAB the required libraries.
req.add( Operations.createProcessorOp("JsonPathEx", "groovy",
"import com.jayway.jsonpath.*; \n" +
"public class JsonPathEx implements org.usergrid.vx.experimental.Processor { \n"+
" public List<Map> process(List<Map> input){" +
" List<Map> results = new ArrayList<HashMap>();"+
" for (Map row: input){" +
" Map newRow = new HashMap(); "+
// grovvy requires you to escape ?
" Integer match = JsonPath.read(row.get(\"value\").toString(), \"\\$.[1].value\"); \n"+
" newRow.put(\"value\",match.toString()); \n "+
" results.add(newRow); \n"+
" } \n" +
" return results;"+
" }"+
"}\n"
));//7
req.add( Operations.processOp("JsonPathEx", Collections.EMPTY_MAP, 6));//8
IntraRes res = new IntraRes();
is.handleIntraReq(req, res, x);
In the slice operation we see that the entire json array is retuned.
List<Map> x = (List<Map>) res.getOpsRes().get(6);
Assert.assertEquals(1, x.size());
Assert.assertEquals("data", x.get(0).get("name"));
Assert.assertEquals(array, x.get(0).get("value"));
Our processor returned the value of our JsonPath query.
List<Map> y = (List<Map>) res.getOpsRes().get(8);
Assert.assertEquals(1, y.size());
Assert.assertEquals("2", y.get(0).get("value") );