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

时间:2017-08-02 07:53:48

标签: javascript json node.js file-upload

我正在通过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)但是语法错误:弹出位置1的JSON中的意外标记o。

我也尝试过使用

将其转换为字符串
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"
}

1 个答案:

答案 0 :(得分:1)

根据您在调试中提供的内容,您的编码不是utf8,而是7bit。因此,要进行正确的解码,您需要更改一下代码。

var file = req.files.seed;
var obj = JSON.parse(file.data.toString('ascii'));

// ... do your creation logic

您可以使用utf8ascii进行任何方式来查看您是否遇到JSON.parse个问题。