JSON (JavaScript Object Notation) has rapidly become universal as a lightweight data interchange format1. Though ostensibly a subset of JavaScript, it is language-independent and supported by nearly all modern programming languages. Itssuccinctness, human readability and built-in JavaScript compatibility has led to widespread adoption. When working with JSON in JavaScript, it is extremely common to print JSON objects to the console for debugging, analyzing API responses, and other development tasks.

Fortunately, JavaScript provides an elegant utility for handling these needs – the JSON.stringify() method. In this comprehensive guide, we‘ll cover how to use JSON.stringify() to effortlessly print string representations of JSON objects.

JSON Usage and Adoption

Let‘s briefly examine why printing JSON in development workflows is so ubiquitous. According to recent surveys2:

  • JSON is used in approximately 70% of web applications
  • Over 96% of web services and APIs employ JSON for data exchange
  • JSON usage has increased 100% from 2016 to 2022
  • All mainstream programming platforms include JSON libraries

With JavaScript itself being used for over 97% of websites3, it dominates as the language of the web. And since JSON originated from JavaScript, they have a natural symbiosis.

Many popular web APIs like REST use JSON for request and response payloads due to its lightweight nature. Single page applications using frameworks like React and Vue also rely heavily on passing JSON data around.

So any JavaScript developer working on web apps requires robust JSON manipulation abilities, including printing.

Using JSON.stringify() for Printing Objects

JavaScript provides the JSON object with essential utility methods for parsing, stringifying and manipulating JSON data. At its core is:

JSON.stringify(value, replacer, space)

This method converts a JavaScript value into a JSON string representation. The key parameters:

  • value – The value to convert, usually an object or array
  • replacer – Function to customize object to JSON conversion
  • space – Formatting space to display objects spaced and indented

For printing purposes, we are mostly concerned with the space parameter. By passing an integer here, it inserts that number of space characters for formatting JSON string representations.

Printing a Basic Object

Consider this simple object:

const person = {
  name: "John",
  age: 30,  
  city: "New York" 
};

To print a stringified version, pass null to use default conversion, and a space integer, like 2:

console.log(JSON.stringify(person, null, 2));  

This prints:

{
  "name": "John",
  "age": 30,
  "city": "New York" 
}

The indentation allows much easier visual scanning than a condensed string. Many developers pretty print all API responses this way during development.

Let‘s examine more examples of printing other JSON object types.

Printing Nested Objects

JSON allows arbitrary levels of nesting, which stringifying handles seamlessly:

const employee = {
  name: "Mary", 
  address: {
    line1: "123 Main St",
    city: "Anytown",
    state: "CA"
  }
};

console.log(JSON.stringify(employee, null, 2));

Print nested employee:

{
  "name": "Mary",
  "address": {
    "line1": "123 Main St", 
    "city": "Anytown",
    "state": "CA"
  }
}

The indentation matches the logical object structure.

Printing Arrays of Objects

JSON is often used for arrays of objects:

const employees = [
  {
    name: "John",
    title: "Manager"
  },
  {
    name: "Sara",
    title: "Engineer"
  } 
];  

console.log(JSON.stringify(employees, null, 2)); 

This array stringifies nicely:

[ 
  {
    "name": "John",
    "title": "Manager"
  },
  {
    "name": "Sara",
    "title": "Engineer"
  }
]

So JSON.stringify works great for arrays with automatic indentation.

Customizing Property Stringification

The second replacer argument permits customized control over property conversion. For example, we may want to exclude sensitive fields from being printed:

const user = {
  username: "jdoe",
  password: "abcd1234", // sensitive
  email: "jdoe@example.com" 
};

console.log(JSON.stringify(user, [‘password‘], 2));

This excludes printing the password:

{
  "username": "jdoe",
  "email": "jdoe@example.com"
}

We can also pass a replacer function to programmatically filter fields:

function replacer(key, value) {
  if (key === ‘password‘) {
    return undefined;
  }
  return value;
}

console.log(JSON.stringify(user, replacer, 2));  

This custom function excludes any password property dynamically.

So the replacer argument is great for redacting sensitive fields.

Why Printing Differs from Parsing

Developers often confuse printing JavaScript objects as JSON with parsing JSON strings. But they have different use cases:

JSON.stringify – Converts JavaScript object to JSON string

JSON.parse – Converts JSON string to JavaScript object

For example:

const json = ‘{"name": "Alex"}‘; // JSON 

const user = JSON.parse(json); // {name: "Alex"}

console.log(user); // regular object

The parsed user object loses JSON formatting. To print back as formatted JSON:

console.log(JSON.stringify(user, null, 2));

So remember – use JSON.stringify() to print. JSON.parse() gives a regular JavaScript object without formatting.

Performance Considerations

A misconception about JSON.stringify() is poor performance parsing large datasets. But native JSON support makes modern JavaScript engines optimize it well.

For example, benchmarking serializing a 10MB dataset4:

Method Time
JSON.stringify() 0.8 sec
Custom Serialize 62 sec

So JSON.stringify() is quite fast. Custom code unlikely to be faster.

However, here are some performance tips:

  • Use replacer function to exclude unneeded properties
  • Set space parameter to 0 to consolidate output
  • Stream stringification for very large data

Best Practices

Here are some best practices when printing JSON objects in JavaScript:

  • Check for circular references that could cause errors
  • Use 2 space formatting during development for readability
  • Omit spacing in production to minimize payload sizes
  • Employ custom replacers to redact sensitive fields
  • Ensure displayed API keys/secrets are not exposed publicly
  • Handle large JSON responses by streaming stringification

Common Pitfalls

Some common mistakes to avoid:

  • Forgetting to stringify objects leading to no formatting
  • Over nesting objects causing hard to diagnose errors
  • Including private data and keys logging should redact
  • Printing JSON tangling with parsing related logic
  • Assuming stringification is slow without profiling

So be careful to use JSON.stringify purposefully.

Conclusion

JSON has quickly become a universal data format, with JavaScript uniquely positioned to leverage it. As a result, printing string representations of JSON objects is an indispensable tool for JavaScript developers.

Luckily the JSON.stringify() method provides an easy way to deeply serialize JavaScript objects into human readable, automatically formatted JSON. It handles object nesting extremely well, while allowing customization like property filtering. And native JSON support makes stringification fast for even large datasets.

So if you find yourself squinting to make sense of a dense lump of JSON, call on JSON.stringify() to prettify it into formatted bliss. This one method can save developers countless hours over the course of a project debugging ugly JSON blobs. Learning to properly print JSON objects unlocks simpler analysis of API responses and interfaces.

What techniques have you found helpful for handling JSON? Please share in the comments below!

Sources

  1. https://json.org/json-en.html
  2. https://techcommunity.microsoft.com/t5/azure-developer-community-blog/json-everywhere/ba-p/331788
  3. https://w3techs.com/technologies/details/cp-javascript
  4. https://github.com/mcollina/fast-json-stringify#benchmarks

Similar Posts