Saturday, November 2, 2013

JSON message processing in performance test

We all know that JSON as a message format has become more popular, databases such MongoDB, CouchDB support it, so do many web services. So it's not a surprise that performance test tools need to deal with it. However, it's not easy to process JSON messages on many existing test platforms, in some cases, users are desperate enough to use regular expressions!

Here we are going to show how easy it is to process json messages innetgend javascript, even for user with modest coding background. For those who have read previous blogs which touched on the subject of processing JSON messages, this blog is a continuation and it will cover some more examples on how to use netgend javascript to process JSON messages in performance testing.

Before diving into the examples, the author would like to thank the sites where examples/questions were taken from. Readers of this blog are encouraged to read more at those sites and try to solve questions/challenges raised there.

Example 1

This example is based on a stackoverflow question: given a JSON string like the following, find the id's whose value is not null.

Note that function "fromJson" parses the JSON string and assign to variable "a", "a" will contain an array of json objects, each containing "id", "value" and "description" fields. The variable "a[id].value" means the "value" field of id'th item of the array "a". Finally, as a reminder, all the variables here are local to the VUser.

Example 2

Based on another stackoverflow question (there have lots of questions, don't they?): given a JSON string like the following, print all id's of the rows whose type is "B".

The JSON structure is a little more complex, so are the compound variables like "resp.applications[0].api_key". However, it should be very easy to map the structure of the variable to the fields in JSON string.

resp = fromJson(http.replyBody);
//now you can access fields in the json string.
//In the following expressions, "application" is an array of two item, first item has index 0
resp.applications[0].api_key
//The above will have value "blted0e7982e1cf62a8"
resp.applications[1].name
//the above will have value "cellapp"

Example 4

Again based on an example in stockoverflow. The JSON string in this example is long and complex. Here we need to find the names of two nodes after "CURRENT", in our case, we need to find "36735928", "37851136".

Despite the long JSON string, the solution is quite short and easy to understand.

//assume variable "jsonstr"contains the complex json string in the question
a = fromJson(jsonstr);
b = keys(a.payload.reservationLists.CURRENT);
//now b[0] will contain first node name ("36735928" in this case)
//and b[1] will contain second node name ("37851136" in this case)

Example 5.

Finally an example JSON from Alex Ersenie's blog, we need to print all the child categoryId's.