开发者

How to add a JSON item whose name already existed as another attribute?

I'm trying create this:

var a = {
"requestM" : {
    "task" : "list",
    "listRequest" : {
        "checkedEntryType" : "GLOBAL",
        "targetList" : {
            "maxResult" : "2",
            "status" : "OPEN",
            "entryType" : "CALL"
        },
        "targetList" : {
            "maxResult" : "3",
            "status" : "CLOSED",
            "entryType" : "CALL"
        },
        "targetList" : {
            "maxResult" : "2",
            "status" : "OPEN",
            "entryType" : "TODO"
        },
        "targetList" : {
            "maxResult" : "2",
            "status" : "CLOSED",
            "entryType" : "TODO"
        }
    }
}

}

The targetList is not nested inside an array, but it repeats. Now I try to create the message like this:

var reqJson = {
        "requestM" : {
            "task" : "list",
            "listRequest" : {
                "checkedEntryType" : checkedEntryType
            }
        }
    };

    reqJson.requestM开发者_Python百科.listRequest.targetList={
        "maxResult" : 10,
        "status" : "OPEN",
        "entryType" : "CALL"
    };
    reqJson.requestM.listRequest.targetList={
        "maxResult" : 10,
        "status" : "OPEN",
        "entryType" : "TODO"
    };

However the second targetList will replace the first one. How to avoid this? Thanks!


A key must be unique for an object. Make its value an array. Once you have converted from JSON to JavaScript objects you can then push data onto it.

"listRequest" : {
    "checkedEntryType" : "GLOBAL",
    "targetList" : [
    {
        "maxResult" : "2",
        "status" : "OPEN",
        "entryType" : "CALL"
    },
    {
        "maxResult" : "3",
        "status" : "CLOSED",
        "entryType" : "CALL"
    }
    ]


I think this is not possible as in json object

var o = 
{
 "p1": value1,
 "p2": value2 
}

p1 and p2 are considered to be properties of the object, so duplicate properties are overwritten. Instead try to use array

i.e

targetList : [ { "maxResult" : "2",
        "status" : "OPEN",
        "entryType" : "CALL"}, { "maxResult" : "3",
        "status" : "CLOSED",
        "entryType" : "CALL"}, {..} ]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜