简体   繁体   English

使用jQuery更新外部JSON文件中的值

[英]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 我有一个外部JSON文件,我需要通过ID更新一些值,我仅使用HTML和Jquery

1 - external JSON file 1-外部JSON文件

 [ {"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. 如果用户通过<input type="file">选择文件,则可以使用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. 换句话说,您不仅可以尝试通过html访问文件,还可以看到随之而来的安全隐患。 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. 因此,除非您从具有该数据的api /服务器中提取数据,否则您将不得不添加输入选项,然后用户将选择该文件,然后您的函数便可以针对该文件运行。

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":- 我认为要更新json文件的内容,您应该具有运行NodeJS之类的后端并使用文件系统“ 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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