如何从JSON文件中删除第一个对象

时间:2019-08-31 16:20:02

标签: node.js json

我正在尝试在节点js中排队,并想删除JSON文件中的第一个JSON对象。

我将用户创建并存储在JSON文件中,然后通过读取users.json将其添加到队列JSON文件中。问题是,当我从user.json获取用户时,它作为数组中的对象出现,并且我无法过滤以比较ID。那我该怎么办呢?

// helper method to read JSON FILE.
    const readFile = (callback, returnJson = false, filePath = dataPath, encoding = 'utf8') => { 
        fs.readFile(filePath, encoding, (err, data) => {
            if (err) {
                throw err;
            }

            callback(returnJson ? JSON.parse(data) : data);
        });
    }; 

    // helper method to write on JSON FILE.
    const writeFile = (fileData, callback, filePath = dataPath, encoding = 'utf8') => {

        fs.writeFile(filePath, fileData, encoding, (err) => {
            if (err) {
                throw err;
            }

            callback();
        });
    };

// thats how i try to delete first user from the queue, but it deletes the user with index 1.

 app.delete('/popLine', (req, res) => {

        readFile(data => {

            //const userId = req.params["id"];
            delete data[1]; // remove the first element from the Line.

            writeFile(JSON.stringify(data, null, 2), () => {
                res.status(200).send(`queue id: removed`);
            });
        },
            true);
    });

// thats how an user is stored in queue.json
"5": [
    {
      "name": "teresa may",
      "email": "parliament",
      "gender": "male",
      "id": 3
    }
  ],

1 个答案:

答案 0 :(得分:0)

我希望将JSON文件作为JSON对象加载(如果它是可管理的),然后通过键删除第一个条目,然后定期或立即将文件持久化(重写)在磁盘上(必要时)。

您可以执行要求以将JSON文件作为JSON对象加载。但是请注意,如果您重新要求对已更改的文件进行重新运行,以在运行时重新加载它,则不会获得您对文件所做的更改,而是从上一个要求。在这种情况下,您需要先从要求缓存中清除该项目,然后再进行更改。

我假设文件按KB顺序排列。对于较大的文件,我不希望采用这种方法,而是想出一种在NoSQL文档数据库中获取文件数据的方法。

希望这会有所帮助:)