2017-09-13 47 views
0

我有一個代碼,它生成的對象逐一:創建從多個對象有效的JSON(Node.js的)

... 

    .data(function(data) { 
     //data is object: {name: Bruce, surname: Lee} 
     fs.appendFile('./test.json', JSON.stringify(data, null, 2), function(err) { 
      console.log(err); 
     }); 
    }) 

... 

之後,我有下一個語法我test.JSON文件:

{"name": "Bruce", "surname": "Lee"}{"name": "Bruce", "surname": "Lee"}{"name": "Bruce", "surname": "Lee"} 

許多單個對象,JSON無效......如何在每個對象之後添加逗號或使我的JSON有效?

預期結果:

​​3210

{ 
    "entity": {"name": "Bruce", "surname": "Lee"}, 
    "entity": {"name": "Bruce", "surname": "Lee"}, 
    "entity": {"name": "Bruce", "surname": "Lee"}, 
} 

哪一個將是更加有用和正確...

+0

您能添加預期的JSON嗎? – marvel308

+0

你是否在循環中編寫這些對象? – alexmac

+0

您正在使用'appendFile'循環或至少多次。您可以將所有對象存儲在數組中,然後調用'JSON.stringify()'或者您可以調用'fs.appendFile('./test.json',JSON.stringify(data,null,2)+',' ,function(err){}); ' – Weedoze

回答

0

這將產生對象的數組

[ 
    {"name": "Bruce", "surname": "Lee"}, 
    {"name": "Bruce", "surname": "Lee"}, 
    {"name": "Bruce", "surname": "Lee"} 
] 

這會產生以及包含屬性名稱爲「entity_1」「entity_2」等的其他對象的對象。

{ 
    "entity_1": {"name": "Bruce", "surname": "Lee"}, 
    "entity_2": {"name": "Bruce", "surname": "Lee"}, 
    "entity_3": {"name": "Bruce", "surname": "Lee"}, 
}