0

我的 JSON 响应中有子列表,如

"sublist" : {
    "102" : "Core_Java(23)",
    "103" : "Oracle(12)",
    "111" : "Ruchek(15)",
    "104" : "IST-Examportal(20)",
    "105" : "CyberSecurity(30)"
}

我想变成这样

var jsonSource = '[{
        "ID" : 102,
        "SUBNAME" : "Core_Java(23)"
    }, {
        "ID" : 103,
        "SUBNAME" : "Oracle(12)"
    }, {
        "ID" : 111,
        "SUBNAME" : "Ruchek(15)"
    }, {
        "ID" : 104,
        "SUBNAME" : "IST-Examportal(20)"
    }, {
        "ID" : 105,
        "SUBNAME" : "CyberSecurity(30)"
    }
]';

帮助我使用 JavaScript 做到这一点。

4

2 回答 2

1

您可以使用 for-in 循环来执行此操作。

var result = [];

for(var property in sublist){
   if(sublist.hasOwnProperty(property)){
      result.push({ID: property, SUBNAME: sublist[property]});
   }
}
于 2013-05-21T11:43:46.030 回答
0

只需使用一个for..in循环:

var sublist = [],
    jsonSource;

for (var key in obj.sublist) {
    sublist.push({
        "ID" : key,
        "SUBNAME" : obj.sublist[key]
    });
}

jsonSource = JSON.stringify(sublist);
于 2013-05-21T11:44:53.050 回答