JSON.stringify()

Introduction

JSON.stringify() is a built-in JavaScript method used to convert a JavaScript object or array into a JSON string. It is one of the most commonly used methods when working with JSON in Node.js applications.

Whenever you need to save data to a JSON file, send data to a REST API, store information in a database, or transfer structured data over a network, the JavaScript object must first be converted into a JSON string. This conversion is performed using JSON.stringify().

For automation engineers, JSON.stringify() is frequently used to create API request payloads, save test results, generate reports, and write configuration files.

In this tutorial, you’ll learn how JSON.stringify() works and how it is used in real-world Node.js applications.


What is JSON.stringify()?

JSON.stringify() converts a JavaScript value into a JSON string.

Syntax

JSON.stringify(value);
  • value → The JavaScript object, array, or value to convert into a JSON string.


Why Use JSON.stringify()?

JSON.stringify() allows applications to:

  • Convert JavaScript objects into JSON strings

  • Save data to JSON files

  • Send JSON data to REST APIs

  • Store configuration settings

  • Export reports

  • Save automation test results

  • Exchange data between applications


Example 1: Convert an Object into JSON

const employee = {
    id: 101,
    name: "John",
    department: "IT"
};

const jsonString =
    JSON.stringify(employee);

console.log(jsonString);

Sample Output

{"id":101,"name":"John","department":"IT"}

Example 2: Convert an Array

const numbers = [10, 20, 30];

const jsonString =
    JSON.stringify(numbers);

console.log(jsonString);

Sample Output

[10,20,30]

Example 3: Convert an Array of Objects

const employees = [
    {
        id: 1,
        name: "John"
    },
    {
        id: 2,
        name: "Alice"
    }
];

const jsonString =
    JSON.stringify(employees);

console.log(jsonString);

Sample Output

[{"id":1,"name":"John"},{"id":2,"name":"Alice"}]

Pretty Printing JSON

By default, JSON.stringify() generates compact JSON without formatting.

Use additional arguments to make the JSON more readable.

const employee = {
    id: 101,
    name: "John",
    department: "IT"
};

const jsonString =
    JSON.stringify(employee, null, 4);

console.log(jsonString);

Sample Output

{
    "id": 101,
    "name": "John",
    "department": "IT"
}

Writing JSON to a File

const fs = require("fs");

const employee = {
    id: 101,
    name: "John",
    department: "IT"
};

fs.writeFileSync(
    "employee.json",
    JSON.stringify(employee, null, 4)
);

console.log("JSON file created.");

Sample Output

JSON file created.

Real-World Example

Generate a configuration file.

const fs = require("fs");

const config = {
    browser: "chrome",
    headless: true,
    baseUrl: "https://example.com"
};

fs.writeFileSync(
    "config.json",
    JSON.stringify(config, null, 4)
);

console.log("Configuration saved.");

Sample Output

Configuration saved.

Automation Testing Example

JSON.stringify() is widely used in automation frameworks.

Playwright Example

Create a configuration file.

const fs = require("fs");

const config = {
    browser: "chromium",
    headless: true
};

fs.writeFileSync(
    "playwright-config.json",
    JSON.stringify(config, null, 4)
);

Selenium Example

Save execution results.

const fs = require("fs");

const result = {
    test: "Login Test",
    status: "Passed"
};

fs.writeFileSync(
    "result.json",
    JSON.stringify(result, null, 4)
);

Cypress Example

Create fixture data.

const fs = require("fs");

const product = {
    productName: "Laptop",
    quantity: 10
};

fs.writeFileSync(
    "product.json",
    JSON.stringify(product, null, 4)
);

API Testing Example

Create an API request payload.

const payload = {
    name: "John",
    email: "john@example.com"
};

const requestBody =
    JSON.stringify(payload);

console.log(requestBody);

Sample Output

{"name":"John","email":"john@example.com"}

Data-Driven Testing Example

Generate employee test data.

const fs = require("fs");

const employees = [
    {
        id: 1,
        name: "John"
    },
    {
        id: 2,
        name: "Alice"
    }
];

fs.writeFileSync(
    "employees.json",
    JSON.stringify(employees, null, 4)
);

Common Mistakes

Forgetting JSON.stringify()

Incorrect:

fs.writeFileSync(
    "employee.json",
    employee
);

Correct:

fs.writeFileSync(
    "employee.json",
    JSON.stringify(employee)
);

Expecting a JavaScript Object as Output

const json =
    JSON.stringify({
        name: "John"
    });

console.log(typeof json);

Sample Output

string

JSON.stringify() always returns a string, not an object.


Forgetting Pretty Printing

Writing compact JSON makes files harder to read.

Prefer:

JSON.stringify(object, null, 4);

Best Practices

  • Use JSON.stringify() before writing JSON to files.

  • Use pretty printing (null, 4) for better readability.

  • Validate objects before converting them to JSON.

  • Store configuration and test data in separate JSON files.

  • Keep JSON files properly formatted.

  • Use meaningful property names.

  • Avoid unnecessary nesting in JSON structures.


Conclusion

JSON.stringify() is one of the most important methods for working with JSON in Node.js. It converts JavaScript objects into JSON strings that can be stored, transmitted, or shared between applications.

For automation engineers, JSON.stringify() is used extensively to create API request payloads, generate reports, save execution results, and write configuration files.

Mastering JSON.stringify() is essential for building scalable Node.js applications and professional automation frameworks.


Frequently Asked Questions (FAQs)

What does JSON.stringify() do?

It converts a JavaScript object or array into a JSON string.


What type of value does JSON.stringify() return?

It always returns a string.


Why is JSON.stringify() required before writing JSON to a file?

Files store text, not JavaScript objects. JSON.stringify() converts objects into text in JSON format.


How can I make the generated JSON more readable?

Use:

JSON.stringify(object, null, 4);

Can JSON.stringify() convert arrays?

Yes. It can convert arrays, objects, strings, numbers, booleans, and null into JSON strings.


Why is JSON.stringify() important in automation testing?

Automation engineers use JSON.stringify() to create API request payloads, save execution results, generate reports, write configuration files, and export test data.


Key Takeaways

  • JSON.stringify() converts JavaScript values into JSON strings.

  • It returns a string, not a JavaScript object.

  • Use JSON.stringify() before writing JSON to files.

  • Use JSON.stringify(object, null, 4) to format JSON with indentation.

  • It supports objects, arrays, strings, numbers, booleans, and null.

  • It is commonly used to create API request payloads and configuration files.

  • Use the fs module together with JSON.stringify() to save JSON files.

  • JSON.stringify() is widely used in Playwright, Selenium, Cypress, API testing, and Node.js applications.

  • Proper formatting improves the readability of JSON files.

  • Mastering JSON.stringify() is essential for backend development and automation testing.