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

Showing nested routes component information - Angular

I am working on a project that includes the following components: TodosComponent (path: './todos/'): displaying <p>TODO WORKS</p> AddTodosComponent (path: './todos/add'): showing <p>ADD TODO WORKS</p> DeleteTo ...

Tips for confirming date is earlier than current date in Reactjs?

Looking for guidance on how to ensure a date selected by a user is always before the current date when using Material UI in my project. For instance, if it's January 6th, 2021 and the user selects either January 5th or 6th that would be acceptable. Ho ...

Enabling JavaScript functions to accept a variable number of arguments

I am looking to enhance the versatility of the function below by enabling it to accept multiple callbacks to other functions if they are specified in the arguments. $(function() { function icisDashBox(colorElem, thisWidth, thisHeight, completeCallBack ...

Fill a .js script with moustache.js

I need help with organizing some JavaScript code that needs to access server-side data. I want to keep this code in a separate .js file, but I'm having issues populating it with the necessary server information using moustache. Here is my current setu ...

Leveraging the power of JavaScript to retrieve data from BigQuery

Having just started my journey with JavaScript and Google BigQuery, I am seeking help due to my lack of experience in these areas. My goal is to create a javascript code that can fetch data from one of the public databases on BigQuery. I came across a solu ...

Adding a button input and deleting non-functional parent elements

Here is a simple append function using jQuery, and it's working perfectly. However, the issue arises when I try to append a button and remove the parent tr upon clicking. The problem lies in using remove parent, as it doesn't seem to work as exp ...

How can I submit a form using ajax and retrieve the data as an array?

Hey there, I need some help on how to submit a form and receive data in the form of an array like this: { "notes":'some notes', "validUntil": '12/12/2015', "status": 1, "menuItemName": "HR Section", "menuItemDesc": "gggg" } Here is th ...

Using a Firebase token repeatedly: simple steps to follow

I have integrated Firebase Web Notification using Firebase SDK. The implementation process involves two files: a) generate-token.js and b) firebase-messaging.sw.js To get access token, permission is requested by calling requestPermission function. Upon ...

varied reactions between componentDidMount and useEffect when employing jquery emoji plugin

Currently, I am facing an issue with a jquery emoji plugin that I need to use on one of my components until I complete building a custom plugin. Interestingly, when I call the emoji plugin inside componentDidMount, everything works fine, except for the ab ...

The process for changing the textContent to X when an image is clicked

How can I create a function that changes the text content to 'X' when an image is clicked? I already have a function that updates the title based on the image dataset, but combining the two functions has been unsuccessful. Can someone help me con ...

Overuse of jQuery's preventDefault() and stopPropagation() functions

A recent discussion with a coworker revealed some contrasting coding practices, mainly concerning his extensive use of the two aforementioned methods in event handlers. Every event handler he creates follows this same pattern... $('span.whatever&apos ...

I recently incorporated Puppeteer along with its necessary dependencies onto Heroku, and as a result, pushing my small app to Heroku now takes approximately 5 to 6 minutes

I am currently using Puppeteer to create a PDF from an HTML page. I installed the npm package by running the following command: npm i puppeteer However, when I deployed to Heroku, I encountered an error: Error while loading shared libraries: libnss3.s ...

Node.js console and endpoint are returning an object, but the JSON object cannot be fetched

Currently, I am working on a project for an online course where I am utilizing an NLP sentiment analysis API. Although I have made significant progress, I seem to be stuck at the final step. When I send the URL for analysis via the API call, I can see the ...

Gradient transition effect changing background color from bottom to top

I am facing an issue where I have a block and I want the background color to animate from bottom to top on hover. Can you please help me identify what is causing this problem? Your assistance is greatly appreciated. .right-block--wrapper { backgroun ...

Failure to display div upon onmouseover event

The div 'hidden-table' is causing issues as it does not display even though the style attribute 'display:none' has been removed. I have attempted to show the table separately outside of the echo statement, and it appears to work correct ...

Why isn't my watch function functioning properly within Vue?

In my JS file, I have two components. The file starts with this line: const EventBus = new Vue(); I am trying to pass two strings, 'username' and 'password', from the first component to the second component, but it's not working. ...

Using CSS or JavaScript to trigger events while scrolling with touch

Imagine a scenario where multiple boxes are stacked on top of each other: <div style="width: 100%; height: 100px; background-color: red"> stuff </div> By clicking or touching them, the background color can be easily changed using CSS (:hover, ...

Communicating data transfer between two Node.js servers through the use of the Node Serial Port technology

How can I send the message "Hello world" from one nodejs server to another using node-serialport? I have confirmed that the radios connecting the two servers are properly connected as they are displaying buffer information after running my current code. ...

Fix background transition and add background dim effect on hover - check out the fiddle!

I'm facing a challenging situation here. I have a container with a background image, and inside it, there are 3 small circles. My goal is to make the background image zoom in when I hover over it, and dim the background image when I hover over any of ...

The removeEventListener method in JavaScript fails to function properly

On my website, I have a unique feature where clicking an image will display it in a lightbox. Upon the second click, the mouse movement is tracked to move the image accordingly. This functionality is working as intended, but now I'm faced with the cha ...