Challenges with JSON Documents

const fs = require('fs');
const express = require('express');

const app = express();

app.use(express.json());

app.get('/submit', (req, res) => {
    let Com_Title = req.query.ComTitle;
    let Com_Text = req.query.ComText;
    let data = {
        Title: Com_Title,
        Text: Com_Text,
    }
    console.log(data);
    let jsonData = JSON.stringify(data);
    // fs.writeFileSync('notes.json', dataJSON)
    // let MyData = JSON.parse(jsonData);
    fs.appendFileSync('ComplaintFile.json', jsonData, err => {
        if (err) {
            console.log(err);
            res.sendStatus(404).end();
        }
        console.log('Data Added');
        res.send('Added');
    })
});

let port = 8080;
app.listen(port, () => {
    console.log("Listening to 8080");
})
{
    "Title": "School Events",
    "Text": "Exciting activities and workshops"
}{
    "Title": "Summer Vacation",
    "Text": "Relaxing by the beach"
}

I am encountering an issue with saving data in a JSON file. It seems that when I add new data, it is not separated properly with commas in the file.

Has anyone else faced this problem before?

Answer №1

It is not recommended to use appendfilesync for storing JSON data because JSON is structured and appendfilesync simply appends data at the end of the file. To properly store JSON data, follow these steps:

  1. Retrieve existing data from the file.
  2. Parse the data into a JSON object.
  3. Add new data to the JSON object/array.
  4. Convert the updated JSON data back into a string.
  5. Save the modified data back to the file.

In this example, the initial content of the file would be an array like:

[{"Title":"Title","Text":"Content"}]

Therefore, it starts as an array where you can add more objects.

var fs = require("fs");

fs.readFile("data.json", function(err, buf) {
  let dataStr = buf.toString();
  let dataObj = JSON.parse(dataStr);
  let newData = {Title: "Title", Text: "Content"};
  dataObj.push(newData); // assuming that this is an array

  let newDataStr = JSON.stringify(dataObj);

  fs.writeFile("data.json", newDataStr, (err) => {
    if (err) console.log(err);
    console.log("Successfully Written to File.");
  });
});

Answer №2

You're on the right track with inputting data accurately, but remember to extract existing data from the file and then combine it with the new data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to obtaining specific top elements from an array using JavaScript

I'm seeking assistance with sorting arrays in JavaScript. Here is an example of a sorted array: mainArray : [25 20 20 20 18 17 17 15 12 12 10 5 5 ] The mainArray may contain duplicate values. A. Dealing with duplicates Based on user input, I need ...

Link property can be added to a bindpopup polygon in Leaflet to have it open in a new tab when clicked

Is it possible to include a hyperlink in popup content on Leaflet, similar to this example? function onEachFeature(feature, layer) { idLoDat = feature.properties.IDLo; layer.bindPopup("Company name: " + feature.properties.TenCty + " ...

Updating a nested property within an array of objects in MongoDB

Storing grades for an online education application using MongoDB. Here is a sample classRoom document stored in my mongoDB database. StudentGradeObjs are kept in an array within a GradeObject. GradeObjs are stored in an array of GradeObjects inside a class ...

Ways to eliminate the absence of the 'Access-Control-Allow-Origin' header in an error message when using a Java-based web-service server

I'm currently working on developing a webservice using Java as the server and Javascript as the client. My goal is to send a Post request with JSON data and receive a Post response with JSON data from the server. However, since the client and server h ...

Show the GitHub repositories of the user within a React application

Even though I am relatively new to React, I managed to create a GitHub search application. In this app, you can input a user's name in a search box and view their avatar, bio, username, etc. However, I'm facing an issue with fetching their reposi ...

Efficiently sending VueJS data to a separate script

I am in the process of transitioning an existing site to VueJS, but I have encountered a roadblock when it comes to finding the best method to accomplish this task. The site currently utilizes D3-Funnel (https://github.com/jakezatecky/d3-funnel) to genera ...

The image file that was uploaded to our S3 storage has been detected

I'm attempting to upload an image created by cropperjs to a DigitalOcean space. To achieve this, I am utilizing a pre-signed URL and performing a put request using Axios. The problem arises when I try to open the uploaded image, as it appears to be ...

Retrieve JSON encoded data from a separate AJAX request

Currently utilizing prestashop 1.6, I have a specific ajax function where I encode data that is successfully retrieved on the console using echo. Now, my task is to decode this JSON data in another ajax function in order to extract a value for a particular ...

Setting a condition for a function call when a checkbox is clicked

My table has columns labeled NoBill and Bill, with checkboxes as the values. Here is the default view of the table: https://i.stack.imgur.com/ZUvb2.png When the checkbox in the NoBill column is clicked, the total value (this.total) is calculated. The t ...

Running NodeJS scripts with ElectronJS is not possible

Goal I'm facing a challenge with executing my separate scripts located in the project/api folder. Let's take test.js as an example, where I am exporting it using module.exports. When I run my electron window and create a JavaScript file with a f ...

Why are the $refs always empty or undefined within Vue components?

I am completely new to working with Vue and I've been attempting to utilize $refs to retrieve some elements within the DOM from a sibling component. My objective is very basic, as I just need to obtain their heights, but I haven't had much succes ...

Determine the byte size of the ImageData Object

Snippet: // Generate a blank canvas let canvas = document.createElement('canvas'); canvas.width = 100; canvas.height = 100; document.body.appendChild(canvas); // Access the drawing context let ctx = canvas.getContext('2d'); // Extrac ...

Transmit the Boolean value to the controller using ajax requests in asp.net.core with C# programming

Within the view section, there is a form that includes a checkbox input. <div class="checkbox"> <label class="">active</label> <div class="icheckbox_flat-green checked" style="position: relative;"> <input type="checkbox" id="A ...

How can I implement a Component to show the details of a blog post when clicked in Next.js?

Can someone help me figure out how to display individual blog post details in a modal when clicked on in a blog website, where the posts are stored in a Component rather than pages? The file structure is set up like this: Component |_ Posts.js |_ PostDet ...

What is the best way to deactivate a button when a certain input field is left blank?

I'm having trouble figuring out how to deactivate a button when specific input fields are empty, while others can remain optional for the process. In my course, we were taught to disable the button until all inputs are valid, so I'm a bit confus ...

How can I apply a class to the pre and code elements in Redactor?

I've been struggling for days to figure out how to add a class to the formatting option element within Redactor. By default, the "Code" formatting option wraps content in either <pre></pre> or <code></code> HTML elements. Howe ...

Animating the smooth collapse of panels within listviews

I have successfully implemented a smooth animation code for a collapsible panel, and it is working wonderfully: <script type="text/javascript"> function pageLoad(sender, args) { smoothAnimation(); } function smoothAnimation() ...

Verify whether the value is considered false, true, or null

When dealing with variables in JavaScript, I often need to determine if a variable is false, true, or null. If the variable is null or undefined, I want to assign an array to it by default. While this syntax works well in other languages, in JS assigning a ...

Click the button to trigger the pop-up

After creating a photo gallery using a plugin, my goal is to display this gallery when the user clicks on my homepage button. I am unsure how to make this happen and would appreciate any assistance. Below is my button code: <div class="ow-button-base ...

Encountering a problem with parsing a JSON object using the .map

After receiving this JSON response, my main goal is to extract the value located in the identifier. By utilizing console.log, I am able to analyze the structure of the object: Object {rows: Array[33], time: 0.015, fields: Object, total_rows: 33} fields: O ...