JSON Parameter String Builder
Overview
In continuing my love affair with code generation or using code to create code, we will be creating a small jQuery based utility for creating JSON parameter strings that can be used as parameter strings to page/web methods when making Ajax calls with jQuery. While creating these strings is mostly a trivial task, the formatting that is required between parameter names and values could be error prone when build manually due to the mixing of double quotes, single quotes and the concantenation of parameter names and values. The utility we will be creating will accept two comma delimited strings, one containing parameter names and the other their matching values, combine them and output these together in JSON data parameter format.
The User Interface
The UI for this utility is rather simple. I have added some styling to make things look "nice-a-little", but you may chose to style things to fit your needs. The UI consists of
- a fieldset
- a table
- two label elements
- two text boxes
- a button
- a div element where the output will be shown
I have used the following markup to create the UI for the utility:
<fieldset style="margin: 10px; padding: 10px;"> <legend> <div style="padding: 2px; border: 1px solid silver; background-color: #F1F1F1; font-weight: bold;"> JSON Parameter Format Builder </div> </legend> <div style="margin-top: 6px;"> <table cellpadding="2" cellspacing="0" border="0" style="border: none;"> <tr> <td> <label for="parameterNamesField" style="display: block;"> Parameter Names (P1,P2,P3): </label> </td> <td> <input type="text" id="parameterNamesField" /> </td> </tr> <tr> <td> <label for="parameterValuesField" style="display: block;"> Parameter Values (V1,V2,V3): </label> </td> <td> <input type="text" id="parameterValuesField" style="display: block;" /> </td> </tr> <tr> <td colspan="2"> <input type="button" id="getParameterFormat" value="Get Format" /> </td> </tr> <tr> <td colspan="2"> <div id="parameterFormatValue" style="width: 500px; height: 40px; margin: 2px; padding: 5px; border: 1px solid silver; background-color: #F1F1F1; overflow: auto;" /> </td> </tr> </table> </div> </fieldset>
Once the UI has been created, we can move to the implementation details
The Implementation
The implementation of our utility is very simple because it is 100% coded with JavaScript using jQuery. In order for the utility to work correctly, it will need to do the following:
- Determine whether both, the parameter names string and parameter values string contain the same number of elements when split by their delimiter; in this case a comma character.
- Fetch the value of the parameter names field.
- Fetch the value of the parameter values field.
- If both strings do not contain the same number of elements when split into arrays, the user should be alerted of the input error
- If both strings contain the same number of elements when split into arrays, then begin formatting the return string value by attaching required characters by the JSON parameter string syntax and attach parameter to value by way of a looping control structure.
- Return the string
The following JavaScript code implements our requirements:
$(document).ready(function() {
// Returns a parameter string in json format
function retrieveParamFormat(paramNames, paramValues) {
var format = "";
var lengthsMatch = paramNames.split(",").length == paramValues.split(",").length;
if (lengthsMatch) {
var names = paramNames.split(",");
var values = paramValues.split(",");
// Prefix parameter string
format = "{";
// Build parameter string
for (var i = 0; i < names.length; i++) {
format += "'" + names[i] + "':'" + values[i] + "'";
if (i < (names.length - 1)) {
format += ",";
}
}
// Close parameter format
format = format + "}"
}else{
format = 'Parameter vs. Value mismatch';
}
return format;
}
// Retrieves a json formatted parameter string
$('#getParameterFormat').click(function() {
var paramNames = $('#parameterNamesField').val();
var paramValues = $('#parameterValuesField').val();
if ((paramNames == '') || (paramValues == ''))
alert('Parameter Names and Parameter Values are required');
else
$('#parameterFormatValue').html(retrieveParamFormat(paramNames, paramValues));
});
});
Demo
Use Case
Now that we have a function that will create JSON parameter strings for us all we have to do is utilize its output with an actual Ajax call to a web service. The following is a sample of how this can be achieved:
var serviceUrl = 'http://www.someservicehost.com/someservice.asmx/somemethod';
// Get parameter format
var format = retrieveParamFormat('name,age,address', 'Ramon E. Tristani,39,some address in the beautiful state of WA');
// Execute Ajax call
$.ajax({
type: 'POST',
url: serviceUrl,
data: format,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(result) {
$('#<%= pageMethodNameGreetingField.ClientID %>').val(result.d);
},
error: function() {
alert('An error occurred while accessing the the following web service:\n'
+ serviceUrl);
}
});
In the aove sample I have provided hard-coded strings. In a real life situation however, these values should come from data input elements within the HTML document
Conclusion
In this article we have created a simple utility to automate the creation of data parameter strings used in Ajax calls. Having quick utility functions like these that handle repetitive tasks is important as it will reduce the amount of debugging and application showstopping points, while increasing application maintainability.
Get the source code for this article.







