2013-04-09 143 views
0

我在下面的有道詞典的形式,其具有的字符串:var str1= '{ "T1" : "1"},{ "T1" : "2"}, { "T2" : "3"},{ "T2" : "4"}, { "T2" : "5"}, { "T3" : "6"}, { "T3" : "7"},{ "T3" : "8"},{ "T2" : "9"}, { "T2" : "10"}, { "T1" : "11"}, { "T1" : "12"}';串字典,字典

PLZ給任何想法如何轉換它,使得它表現爲樹狀結構。即T1將搜索直到下一個T1循環,並且將在當前迭代項中追加T1和它的值,並且類似於T2等等。

str2='{ "T1" : "1"} ,{ "T1" : "2", "T2" : "3"},{ "T1" :"2", "T2" : "4"}, { "T1" : "2", "T2" : "5", "T3" : "6"}, { "T1" : "2", "T2" : "5", "T3" : "7"},{ "T1" : "2", "T2" : "5", "T3" : "8"}, 
{ "T1" : "2", "T2" : "9"},{ "T1" : "2", "T2" : "10"}, { "T1" : "11"}, { "T1" : "12"}'; 
+0

首先,它包裝到方括號並用JSON.parse解析。然後循環所得到的對象數組並構建您的樹。 – bfavaretto 2013-04-09 02:14:11

回答

0

我不確定爲什麼你有這樣的結構。這不是一個有效的JSON,你不能解析它,因爲你不能有兩次相同的屬性。所以,你需要的是「標準化」一下,或者以另一種方式從中獲得價值。例如:

var str = '{ "T1" : "1"},{ "T1" : "2"}, { "T2" : "3"},{ "T2" : "4"}, { "T2" : "5"}, { "T3" : "6"}, { "T3" : "7"},{ "T3" : "8"},{ "T2" : "9"}, { "T2" : "10"}, { "T1" : "11"}, { "T1" : "12"}'; 

var re = /"([^"]*)"\s*:\s*"([^"]*)"/g; 
var dict = {}; 

for (var matches; matches = re.exec(str);){ 
    var key = matches[1]; 
    (dict[key] || (dict[key] = [])).push(matches[2]); 
} 

這將創建一個對象dict像:

{T1:["1", "2", "11", "12"], T2:["3", "4", "5", "9", "10"], T3:["6", "7", "8"]}