2012-07-07 118 views
0

我已經收到一個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

回答

1

如果你表現出你的一些代碼,這將是非常巨大的:我們基本上不知道這個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

0
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"]); 
}