简体   繁体   中英

Update value in external JSON file using jquery

I have an external JSON file and I need to update some values by Id, I am using only HTML and Jquery

1 - external JSON file

 [ {"Id":1,"startTime":7.665519,"endTime":15.701717}, {"Id":2,"startTime":18.9402,"endTime":23.036628}, {"Id":3,"startTime":27.398977,"endTime":33.404313}, {"Id":4,"startTime":37.254842,"endTime":41.127843}, {"Id":5,"startTime":44.534945,"endTime":50.064397}, {"Id":6,"startTime":44.534945,"endTime":50.064397}, {"Id":7,"startTime":44.534945,"endTime":50.064397} ] 

  $("#btnUpdateJson").click(function(){ var Id = $("#txtId").val(); var startTime = $("#txtStartTime").val(); var endTime = $("#txtEndTime").val(); $.getJSON( "../Admin/Data/fileName.json", function( data ) { $.each(data, function(i, item){ if (data[i].Id == Id){ // What can i do to update // StartTime and EndTime ? // where Id in jsone file = Id from html } }); }); }); 

If the user selects a file via <input type="file"> , you can read and process that file using the File API.

Reading or writing arbitrary files is not allowed by design. It's a violation of the sandbox.

In other words, you can't just try and access a file via html, you can see the security concerns that may follow that. So unless you are pulling from an api/server that has that data you will have to add an input option, then the user will select the file, then your function can run against it.

Here's the solution in node

const fs = require('fs');

var update_entry = (id, st, et, fn) => {
    var old_instance = JSON.parse(fs.readFileSync(`${fn}`, 'utf-8')); // Read the json file in
    let found = old_instance.find(record => { return record.Id == id }); // Find the object by Id
    st != null ? found.startTime = st : ''; // If not null, set value
    et != null ? found.endTime = et : ''; // If not null, set value
    let new_instance = old_instance.filter(record => { return record.Id != id }); // Copy original array besides found record
    new_instance.push(found);return new_instance; // Add found record to new array and return
}

var updated = update_entry(2, 5.9999, null, 'data.json');
console.log(updated);

Output

[ { Id: 1, startTime: 7.665519, endTime: 15.701717 },
  { Id: 3, startTime: 27.398977, endTime: 33.404313 },
  { Id: 4, startTime: 37.254842, endTime: 41.127843 },
  { Id: 5, startTime: 44.534945, endTime: 50.064397 },
  { Id: 6, startTime: 44.534945, endTime: 50.064397 },
  { Id: 7, startTime: 44.534945, endTime: 50.064397 },
  { Id: 2, startTime: 5.9999, endTime: 23.036628 } ]

 // server side example const express=require('express'); const app = express(); const fs = require('fs'); const bodyParser=require('body-parser'); app.use(bodyParser.json()); app.put('your/end/point, (req, res)=>{ let id = req.body.id; let startTime = req.body.startTime; let endTime = req.body.endTime; if(!id || !startTime || !endTime) return res.status(400).send({ error:'id, startTime and endTime are required!' }); fs.readFile(__dirname + '../Admin/Data/fileName.json,'utf-8', (err, data)=>{ if(err) return res.send({error:err}); let myTimesList = JSON.parse(data); let idFound = false; for (let i = 0; i < myTimesList.length; i++) { if (id == myTimesList[i].id){ let newTime ={id, startTime, endTime } myTimesList.splice(i, 1, newTime); idFoud = true; break; } } if(!idFound) { return res.send({ error:'invalid id!' }); } fs.writeFile(__dirname +'../Admin/Data/fileName.json,'utf-8' , JSON.stringify(myTimesList), 'utf-8', (err)=>{ if (err) return res.send({error:err}); return res.send({message:'Your file has been updated'}); }); }); }); 

I think to update the content of the json file you should have a backend like NodeJS running and use the file system "fs":-

1st step: read the file and parse it.

2nd step: check where exactly you want to change.

3rd step: you already have new content for your file you have to stringify

4th step: now your new data ready to write the file again.

Hope this will help you.

您的数据成为项,现在您可以在外部文件中获取ID

if (item.Id == Id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM