Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Use Trimming During Object to JSON String Serialization in JavaScript

5.00/5 (3 votes)
11 Jul 2014CPOL1 min read 26.8K   58  
How to use trimming during object to JSON string serialization in JavaScript

Introduction

Removing unnecessary white spaces at the start and end of the string types (trimming) is quite important when we want to save or update user input values. But managing this trimming becomes a big burden, when we have to consider all input fields.

Background

Let’s say we have an object collected using input fields from user which we wanted to post to the server. But the problem is that it contains unnecessary white spaces at the start and end of the string types.

JavaScript
/*object which we want to post to server*/
var postObject = {
    firstName: '    Dipon    ',
    lastName: '   Roy   ',
    age: ' 24 ',   
    department: { name: ' CSE ', code: ' CSE '},
    subjects: [
        { name: ' CSE-100 ', marks: 10 },
        { name: ' CSE-100 ', marks: 10 },
        { name: ' CSE-100 ', marks: 10 }
    ]
};

Now it is what we desire to be, before we post it to server.

JavaScript
/*object with trimmed string types, which we really want to post to server*/
var postObject = {
    firstName: 'Dipon',
    lastName: 'Roy',
    age: '24',   
    department: { name: 'CSE', code: 'CSE'},
    subjects: [
        { name: 'CSE-100', marks: 10 },
        { name: 'CSE-100', marks: 10 },
        { name: 'CSE-100', marks: 10 }
    ]
};

What We Can Use?

  1. jquery.js - $.trim() which will trim the string type, but the problem is we have to use it for each input field when we collect the data.
  2. knockout.js - if we know how to use knockout, we can use Trimmed Value Binding in knockout.js for model binding. This trims the value and even shows it to the user. Even here, we have to bind every field with the custom value binder.
  3. or the solution which I am demonstrating here.

json2.extension.js

json2 is a popular and simple to use json serializer, and I have been using it for a couple of months. When I was exploring the lib to solve my problem, I found out that it is not just about only the JSON.stringify() and JSON.parse():

JavaScript
JSON.stringify(value, replacer, space)
    value       any JavaScript value, usually an object or array.
    replacer    an optional parameter that determines how object
                values are stringified for objects. It can be a
                function or an array of strings.
    space       an optional parameter that specifies the indentation
                of nested structures. If it is omitted, the text will
                be packed without extra whitespace. If it is a number,
                it will specify the number of spaces to indent at each
                level. If it is a string (such as '\t' or ' '),
                it contains the characters used to indent at each level.

JSON.parse(text, reviver)
    This method parses a JSON text to produce an object or array.
    It can throw a SyntaxError exception.

    The optional reviver parameter is a function that can filter and
    transform the results. It receives each of the keys and values,
    and its return value is used instead of the original value.
    If it returns what it received, then the structure is not modified.
    If it returns undefined then the member is deleted.

So I made an extension for it, which would help us in many ways. For a quick preview, please check out json2.extension.js.

JavaScript
JSON.extn = {

    format: '\t',

    replacer: function (key, value) {
        function trim(text) {
            var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
            text = (text == null)
                        ? ""
                        : (text + "").replace(rtrim, "");
            return text;
        }
        return typeof this[key] === "string" ? trim(value) : value;
    },  

    parse: function (string, replacer) {
        return JSON.parse(string, replacer);
    },

    stringify: function (obj, replacer, space) {
        return JSON.stringify(obj, replacer, space);
    }, 
              
    formatedStringify: function (obj) {
        return this.stringify(obj, {}, this.format);
    },

    trimedStringify: function (obj) {
        return this.stringify(obj, this.replacer);
    }, 

    trimedAndFormatedStringify: function (obj) {
        return this.stringify(obj, this.replacer, this.format);
    },

    trimedObject: function (obj) {
        var json = this.stringify(obj, this.replacer);
        return this.parse(json, {});
    },   
}

Using the Code

JavaScript
function dump(json) {
     alert(json);
 }

 var json = null;

 /*stringify the object as it exactly is*/
 json = JSON.extn.stringify(postObject);
 dump(json);

 /*trims the string type properties*/
 json = JSON.extn.trimedStringify(postObject);
 dump(json);

 /*stringify the object as it exactly is,
 But adds extra '\t' to string and the string looks like the JavaScript object*/
 json = JSON.extn.formatedStringify(postObject);
 dump(json);

 /*trims the string types and adds format*/
 json = JSON.extn.trimedAndFormatedStringify(postObject);
 dump(json);

 /*parse json string to JavaScript object*/
 json = JSON.extn.parse(json);
 dump(json);

 /*trims the strings types but returns JavaScript object rather than string*/
 json = JSON.extn.trimedObject(postObject);
 dump(json);

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)