8

How to output an object as a readable string with formatting (structured like with <pre>) ?

No jQuery possible.

My object looks like this using console.log.

Object
   title: "Another sting"
   type: "tree"
   options: Object
      paging: "20"
      structuretype: "1"
   columns: Object
      ...
   description: "This is a string"
   ...

What is the best to convert it to a structured string?

My attempt:

I tried using stringify() to get the JSON structure. I could then write my own parser, but maybe there are already any implementations?

2
  • Do you mind using a framework? api.jquery.com/jQuery.parseJSON Commented Oct 18, 2012 at 8:38
  • 2
    @CharliePrynn He said, no jQuery possible. Commented Oct 18, 2012 at 8:38

2 Answers 2

18

JSON.stringify includes a formatting argument:

JSON.stringify(value[, replacer [, space]])

The space argument may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10). If it is a string, successive levels will indented by this string (or the first ten characters of it).

Using a tab character mimics standard pretty-print appearance

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify

Is that enough formatting for what you need? E.g. try:

 JSON.stringify( object, null, 2 );

Otherwise, http://code.google.com/p/google-code-prettify/ is a standalone JSON to HTML pretty printer. Used by stackoverflow and google code, I believe.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the solution, I did not know about the space parameter. Indeed I can use this combined with removing unwanted characters {, } and ".
0

In the meantime I came up with this function, maybe someone can use it:

addIndent: function(nSpaces) {
         var strOutput = '';
         for(var i = 0; i < nSpaces; i++) {
            strOutput += '--';
         }
         return strOutput; 
      }

parseObjToStr: function(oObject, nLevel) {
         var that = this;
         var strOutput = '';
         nLevel = nLevel || 0;

         for(var oEl in oObject) {
            if(typeof oObject[oEl] === 'object' || Object.prototype.toString.call( oObject[oEl] ) === '[object Array]') 
            {
               strOutput += that.addIndent(nLevel) + oEl + "<br />";
               strOutput += that.parseObjToStr( oObject[oEl], nLevel+1);
            } 
            else 
            {
               strOutput += that.addIndent(nLevel) + oEl + " = " + oObject[oEl] + "<br />";
            }
         }
         return strOutput;
      }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.