How to add data to a JSON file in JavaScript?

Adding data to a JSON file in JavaScript typically involves a few steps: reading the existing data from the file, modifying the data in memory, and then writing the updated data back to the file. The specifics can vary slightly depending on the environment in which your JavaScript code is running (Node.js server-side versus client-side in a browser).

Node.js Environment

On a Node.js server, you have the filesystem (fs) module available to read from and write to files directly. Here’s how you can add data to a JSON file:

1. Read the JSON File

First, you need to read the existing JSON file. This can be done synchronously or asynchronously. For better performance in a production environment, you should use the asynchronous methods.

const fs = require('fs'); // Read the JSON file asynchronously fs.readFile('data.json', 'utf8', (err, data) => { if (err) { console.error("An error occurred reading the file:", err); return; } // Parse the JSON data const obj = JSON.parse(data); // Modify your JSON object obj.newData = "This is new data"; // Convert it back to a string to prepare for output const updatedJson = JSON.stringify(obj, null, 2); // Write it back to the file fs.writeFile('data.json', updatedJson, 'utf8', err => { if (err) { console.error("An error occurred writing the file:", err); } else { console.log("File has been updated"); } }); });

2. Modify the Data

Once you've read and parsed the data, you can add or modify it just like any other JavaScript object.

3. Write the Data Back to the File

After modifying the data, you need to serialize it back to a JSON string using JSON.stringify() and then write it to the file.

Browser Environment

In a client-side JavaScript running in a browser, you don't have direct access to the file system for security reasons. To modify a JSON file, you typically need to:

  1. Fetch the JSON data from a server.
  2. Modify it in the browser.
  3. Send the modified data back to the server where it can be saved.

Here’s a basic example using fetch API:

// Fetch the JSON data from the server fetch('data.json') .then(response => response.json()) .then(data => { // Modify the data data.newData = "New data added"; // Send the updated data back to the server fetch('server-endpoint', { method: 'POST', // or 'PUT' headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }) .then(response => response.json()) .then(updatedData => { console.log('Updated data:', updatedData); }) .catch(error => console.error('Error updating data:', error)); }) .catch(error => console.error('Error fetching data:', error));

In this browser example, you need to have a server-side endpoint (server-endpoint) that accepts the updated JSON data, processes it, and potentially writes it to a file on the server or updates a database.

Summary

  • In Node.js, you can directly read and write files using the fs module.
  • In a browser, you must handle JSON data via HTTP(S) requests since direct file manipulation is not allowed for security reasons.
TAGS
System Design Interview
CONTRIBUTOR
Design Gurus Team
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
What is the entry level package of Cisco?
What is Pinterest interview difficulty?
Preparing for system design interviews at major technology companies
Prepare for system design interviews at Google, Meta, Amazon, and Netflix. Covers company-specific rubrics, leveling expectations, and a proven prep timeline.
Which IT job is most in demand?
What is AEO and How to Make Answers LLM-Friendly?
Learn what Answer Engine Optimization (AEO) is, how to write LLM-friendly answers, and how it helps your content rank higher on Google, ChatGPT, Perplexity, and Gemini.
Which of the following are valid best practices for multithreading and concurrency?
Related Courses
Grokking the Coding Interview: Patterns for Coding Questions course cover
Grokking the Coding Interview: Patterns for Coding Questions
The 24 essential patterns behind every coding interview question. Available in Java, Python, JavaScript, C++, C#, and Go. The most comprehensive coding interview course with 543 lessons. A smarter alternative to grinding LeetCode.
4.6
Discounted price for Your Region

$197

Grokking Modern AI Fundamentals course cover
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
3.9
Discounted price for Your Region

$72

Grokking Data Structures & Algorithms for Coding Interviews course cover
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
4
Discounted price for Your Region

$78

Design Gurus logo
One-Stop Portal For Tech Interviews.
Copyright © 2026 Design Gurus, LLC. All rights reserved.