【发布时间】:2020-10-29 13:10:12
【问题描述】:
我有一个包含 10 个元素的 json,如下所示: {"id":"2","name":"Peter","number":"A4584857","father":"Gerart","color":"green"}
我尝试修改 json,所以我有一个像这样读写的函数:
function updatefilelocal(id,texto) {
const fs = require('fs');
fs.readFile('students.json', (err, data) => {
if (err) throw err;
let json = JSON.parse(data);
console.log('This is after the read call')
const filename='students.json';
var file=json;
file.alumnos[id].color= texto
fs.writeFile(filename,JSON.stringify(file),function writeJson(err){
if (err)return console.log(err);
//console.log(JSON.stringify(file));
//console.log('writing to'+filename )
});
});
}
所以,用这一行:file.alumnos[id].color= texto 和这个函数:updatefilelocal(2,'yellow') 我可以修改我的 json 中的键颜色,嗯,它有效,但是当我想修改我的元素的键“名称”时像这样更改名称的颜色:file.alumnos[id].name= texto 没关系,但我想做的是在我的函数中添加第三个参数:
function updatefilelocal(id,texto,third_parameter) {...} 更改“名称”上的“颜色”。我会这样调用我的函数:updatefilelocal(id,texto,name) 如果我想更改元素的名称或
updatefilelocal(id,texto,color) 如果我想改变元素的颜色...我已经尝试了所有...我已经放了括号file.alumnos[id].{third parameter}= texto 但没有任何效果...
感谢您的帮助。
【问题讨论】:
-
请在此处发布您的 json 结构。它是一个数组吗?还是具有这些键/值的对象?
-
{"alumnos":[ {"id":"1","name":"Peter","number":"A4584837","father":"Gerart","color" :"green"},{"id":"2","name":"Maria","number":"A4584857","father":"pett","color":"yellow"},{" id":"3","name":"John","number":"A4584857","father":"Juan","color":"green"},etc...]}
标签: javascript node.js json parameter-passing