简体   繁体   中英

How to write/append the json object from a POST request to a JSON file?

I want to add a JSON element to a JSON file using the data given by a POST request. This already kind of works, I just can't figure out how to add the id to the data, how do I do that?

I tried a lot, I have created a completely new JSON object and tried to add it to my file which didn't work and I tried adding data to the data given from the POST request like this: body += { "id": 10 }; which produces an undefined error.

Here is how I handle the POST request:

} else if (req.method === 'POST' && pathname === 'Kunden') {

        res.writeHead(200, {
            'Content-Type' : 'application/json'
        });

        var body = '';
        req.on('data', function(data) {
            body += data;
        });

        req.on('end', function() {

            fs.readFile('Kunden.json', function(err, kundenJSON) {
                if (err) {
                    console.log(err);
                }

                var kunden = JSON.parse([kundenJSON]);
                kunden.kunde.push(JSON.parse(body));
                kundenJSON = JSON.stringify(kunden);

                fs.writeFile('Kunden.json', kundenJSON, function(err) {
                    if(err) {console.log(err);
                    }});
            });

            });
    }

}).listen(8081);

and here is my already existing JSON file:

{"kunde":[{"id":1,"name":"Customer1"},{"id":2,"name":"Customer2"},{"id":3,"name":"Customer3"}]}

Basically I get the "name" from the POST req and I have to add the following id (in the first request this would be 4, then 5 and so on) to it and then append it to my file.

In the end my file should look like this:

{"kunde":[{"id":1,"name":"Customer1"},{"id":2,"name":"Customer2"},{"id":3,"name":"Customer3"},{"id":4,"name":PostData"}]}

But I can only manage this right now:

{"kunde":[{"id":1,"name":"Customer1"},{"id":2,"name":"Customer2"},{"id":3,"name":"Customer3"},{"name":PostData"}]}

If I understand you correctly, you want to add and id to the new object when you save it to the file. This is basically easy, but you should also know how to keep track of the ids properly.

var kunden = JSON.parse([kundenJSON]);
var newKunde = JSON.parse(body);
newKunde.id = 4;
kunden.kunde.push(newKunde);
kundenJSON = JSON.stringify(kunden);

The problems I'm talking about is, how to you get to know the new id? You could just say newId = kunden.kunde.length + 1 - but if you delete one later on, you will have duplicate ids. You also need to think about how to handle unique ids for the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM