从JSON子列表转换字符串数组

时间:2013-05-21 11:37:46

标签: javascript arrays json using

我的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执行此操作。

2 个答案:

答案 0 :(得分:1)

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

var result = [];

for(var property in sublist){
   if(sublist.hasOwnProperty(property)){
      result.push({ID: property, SUBNAME: sublist[property]});
   }
}

答案 1 :(得分:0)

只需使用for..in循环:

var sublist = [],
    jsonSource;

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

jsonSource = JSON.stringify(sublist);