admin管理员组文章数量:1345007
I want to delete a field from a JSON file in node. Suppose my file looks like this
{
'name': John Doe,
'nickname': Johnny
}
and if I say delete('nickname');
I want it to look like this.
{
'name': John Doe
}
How should I go about doing this? Also is there a way to check how many elements are left in the file? And if so how could I delete the whole file if it is empty?
update: this is the code I'm debugging
var data = require(pathToFile);
var element = data[deleteKey];
delete element;
fs.writeFileSync(pathToFile, JSON.stringify(data, null, 4), 'utf8');
res.end(deleteKey + ' was deleted');
console.log(JSON.stringify(data, null, 4));
I want to delete a field from a JSON file in node. Suppose my file looks like this
{
'name': John Doe,
'nickname': Johnny
}
and if I say delete('nickname');
I want it to look like this.
{
'name': John Doe
}
How should I go about doing this? Also is there a way to check how many elements are left in the file? And if so how could I delete the whole file if it is empty?
update: this is the code I'm debugging
var data = require(pathToFile);
var element = data[deleteKey];
delete element;
fs.writeFileSync(pathToFile, JSON.stringify(data, null, 4), 'utf8');
res.end(deleteKey + ' was deleted');
console.log(JSON.stringify(data, null, 4));
Share
Improve this question
edited Jul 20, 2015 at 10:14
Brian Tompsett - 汤莱恩
5,89372 gold badges61 silver badges133 bronze badges
asked Jul 19, 2015 at 23:21
Lee DennisLee Dennis
951 gold badge1 silver badge5 bronze badges
2
-
var element = data[deleteKey]; delete element;
should bedelete data[deleteKey];
– Sebastian Nette Commented Jul 19, 2015 at 23:50 - yes this was just for debugging purposes. but neither way works haha – Lee Dennis Commented Jul 19, 2015 at 23:52
2 Answers
Reset to default 6To check how many elements are left in the JSON file, you can use this:
Object.keys(jsonArray).length;
To delete an element however:
var json =
{
'name': John Doe,
'nickname': Johnny
}
var key = "name";
delete json[key];
As for deleting a file, you can use ajax and call a server-side file to acplish this.
You can just delete it...
var myObj = { 'name': 'John Doe', 'nickname': 'Johnny'};
delete myObj.nickname;
OR
var myObj = { 'name': 'John Doe', 'nickname': 'Johnny' };
delete myObj["nickname"];
OUTPUT
{name: "John Doe"}
本文标签: javascriptDelete field from JSON file in nodeStack Overflow
版权声明:本文标题:javascript - Delete field from JSON file in node - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743767957a2535590.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论