node.jsjsonformidable

How to build json dynamically from formidable


Am trying to build a json object from request's form fields dynamically, the fields are recevied okey, but I can't get the json to be built as I want.

I tried the below approach

let userJson = {}

var form = new formidable.IncomingForm();

form.parse(req);

form.on('field', function (name, value) {
   userJson[name]=value; //didn't work
   [userJson.name]=value]; // didn't work
});

Solution

  • I did it manually in two steps ...

    var userJson = []
    
        var form = new formidable.IncomingForm();
    
        form.parse(req);
    
        form.on('field', function (name, value) {
            userJson.push('"' + name + '"' + ':' + '"' + value + '"')
        });
    

    and then I did

    form.on('end', function (name, file) {
            userJson = '{' + userJson.toString() + '}'
            userJson = JSON.parse(userJson)
            console.log(userJson)
        });