» » » How to stringify an object in Javascript: converting an object to a padded & well-formatted string or simply inline

How to stringify an object in Javascript: converting an object to a padded & well-formatted string or simply inline

I wrote a function to convert an object in a string (stringification) without using a JSON library; you can convert an object to a well formatted string with padding or simply to an unique line:

function stringify(object, padding, margin){
	var o = (typeof object == 'object' || typeof object == 'function') && object != null ? object : null;
	var p = typeof padding == 'boolean' && padding ? true : false;
	var m = typeof margin == 'number' && margin>0 && p ? margin : 0;
	if(o != null){
		var s = '';
		var a = function(o){return (typeof o === 'object' && o ? ((typeof o.length === 'number' &&!(o.propertyIsEnumerable('length')) && typeof o.splice === 'function') ? true : false) : false);}; //is array?
		for(var v in o){
			s += typeof o[v] === 'object' ? (o[v] ? (
					(typeof o[v].length === 'number' && !(o[v].propertyIsEnumerable('length')) && typeof o[v].splice === 'function') ?
					(m>0 ? Array(m).join(' '):'') + v + ':' + (p ? ' ':'') + '[' + (p ? 'rn':'') + stringify(o[v],p,(m>0?m:1)+v.length+4) + (p!=true ? '' : 'rn' + Array((m>0?m:1)+v.length+2).join(' ')) + '],' + (p ? 'rn':'') :
					(m>0 ? Array(m).join(' '):'') + v + ':' + (p ? ' ':'') + '{' + (p ? 'rn':'') + stringify(o[v],p,(m>0?m:1)+v.length+4) + (p!=true ? '' : 'rn' + Array((m>0?m:1)+v.length+2).join(' ')) + '},' + (p ? 'rn':'')
				) : (m>0 ? Array(m).join(' '):'') + v + ':' + (p ? ' ':'') + o[v] + ',' + (p ? 'rn':''))
			: (m>0 ? Array(m).join(' '):'') + v + ':' + (p ? ' ':'') + (typeof o[v] == 'string' ? ''' + o[v].replace(/'/g,'\'') + ''' : o[v]) + ',' + (p ? 'rn':'');
		};
		o = s.length>0 && p!=true ? s.substring(0, s.length-1) : (s.length>2 ? s.substring(0, s.length-3) : s);
	}else{
		o = object;
	};
	return o;
};

a little example, you declare same variable….

var associative_array = new Array();
associative_array['one'] = 1;
associative_array['two'] = 2;
associative_array['undefinedvar'];

var myobject = {
					mystring: 'value',
					myquoted: 'string with 'single quotation mark'',
					mynumber: 1,
					myboolean: true,
					myarray: [1, 2, 3],
					myassocarray: associative_array,
					myobject: {
								obj_string: 'hi!',
								obj_number: 1,
								obj_array: [
												'just', 'a', 'test', 1, false, 
												['array', 'inside', 'array'],
												{
													object: 'inside array',
													array: [1,2,3,4,5,6,7,8,9]
												},
												
											]
								},
					mynullvalue: null,
					myundefined: associative_array['undefinedvar'],
					myfunction: function(){ var s = 'hello!'; return s; }					
				};

then, for an inline stringification, you can use

var str = stringify(myobject);

and “str” value will be a string as

mystring:'value',myquoted:'string with 'single quotation mark'',mynumber:1,myboolean:true,myarray:[0:1,1:2,2:3],myassocarray:[one:1,two:2],myobject:{obj_string:'hi!',obj_number:1,obj_array:[0:'just',1:'a',2:'test',3:1,4:false,5:[0:'array',1:'inside',2:'array'],6:{object:'inside array',array:[0:1,1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9]}]},mynullvalue:null,myundefined:undefined,myfunction:function () {
    var s = "hello!";
    return s;
}

Instead, for a stringification with a well formatted padding, you can use

var str_formatted = stringify(myobject, true);

and this is the “str_formatted” value:

mystring: 'value',
myquoted: 'string with 'single quotation mark'',
mynumber: 1,
myboolean: true,
myarray: [
           0: 1,
           1: 2,
           2: 3
         ],
myassocarray: [
                one: 1,
                two: 2
              ],
myobject: {
            obj_string: 'hi!',
            obj_number: 1,
            obj_array: [
                         0: 'just',
                         1: 'a',
                         2: 'test',
                         3: 1,
                         4: false,
                         5: [
                              0: 'array',
                              1: 'inside',
                              2: 'array'
                            ],
                         6: {
                              object: 'inside array',
                              array: [
                                       0: 1,
                                       1: 2,
                                       2: 3,
                                       3: 4,
                                       4: 5,
                                       5: 6,
                                       6: 7,
                                       7: 8,
                                       8: 9
                                     ]
                            }
                       ]
          },
mynullvalue: null,
myundefined: undefined,
myfunction: function () {
    var s = "hello!";
    return s;
}

Finally, when you pass a variable to stringify() that is not an object, it will just return the value.

Happy stringifications!

Max 🙂

Leave a Reply