How do I parse a JSON response for validation or to extract a value?

Document created by DPM Admin Employee on Jul 21, 2017
Version 1Show Document
  • View in full screen mode

You will need to write a Script that plays after your message and extracts the value.

 

Step 1

Insert a Script following the Message whose response you wish to validate or extract a value from.

 

Step 2

Ensure that the Script doesn't play until the Message has completed.

If you are using a Sequenced Test Clip, this will always be the case and there is nothing special to do.

If you are using a Timed Test Clip, then you must either put the Message and the Script together into a Chain or put a Checkpoint between the Message and the Script. You could also insert a Delay between the Message and Script that you know will always be long enough, but this may not be consistently reliable if the response times to your Message vary.

Note that your Script could also put the extracted value into a property, insert it into another message, or do anything with that value that a Script can do.

 

Step 3

Your script should be something like the following:

// This Script looks at the response to the Message that
// precedes it (it assumes that a Message precedes it).
// The response is assumed to be JSON containing an
// array of values, in a form such as the following:
//   {"ResultSet":{"Result":"lincoln"}}
// It extracts all of the values from the array and logs
// them in the Result.

// Get the Message that immediately precedes this
// Script.
var msg = $context.currentItem.previousItem;

// Extract the array from the JSON response. Note
// that for XPath purposes, the JSON is always
// considered to have a "JSON" node at the root.
var matches = msg.getResponse
  (msg.RESPONSE_HTTP_BODY_AS_JSON,
  "/JSON/ResultSet/Result");

// Was the array found in the response?
if (matches == null)
{
  // The array was not found in the response.
  // Abort the Test Composition with an error.
  $context.composition.abort("Response for
          " + msg.name + ": Result array not found.");
}
else
{
  // The array was found. Format the array
  // value nicely, andthen post an entry to
  // the Result with the value.
  var details = "";
  for (var i = 0; i < matches.length; i++)
  {
    details += "Match " + i + ": " + matches[i] + "\n";
  }
  $context.result.postMessage($context.result.LEVEL_INFO,
    "Extracted value from JSON response for
          " + msg.name, details);
}

 

Here is an example of the Script following the Message in a Chain:

Attachments

    Outcomes