Explain Codes LogoExplain Codes Logo

Print JSON parsed object?

javascript
debugging-strategies
console-abilities
json-stringify
Alex KataevbyAlex Kataev·Dec 11, 2024
TLDR

To display a formatted JSON object, utilize JSON.stringify(obj, null, spaces).

Here's the fast track:

console.log(JSON.stringify({ a: 1, b: true, c: ['x', 'y'] }, null, 4));

This tags the object with 4-space indentation, delivering a structured view for easier inspection.

Debugging strategies

When examining parsed JSON objects, using the right tools is crucial.

Exploit console abilities

  • console.dir(obj) offers an interactive view of object's properties
  • Combining console.log() with JSON.stringify() helps visualize the object in text form
  • The replacer parameter can be used in JSON.stringify(obj, replacer, spaces) to cleverly filter or transform the properties you're interested in.

Easy-see with Stringify

Consider a complex object with many levels. Creating a neat picture becomes easy with a sprinkle of JSON.stringify().

let nestedObj = { a: 1, b: { c: 3, d: { e: 5 } } }; // Anybody else think nesting is a full-contact sport? console.log(JSON.stringify(nestedObj, null, 2));

2-space indentation here transforms the deep structure into a readable novel.

Caution: 'for...in' loops

for...in loops on JSON objects are like stepping on a landmine - unexpected output if the object's prototype chain has enumerable properties. Play safe with Object.keys() or Object.values() for iterating over properties.

Advanced JSON navigation

At times, parsed JSON objects could be a forest. Here are a few tricks to not lose your way.

Mark checkpoints

Make clever use of debugger tools, breakpoints, and console.log for a breadcrumb trail:

// You shall not pass... without logging! console.log('Checkpoint: ', JSON.stringify(checkpointData, null, 2));

Keep visual cues

Use emojis or simple graphics as symbols for quick information access.

Using 'replacer' for detailed focus

Rather than looking at the entire forest, sometimes you just want to look at one type of tree. The replacer function has got you covered:

function replacer(key, value) { // Ignoring all string-valued props if (typeof value === 'string') { return undefined; } return value; } // Not all treasure's silver and gold, mate. console.log(JSON.stringify(objectTreasure, replacer, 2));

Object mysteries: Unwrapped

Excavating every corner of your objects

Comparing with console.table

console.table() lays out objects for comparison:

// One man's "items in a list" is another man's organized tool riot. console.table([{ a: 1, b: 'Y' }, { a: 2, b: 'Z' }]);

Handling large objects

Massive objects can bust the console limits. Utilize browser-based inspection tools or Node.js's util.inspect for manageable scrollable views.

JSON: A multi-environment hero

Meet JSON: The undercover hero in browsers, the brave knight in Node.js and the crown jewel in database systems like MongoDB.