从多个对象创建有效的JSON

时间:2017-09-13 08:04:15

标签: javascript 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有效?

预期结果:

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

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

哪一个更有用又更正确?

2 个答案:

答案 0 :(得分:1)

单个实体请求应如下所示:单个对象

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

多个实体应如下所示:多个对象

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

答案 1 :(得分: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"},
}