一尘不染

将键值对附加到json对象

json

这是我正在使用的 json对象

{
    "name": "John Smith",
    "age": 32,
    "employed": true,
    "address": {
        "street": "701 First Ave.",
        "city": "Sunnyvale, CA 95125",
        "country": "United States"
    },
    "children": [
        {
            "name": "Richard",
            "age": 7
        },
        {
            "name": "Susan",
            "age": 4
        },
        {
            "name": "James",
            "age": 3
        }
    ]
}

我希望将此作为另一个键值对:

"collegeId": {
                      "eventno": "6062",
                      "eventdesc": "abc"
                                            };

我尝试了concat,但是使用||给了我结果 符号,我cdnt进行迭代。我用过溢漏,但只删除了逗号。

concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2)));

如何将密钥对值添加到现有的json对象?我正在使用JavaScript。


阅读 240

收藏
2020-07-27

共1个答案

一尘不染

这是最简单的方法,对我有用。

var testJson = {
        "name": "John Smith",
        "age": 32,
        "employed": true,
        "address": {
            "street": "701 First Ave.",
            "city": "Sunnyvale, CA 95125",
            "country": "United States"
        },
        "children": [
            {
                "name": "Richard",
                "age": 7
            },
            {
                "name": "Susan",
                "age": 4
            },
            {
                "name": "James",
                "age": 3
            }
        ]
    };
    testJson.collegeId = {"eventno": "6062","eventdesc": "abc"};
2020-07-27