Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

428
Views
how to update properly an json´s object?

I´m learning backend using node.js, so I´m developing a API RESTfull. I need to use PUT to update a object by id (the id as a params) in a json file. I´m using postaman to test.

This is my array:

[
  {
    "item": "phone",
    "price": 10000,
    "id": 1
  },
  {
    "item": "tv",
    "price": 20000,
    "id": 2
  },
  {
    "item": "nintendo",
    "price": 2500000,
    "id": 3
  },
  {
    "item": "ipad",
    "price": "500000",
    "id": 4
  }
]

For example I a have a local server http://127.0.0.1:8080/products/3 (the number 3 will be the item I wanna update changing the price or the name).

I started like this

app.put("/products/:id", (request, resolve) => {
  const id = Number(request.params.id);



})
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

in a JSON file, you need to rewrite your data every time you update data

const data = require("./<fileName>.json"); // bring your json file
const fs = require("fs"); // fileModule to updata your json file

app.put("/products/:id", (request, resolve) => {
  const id = Number(request.params.id);

  let idx = data.findIndex(e=>e.id===id);// getting index of data by matching your id
  if(!idx){
    return resolve.json({message:"data not found"});
  }

  data[idx] = {} // your new data with id, you will get this data from request.body

  fs.writeFile("./<fileName>.json",JSON.stringify(data),(err)=>{  // writing updated data in your json fil
    if(err){
      return resolve.json({message:err}); // if you get ant error
    }
  });

  resolve.json(JSON.stringify(data)); // send response 
})

note:this is not the synchronous way of writing JavaScript. if you like my answer don't forget to upvote and follow.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!