合并并保存在json文件中nodejs

时间:2016-07-21 07:30:31

标签: json node.js

我想将json文件的JSON对象添加到另一个文件中。 这是一个例子:

{
    "HOUSES": {
        "1": {
            "NAME": "House1",
            "PEOPLE": {},
            "ID": 1
        },
        "2": {
            "NAME": "House2",
            "PEOPLE": {},
            "ID": 2
        },
        "3": {
            "NAME": "House3",
            "PEOPLE": {},
            "ID": 3
        }
    }
}

人们反对:

{

    "1": {
        "NAME": "People1"
    },
    "2": {
        "NAME": "People2"
    },
    "3": {
        "NAME": "People3"
    }
}

现在我想将人物对象添加到House1中。

我试过了:

var extend = require('util')._extend;
var obj1 = house.PEOPLE; //var content : {}
var obj2 = extend(people, obj1); //var people content people object

此代码用people对象替换所有house1。如何在house1的子级PEOPLE中添加人物对象?

我也尝试使用object-assign,我遇到了同样的问题。

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以通过以下方式完成:

HOUSES.1.PEOPLE = PEOPLEOOBJ;

PEOPLEOBJ在哪里:

PEOPLEOBJ = {

    "1": {
        "NAME": "People1"
    },
    "2": {
        "NAME": "People2"
    },
    "3": {
        "NAME": "People3"
    }
}