使用Javascript替换JSON中的项目

我是javascript新手。我正在尝试将JSON元素替换为从另一个函数传递的设置值。当我解析对象时,在位置0处收到错误消息意外令牌。

谢谢。

var defaultMessage = {
    "MTI": "1101",
    dataElements: {
        "DE01": "101",
        "DE02": "201",
        "DE03": "301",
        "DE04": "401",
        "DE05": "501",
        "DE06": "601",
        "DE07": "701"
    }
}


replaceDefaultElements: (testElements) => {
    console.info(testElements)
    console.info(defaultMessage);
    var messageElements = JSON.parse(defaultMessage.dataElements);
    Object.keys(testElements).forEach(function (key) {
        messageElements[key] = testElements[key];
    });
    return messageElements;
}

//Calling from JEST test function:

test('Should be ', () => {
    expect(functions.replaceDefaultElements('{"MTI":"1101",{"DE01":"XXX"}}')).toEqual({
        "MTI": "1101",
        dataElements: {
            "DE01": "XXX",
            "DE02": "201",
            "DE03": "301",
            "DE04": "401",
            "DE05": "501",
            "DE06": "601",
            "DE07": "701"
        }
    })
评论
半面妆
半面妆
当我解析对象时,在位置0处收到错误消息意外令牌。

defaultMessage.dataElements is a JavaScript object. It isn't JSON.

Don't use JSON.parse there.

testElements, on the other hand, is JSON.

点赞
评论
罗小乖
罗小乖

用defaultMessage.dataElements替换JSON.parse(defaultMessage.dataElements)

用Object.keys(JSON.parse(testElements))替换Object.keys(testElements)

希望它能工作

点赞
评论