2017-08-02 86 views
1

我正在通過http發送JSON文件。該文件可在req.files上使用express-fileupload中間件獲得。我將該文件作爲緩衝數據。我想將文件轉換爲JSON對象。將緩衝的文件數據轉換爲Json對象:express-fileupload

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)但語法錯誤:意外的標記?在JSON在位置1個彈起。

我還用它轉換成使用

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": "[email protected]", 
     "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

鑑於你在調試呈現,你的編碼不​​是utf87bit。所以爲了正確的解碼,你需要改變你的代碼。

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

// ... do your creation logic 

任何方式,您可以用utf8ascii econdings玩玩看,如果你沒有JSON.parse問題。