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"}';

请给出任何想法如何转换它,使其表现为树状结构。即 T1 将在循环中搜索到下一个 T1,并将 T1 及其值附加到当前迭代项中,类似于 T2 等等。例如 str2。

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"}';
4

1 回答 1

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"]}
于 2013-04-09T02:29:50.060 回答