【发布时间】:2018-11-26 05:16:30
【问题描述】:
我有一个 json 文件,我正在尝试使用以下代码删除一个元素。
exports.delete = function(req, res) {
var deletearticle = articles[req.params.id];
delete articles[req.params.id];
fs.writeFile('server/articles.json',JSON.stringify(articles, null, 4),finished);
function finished(err){
console.log("--->After deletion, article list:\n" + JSON.stringify(articles, null, 4) );
}
res.end(JSON.stringify(deletearticle, null, 4));
};
删除元素后,我的 json 文件将如下所示:
[
{
"header": "Jack",
"body": "Davis",
"date": "",
"id": 0
},
null,
{
"header": "dfd",
"body": "dgfgfgfgfdgfg",
"date": "2018-11-24T16:33:48.842Z",
"id": 2
}]
我在客户端收到错误:
{articles ? articles.map(({ id, header ,body}) => (
<div key={id} timeout={500} className="fade">
<div className="article">
<h2 className="article_title">{header}</h2>
因为我的 JSON 元素之一是 null,所以它说无法从 null 读取 id。有没有更好的方法从我的 json 文件中删除这个元素?或者我可以检查客户端的 srticle 是否不为空。
【问题讨论】: