A simple way to serialize a JSON object is to iterate through the object’s property and create a JSON formatted string. All the properties and functions in a JSON object can be read just like an associative array or a name/value pair. This allows us to list all the keys and query the object for the values using the keys. Look at the following script:
var myJSON = {
FirstName: '',
LastName: '',
Email: '',
load: function () {
},
serialize: function () {
var json = "";
for (var key in this) {
if (typeof this[key] != 'function') {
json += (json != "" ? "," : "") + key + ":'" + this[key] + "'";
}
}
json = '[{' + json + '}]';
return json;
}
}
The serialize
function uses a for
loop to get all the keys in the object. It checks if the type is not a function because, for this case, we just want to extract the user data values and ignore the functions. You could also extract the contents of the function by just removing the if
condition. To build the formatted string
, the function concatenates a string
with the key/value pair until it reads all the keys. The following sample script sets the property values and serializes the data to a string
:
if (typeof (myJSON) != 'undefined') {
myJSON.FirstName = "myfirstname";
myJSON.LastName = "mylastname";
myJSON.Email = "myemail";
var data = myJSON.serialize();
}
The data variable contains a string
with this format:
[{FirstName:’myfristname’,LastName:’mylastname’,Email:’myemail’}]
I hope this helps.