jQuery – $ .each循环遍历json代码

由于我的服务器端脚本输出的方式,我收到多个JSON对象。 {jsonhere} {jsonhere1} {jsonhere2} {jsonhere3}等等。他们没有被任何东西分开。 如果我做分裂} {我会失去那些括号。 那么有一个外环我可以放在常规的$ .each循环上来实现这个function吗?

谢谢,

粗糙算法:

Define a stack Define an array LOOP on each character in the string IF the top item of the stack is a single or double quote THEN LOOP through each character until you find a matching single or double quote, then pop it from the stack. ELSE IF "{", push onto the stack IF "}" THEN pop a "{" from the stack if it is on top IF the stack is empty THEN //we just finished a full json object Throw this json object into an array for later consumption END IF END IF IF single-quote, push onto the stack IF double-quote, push onto the stack END IF END LOOP 

这不是JSON。

jQuery以懒惰的方式解释JSON,调用eval()并希望那里没有“真正的”代码; 因此它不会接受。 (我猜你已经知道了)。

似乎唯一的出路是将其视为文本字符串,并使用正则表达式来提取数据。

以下是有效的JSON响应:

 [ {JSON}, {JSON}, {JSON}, {JSON} ] 

由于您的JSON格式不正确,只需将其修复到服务器端即可。 下面的代码比EndangeredMassa建议的更简单,它避免在引号括起来的大括号之间添加逗号。 我不太擅长RegEx用一个.replace()来解决它。

 var string = "{\"key\":\"val}{ue\"}{'key':'val}{ue'}{ \"asdf\" : 500 }"; var result = string.match(/('.*?')|(".*?")|(\d+)|({)|(:)|(})/g); var newstring = ""; for (var i in result) { var next = parseInt(i) + 1; if (next <= result.length) { if (result[i] == "}" && result[next] == "{") { newstring += "},"; } else { newstring += result[i]; } } 

}

要循环访问JSON对象,请使用以下命令:

 $.each(eval(newstring), function() { //code that uses the JSON values alert(this.value1); alert(this.value2); }); 

除非你能保证数据中的任何字符串都不包含“} {”,否则你甚至不能安全地拆分它而不解析JSON至少足以跟踪你是否在字符串中。 例如,如果您只是拆分它:

 {"foo": "}{", "bar": 42} 

在“} {”附近,你会得到两个无效的JSON对象而不是一个。

如果您知道永远不会发生这种情况,您可以拆分大括号并将“}”附加到除最后一个元素之外的每个元素,并将“{”添加到最后一个元素。 如果没有其他办法,我只会这样做,因为它真的很脆弱。

我设法凑齐了一个工作的例子! 将以下文本另存为html页面。 它似乎在IE7和FF3中运行良好。 如果您有任何问题,请告诉我。

(我使用了jquery,但根本没有必要。)

       


Results:

这不是JSON,在客户端只修复你的JSON代码,你可以安全地“评估”它。

 var jsonWrong = '{a:1}{a:2}{a:3}'; var jsonRight = jsonWrong.replace('}{', '},{'); var json = eval('('+jsonRight+')');