Click here to Skip to main content
12,763,299 members (38,105 online)
Click here to Skip to main content
Add your own
alternative version


3 bookmarked
Posted 11 Jul 2014

Use trimming during Object to JSON string serialization in JavaScript

, 11 Jul 2014 CPOL
Rate this:
Please Sign up or sign in to vote.


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 really Bearden, when we have to consider all input fields.


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

/*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.

/*object with trimed string types, which we realy 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 fields 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 user. Even here we have to bind every field with the custom value binder.

3. or the solution which I am demonstrating here.


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

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 quick preview check out, json2.extension.js

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

   function dump(json) {

    var json = null;

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

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

    /*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);

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

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

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


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


About the Author

Bangladesh Bangladesh
No Biography provided

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170217.1 | Last Updated 11 Jul 2014
Article Copyright 2014 by DiponRoy
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid