Javascript 将缓冲文件数据转换为Json对象:express fileupload
我正在通过http发送一个JSON文件。该文件可使用express fileupload中间件在Javascript 将缓冲文件数据转换为Json对象:express fileupload,javascript,json,node.js,file-upload,Javascript,Json,Node.js,File Upload,我正在通过http发送一个JSON文件。该文件可使用express fileupload中间件在req.files上获得。我将文件作为缓冲数据获取。我想将文件转换为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; v
req.files
上获得。我将文件作为缓冲数据获取。我想将文件转换为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文件结构
{
"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"
}
根据调试中显示的内容,您的编码不是
utf8
,而是7bit
。因此,为了正确解码,您需要更改一点代码
var file = req.files.seed;
var obj = JSON.parse(file.data.toString('ascii'));
// ... do your creation logic
您可以使用utf8
,ascii
econdings来查看是否存在JSON.parse
问题
var file = req.files.seed;
var obj = JSON.parse(file.data.toString('ascii'));
// ... do your creation logic