Writing JSON

Introduction

Writing JSON means saving JavaScript objects or arrays into a JSON file. JSON files are widely used for storing configuration settings, application data, user information, reports, and API responses.

In Node.js, writing JSON files is simple using the built-in File System (fs) module together with JSON.stringify().

For automation engineers, writing JSON files is commonly used to save API responses, generate test reports, store execution logs, create configuration files, and export test data.

In this tutorial, you’ll learn different ways to write JSON data to files in Node.js.


Why Write JSON Files?

Writing JSON files allows applications to:

  • Save application data

  • Store configuration settings

  • Export reports

  • Save API responses

  • Create backup files

  • Store automation test results

  • Generate reusable test data


The File System Module

Node.js uses the built-in File System (fs) module for file operations.

const fs = require("fs");

Understanding JSON.stringify()

JavaScript objects cannot be written directly to a file.

Use JSON.stringify() to convert a JavaScript object into a JSON string.

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

const jsonData = JSON.stringify(employee);

The output becomes:

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

Example 1: Write a JSON File

const fs = require("fs");

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

fs.writeFile(
    "employee.json",
    JSON.stringify(employee),
    (error) => {

        if (error) {
            console.log(error);
            return;
        }

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

Sample Output

JSON file created.

Generated employee.json

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

Pretty Printing JSON

To make JSON more readable, pass additional arguments to JSON.stringify().

JSON.stringify(employee, null, 4);

Generated JSON:

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

Example 2: Write Formatted JSON

const fs = require("fs");

const product = {
    id: 501,
    name: "Laptop",
    price: 75000
};

fs.writeFile(
    "product.json",
    JSON.stringify(product, null, 4),
    (error) => {

        if (error) {
            console.log(error);
            return;
        }

        console.log("Product saved.");
    }
);

Sample Output

Product saved.

Example 3: Write JSON Synchronously

const fs = require("fs");

const student = {
    rollNo: 101,
    name: "Alice"
};

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

console.log("Student saved.");

Sample Output

Student saved.

Example 4: Write a JSON Array

const fs = require("fs");

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

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

console.log("Employee data saved.");

Sample Output

Employee data saved.

Generated employees.json

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

Real-World Example

Create an application 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

Writing JSON files is widely used in automation frameworks.

Playwright Example

Save browser configuration.

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

Store fixture data.

const fs = require("fs");

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

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

API Testing Example

Save API response.

const fs = require("fs");

const response = {
    status: 201,
    message: "User Created"
};

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

Data-Driven Testing Example

Create employee test data.

const fs = require("fs");

const employee = {
    id: 1001,
    name: "David",
    department: "HR"
};

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

Common Mistakes

Forgetting JSON.stringify()

Incorrect:

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

Correct:

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

Writing Invalid Objects

Always ensure the object contains valid JavaScript values before converting it to JSON.


Forgetting Error Handling

When using writeFile(), always handle errors.

if (error) {
    console.log(error);
    return;
}

Best Practices

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

  • Use pretty printing (null, 4) to improve readability.

  • Prefer asynchronous methods for better performance.

  • Store configuration and test data in separate JSON files.

  • Handle write errors properly.

  • Keep JSON files well organized and properly formatted.

  • Use meaningful property names.


Conclusion

Writing JSON files is an important part of Node.js development. The combination of the built-in fs module and JSON.stringify() makes it easy to save structured data in a portable and readable format.

For automation engineers, JSON files are essential for storing configuration settings, API responses, test data, execution reports, and environment information.

Mastering JSON writing helps you build scalable Node.js applications and professional automation frameworks.


Frequently Asked Questions (FAQs)

Which module is used to write JSON files?

The built-in fs (File System) module.


Why is JSON.stringify() required?

Because files can only store text, JSON.stringify() converts JavaScript objects into JSON strings.


How do I make JSON more readable?

Use:

JSON.stringify(object, null, 4);

What is the difference between writeFile() and writeFileSync()?

  • writeFile() is asynchronous.

  • writeFileSync() is synchronous and blocks execution until the file is written.


Can I write JSON arrays?

Yes. Arrays can be converted using JSON.stringify() and written to JSON files.


Why is writing JSON important in automation testing?

Automation engineers write JSON files to save API responses, generate execution reports, store configuration settings, maintain test data, and export automation results.


Key Takeaways

  • Use the built-in fs module to write JSON files.

  • Convert JavaScript objects into JSON using JSON.stringify().

  • Use writeFile() for asynchronous writing.

  • Use writeFileSync() for synchronous writing.

  • Pretty print JSON using JSON.stringify(object, null, 4).

  • JSON files are commonly used for configuration, reports, and API data.

  • Handle file writing errors properly.

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

  • Store structured data in readable JSON format.

  • Mastering JSON writing is essential for backend development and automation testing.