Sidebar

How to access all values for a query string parameter that is repeated?

0 votes
54 views
asked May 1 by rich-c-2789 (17,430 points)
I have an HTTP Listener and I recieve requests that look like this:

http://host/location?facility=south&specialty=Nephrology&specialty=Neurology&specialty=Psychiatry

How can I get all the specialty values?

1 Answer

0 votes

Save this function as a published function:

function getQueryParameterValues(urlQuery,parameterKey) {

  // Validate: return an empty array when the URL query or parameterKey are empty 
  if (StringUtils.isEmpty(urlQuery)) {
    return [];
  }
  if (StringUtils.isEmpty(parameterKey)) {
    return [];
  }

  var parameterValues = [];
  try {
    //Split out the query string portion if we got a complete URL 
    var urlParts = StringUtils.splitByWholeSeparator(urlQuery, "?");

    // If no "?", treat the entire string as the queryParameters.
    var queryParams = urlParts.length > 1 ? urlParts[1] : urlParts[0];

    //Split into key value pairs
    var keyPairs = StringUtils.splitByWholeSeparator(queryParams, "&");

    // Cycle through key-value pairs, collecting all values for the parameter
    for (var i = 0; i < keyPairs.length; i++) {
      var keyValueParts = StringUtils.splitByWholeSeparator(keyPairs[i], "=");

      if (keyValueParts.length == 2 && StringUtils.equalsIgnoreCase(keyValueParts[0], parameterKey)) {
        parameterValues.push(String(qie.urlDecode(keyValueParts[1])));
      }
    }
  } catch (err) {
    throw "Failed to getQueryParameterValues: " + err;
  }

  return parameterValues;
}

This function helps you extract all values associated with a specific key from a URL query string. Here's how it works:

Inputs:

  • urlQuery: This is the query string containing the query portion of a URL, typically everything after the ? symbol.
  • parameterKey: This is the specific key you want to extract values for (e.g., "facility", "specialty").

Output:

The function returns an array containing all the values associated with the provided parameterKey. If the key is not found or the URL query is invalid, it returns an empty array.

Example Usage:

var queryString = source.getNode('/Request/QueryString');

//When parameter only has one value
var names = getQueryParameterValues(queryString, "facility");
qie.info("Facility: " + names[0]);

//When parameter has more than one value
var aliases = getQueryParameterValues(queryString, "specialty");
for (var i = 0; i < aliases.length; i++) {
   qie.info("Specialty " + (i + 1) + ": " + aliases[i]);
}

This example retrieves all values for the key "specialty" from the given URL and prints them to the console.

Results:

Facility: south
Specialty1: Nephrology
Specialty2: Neurology
Specialty3: Psychiatry

 

See also:

Handling HTTP requests and responses

Processing Requests in mapping nodes via HTTP Listener source node

 

 

answered May 1 by rich-c-2789 (17,430 points)
edited May 16 by rich-c-2789
...