将缓冲的文件数据转换为Json对象:express-fileupload

我通过http发送一个JSON文件。 该文件在req.files使用express-fileupload中间件提供。 我正在获取文件作为缓冲的数据。 我想将文件转换为JSON对象。

 app.post('/start', function(req, res){ if(!req.files.seed) res.status(400).send("Please upload the seed file"); var file = req.files.seed; var obj = //Convert the file to JSON object and send it to create instance; instance.createInstance(obj); res.status(200).send("Started...."); }); 

打印时,文件看起来像这样

 { name: 'seed.json', data: <Buffer 7b 0d 0a 09 22 61 72 72 61 79 22 3a 20 5b 20 31 2c 20 31 20 5d 2 c 0d 0a 09 22 72 65 63 75 72 72 65 6e 63 65 22 3a 20 7b 0d 0a 09 09 22 73 65 63 6f 6e ... >, encoding: '7bit', mimetype: 'application/json', mv: [Function: mv] } 

我尝试使用JSON.parse(file)但SyntaxError:在JSON位置1的意外令牌opopup。

我也尝试使用将其转换为string

 var text = file.toString(file,'utf8') var obj = JSON.parse(text) 

但是这似乎也不起作用。 这个对象的属性在访问时是未定义的。

JSON文件结构。

 { "array": [ 1, 1 ], "recurrence": { "second": 50, "minute": null, "hour": null, "dayOfweek": null }, "campaign": { "sender": "StartUp India Yatra", "email": "fashion@getposhaq.com", "subject": "{Invitation} StartUp India Yatra Chapter", "title": "StartUp India Yatra Campaign" }, "condition": { "open": { "greaterThanEqual": 1, "lessThan": 2 }, "campaignSummary": null }, "textPath": "../template.txt", "htmlPath": "../template.html", "path": "../emailer/index.js" "retailerId": "4" } 

鉴于你在debugging中提出的,你的编码不​​是utf8而是7bit 。 所以为了正确的解码,你需要改变一下你的代码。

 var file = req.files.seed; var obj = JSON.parse(file.data.toString('ascii')); // ... do your creation logic 

任何方式你可以玩utf8ascii econdings,看看你是否没有JSON.parse问题。