最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Delete field from JSON file in node - Stack Overflow

programmeradmin1浏览0评论

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 be delete 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
Add a ment  | 

2 Answers 2

Reset to default 6

To 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"}
发布评论

评论列表(0)

  1. 暂无评论