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

425
Views
¿Cómo actualizar correctamente un objeto json?

Estoy aprendiendo backend usando node.js, así que estoy desarrollando una API RESTfull. Necesito usar PUT para actualizar un objeto por id (la id como parámetro) en un archivo json. Estoy usando postaman para probar.

Esta es mi matriz:

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

Por ejemplo, tengo un servidor local http://127.0.0.1:8080/products/3 (el número 3 será el artículo que quiero actualizar cambiando el precio o el nombre).

comencé así

 app.put("/products/:id", (request, resolve) => { const id = Number(request.params.id); })
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

en un archivo JSON, debe volver a escribir sus datos cada vez que actualice los datos

 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 })

nota : esta no es la forma síncrona de escribir JavaScript. Si te gusta mi respuesta, no olvides votar y seguir.

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!