2012-12-04 47 views
1

什麼是重組的Json與Angularjs或jQuery的最好方式..重組的Json與Angularjs或jQuery的

我得到一個JSON具有以下格式

[ 
    { 
    "address":"balh", 
    "lat":123, 
    "long":456 
    }, 
    { 
    "address":"balh", 
    "lat":321, 
    "long":543 
    }, 
    { 
    "address":"balh", 
    "lat":432, 
    "long":333 
    }, 
    { 
    "address":"balh", 
    "lat":123, 
    "long":456 
    }, 
    { 
    "address":"balh", 
    "lat":321, 
    "long":543 
    }, 
    { 
    "address":"balh", 
    "lat":432, 
    "long":333 
    } 
] 

我需要的格式是其組有三個像下面這樣..

{ 
    "1":[ 
     { 
     "address":"balh", 
     "lat":123, 
     "long":456 
     }, 
     { 
     "address":"balh", 
     "lat":321, 
     "long":543 
     }, 
     { 
     "address":"balh", 
     "lat":432, 
     "long":333 
     } 
    ], 
    "2":[ 
     { 
     "address":"balh", 
     "lat":123, 
     "long":456 
     }, 
     { 
     "address":"balh", 
     "lat":321, 
     "long":543 
     }, 
     { 
     "address":"balh", 
     "lat":432, 
     "long":333 
     } 
    ] 
} 
+3

你輸入JSON實際上不是有效的JSON:最外面的'{'和'}'應該是'['和']',因爲它是一個數組。假設你糾正了這個問題,你就不會重構JSON _string,你會解析它,然後操縱結果對象來創建一個新的對象,並且需要你需要的結構(如果你需要的話,你可以連續返回一個JSON字符串至)。 – nnnnnn

+0

Ahh ..它現在已經修復..謝謝.. – MomentH

+0

謝謝nnnnnn,我不認爲你看着Angularjs ..有一個理由這樣做,使用直接與ng-repeat json綁定.. – MomentH

回答

2

這看起來更像是一個直接的JavaScript問題給我。

下面的代碼應該把你的陣列,並將其與三個(或更少)打入陣列的字典對象,每個:

var yourArray = [/*whatever it is in here*/]; 

var output = {}; 

for(var i = 0, c = 1, current = null; i < yourArray.length; i++) { 
    if(i % 3 == 0) { 
     output[c++] = current = []; 
    } 
    current.push(yourArray[i]); 
} 

Here's a fiddle (using Angular) demonstrating before and after output

+1

真棒小提琴..謝謝:) – MomentH