Creating a JSON String in JavaScript

In JavaScript, you can use JSON.stringify() method to convert a JavaScript object into a JSON string.

Here's a simple example

// Define an object named 'obj'
const obj = {
  name: "John",
  age: 30,
  address: {
    street: "123 Main St",
    city: "New York",
  },
};

// Convert the 'obj' object to a JSON string
const jsonString = JSON.stringify(obj);

console.log(jsonString);

This will give you a JSON string like this:

{"name":"John","age":30,"address":{"street":"123 Main St","city":"New York"}}

Excluding Properties

You can choose which properties to exclude during the conversion by providing an array or a function as the second argument.

If you pass an array of strings (or numbers), they are treated as the names of object properties. Properties not in the array will be left out during stringification.

const jsonStringArrayReplacer = JSON.stringify(person, ["name", "age"]);

console.log(jsonStringArrayReplacer);
// Output: {"name":"John","age":30}

If you pass a function as the replacer, it gets called for each value being stringified. The function takes two arguments: the property name or array index of the value, and the value itself.

If the replacer function returns undefined or nothing, the corresponding value (and its property) won't be included in the final JSON string.

const jsonStringFunctionReplacer = JSON.stringify(person, (key, value) => {
  if (key.includes("name")) {
    return undefined;
  }
  return value;
});

console.log(jsonStringFunctionReplacer);
// Output: {"age":30,"address":{"street":"123 Main St","city":"New York"}}

Making JSON Readable

If you want to make your JSON string more readable, you can use the 3rd parameter

Provide a number or a string as the third argument.

  • If you use a number, it indicates the number of spaces for each indentation level.

  • If you use a string (like '\t'), it represents the characters for each level of indentation.

const obj = {
  name: "John",
  age: 30,
  address: {
    street: "123 Main St",
    city: "New York",
  },
};

// Format the JSON string for better readability (2 spaces indentation)
const jsonStringFormatted = JSON.stringify(obj, null, 2);

// Display the nicely formatted JSON string
console.log(jsonStringFormatted);

This will give you a nicely formatted, indented JSON string:


{
  "name": "John",
  "age": 30,
  "address": {
    "street": "123 Main St",
    "city": "New York"
  }
}

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda