AnswerBun.com

How can i edit an array in a JSON file from node?

Stack Overflow Asked by thomas bouasli on January 3, 2022

I have an JSON file that holds an array of objects, like so:

[
  { "id": 1, "name": "JavaScript Begginer", "duration": "10 Hours" },
  { "id": 2, "name": "JavaScript Intermediate", "duration": "15 Hours" },
  { "id": 3, "name": "JavaScript Advanced", "duration": "20 Hours" }
]

and I wish to add a new object to it using Node, can this be accomplished with the File System Module?

Here is where I want the change to be made:

 app.post("/api/courses", (req, res) => {
  const course = {
    id: courses.length + 1,
    name: req.body.name,
  };
  res.send(course);

  courses.json.push(course); //Something like this

});

I did try fs.appendFile but it returns this:

[
  { "id": 1, "name": "JavaScript Begginer", "duration": "10 Hours" },
  { "id": 2, "name": "JavaScript Intermediate", "duration": "15 Hours" },
  { "id": 3, "name": "JavaScript Advanced", "duration": "20 Hours" }
]
[object Object]

One Answer

Check out lowdb... its a fs based wrapper for working with json file as your persisted storage method:

https://github.com/typicode/lowdb

Answered by jremi on January 3, 2022

Add your own answers!

Related Questions

C# find the greatest common divisor

11  Asked on January 5, 2022 by user2723261

   

Time series summary

2  Asked on January 5, 2022 by naanan_

     

Compute frequencies for groups of variables

3  Asked on January 5, 2022 by armel-tedjou

       

How to plot entropart Diversity profiles in ggplot2

1  Asked on January 5, 2022 by alejandra-dip

   

Laravel 6.4.1 SQLSTATE[HY000] [2002] Connection refused

12  Asked on January 5, 2022 by manish-mahajan

         

How to get the key of an element in firebase with AngularFire2?

1  Asked on January 5, 2022 by juan-esteban-rios-gonzalez

         

(PowerShell) How do I filter usernames with Get-EventLog

3  Asked on January 5, 2022 by jeremiah-williams

     

pandas isin() fail between dataframes with objects types columns

1  Asked on January 5, 2022 by franco-milanese

     

Ask a Question

Get help from others!

© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP