转换JSON对象到对象的JSON数组

问题描述:

我已经收到一个JSON片段,其具有下面的行(串转换为JSON对象)转换JSON对象到对象的JSON数组

"profile":{"id":"billg","name":"Bill Gates","countryCode":"US"} 

现在用户增加一个更多的个人,我需要转换简档对象到一组配置文件对象。

"profile":[{"id":"billg","name":"Bill Gates","countryCode":"US"},{"id":"steve","name":"Steve Jobs","countryCode":"US"}] 

任何指针或代码的高度赞赏

+4

指针#1)首先尝试的东西。 – 2012-07-07 07:38:46

+0

http://www.whathaveyoutried.com – 2012-07-07 07:41:30

如果你表现出你的一些代码,这将是非常巨大的:我们基本上不知道这个json字符串的来源是什么(JSON = JavaScript Object Notation,所以'JSON对象'是一个重言式),我们不知道第二个配置文件是如何创建的。

考虑这一点,虽然:

var jsonData = '{"profile":{"id":"billg","name":"Bill Gates","countryCode":"US"}}'; 
var data  = JSON.parse(jsonData); // it's an object now... 
var profile = data.profile;   // storing another object as a value of `.profile` property 
var anotherProfile = {"id":"steve","name":"Steve Jobs","countryCode":"US"}; 
if (! profile[0]) { // checking whether it's an array or not 
    // it's not, so we should make an array, adding another profile as well 
    data.profile = [data.profile, anotherProfile]; 
} 
else { // but if it was, it'd be enough just to push anotherProfile into the end of it 
    data.profile.push(anotherProfile); 
} 
console.log(data); 
+0

谢谢....我完全不清楚,如何用数组覆盖对象。 – amj 2012-07-07 11:46:18

Try This: 


    var obj = jQuery.parseJSON('"profile":[{"id":"billg","name":"Bill Gates","countryCode":"US"},{"id":"steve","name":"Steve Jobs","countryCode":"US"}]'); 

    var a = obj.profile; 

    var jsonArrObj = $.parseJSON('[' + a + ']'); 

可以在阵列访问的名字,像这样:

for (i in jsonArrObj) 
{ 
alert(jsonArrObj[i]["name"]); 
}