Formatting JSON object as string.


Just a little trick… when you need to format a JSON object for displaying it you might use JSON.stringify and there is a third argument that is the space. If you write JSON.stringify(obj, null, ‘\t’) if prints each element preceded by a tabulator.

The space might also be a number and then the text is indented with the specified number of white spaces at each level.

Example:

var obj = {
    field1: 123.5,
    field2: true,
    field3: "Hello, OnaBai!",
    field4: [ "Working", "in", "a", "cloud", "of", "documents" ],
    field5: {
        field51: "I'm nested"
    },
    field6: function() {
        alert("Hello, OnaBai");
    }
};
console.log(JSON.stringify(obj, null, 2));

Shows:

{
  "field1": 123.5,
  "field2": true,
  "field3": "Hello, OnaBai!",
  "field4": [
    "Working",
    "in",
    "a",
    "cloud",
    "of",
    "documents"
  ],
  "field5": {
    "field51": "I'm nested"
  }
} 

NOTE: As you can see functions are not displayed!!!

More information here and here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s