我在尝试通过JQuery.parseJSON函数解析以下JSON时遇到麻烦。 (“未捕获的SyntaxError:意外令牌”)
[{"ExtIdremoto":"8","ExtNombre":"Silla bebe","ExtDescripcion":"Lorem ipsum lorem pete can","ExtPrecioDia":"4.5","ExtPrecio":"13.5","ExtCuantificable":"true"},{"ExtIdremoto":"9","ExtNombre":"Alzador","ExtDescripcion":"Lorem ipsum lorem pete can","ExtPrecioDia":"4.5","ExtPrecio":"13.5","ExtCuantificable":"false"},{"ExtIdremoto":"10","ExtNombre":"Maxicosi","ExtDescripcion":"Lorem ipsum lorem pete can\r\n•\tBlue\r\n•\tBlue\r\n•\t“blue”","ExtPrecioDia":"0","ExtPrecio":"0","ExtCuantificable":"true"},{"ExtIdremoto":"12","ExtNombre":"GPS","ExtDescripcion":"Lorem ipsum lorem pete can","ExtPrecioDia":"0","ExtPrecio":"0","ExtCuantificable":"true"}]
尽管JSON通过了http://jsonlint.com/验证,但看起来好像是“•”引起了问题。
我没有使用任何解析器库,并且一直在尝试使用此处指定的函数进行解析:
https://stackoverflow.com/a/16652683/1161355
我该如何替角色装扮?
PD:我在努力避免包含任何外部库来满足项目要求
更新资料
JSON存储在字符串中,并通过会话var传递到jsp。
StringBuilder sbJson = new StringBuilder();
sbJson.append("[");
Iterator<DatosExtra> it = datosDisponibilidad.getExtrasOpcionales().iterator();
while(it.hasNext()){
DatosExtra datos = (DatosExtra) it.next();
sbJson.append("{\"ExtIdremoto\":").append("\"").append(datos.getExtIdremoto()).append("\"").append(",\"ExtNombre\":").append(escaparCaracteresJSON(datos.getExtNombre(locale)))
.append(",\"ExtDescripcion\":").append(escaparCaracteresJSON(datos.getExtDescripcion(locale)))
.append(",\"ExtPrecioDia\":").append("\"").append(datos.getExtPrecioDia()).append("\"")
.append(",\"ExtPrecio\":").append("\"").append(datos.getExtPrecio()).append("\"")
.append(",\"ExtCuantificable\":").append("\"").append("S".equals(datos.getExtCuantificable())).append("\"")
.append("}");
if(it.hasNext()) sbJson.append(",");
}
sbJson.append("]");
hpRequest.getRequest().getSession().setAttribute("jsonExtras", sbJson.toString());
其中escaparCaracteresJSON是已注释的先前函数
在JSP中,我恢复了该值:
var jsonExtras = jQuery.parseJSON('<%=session.getAttribute("jsonExtras")%>');
输出就是这样的:
var jsonExtras = jQuery.parseJSON('[{"ExtIdremoto":"8","ExtNombre":"Silla bebe","ExtDescripcion":"Lorem ipsum lorem pete can","ExtPrecioDia":"4.5","ExtPrecio":"9","ExtCuantificable":"true"},{"ExtIdremoto":"9","ExtNombre":"Alzador","ExtDescripcion":"Lorem ipsum lorem pete can","ExtPrecioDia":"4.5","ExtPrecio":"9","ExtCuantificable":"false"},{"ExtIdremoto":"10","ExtNombre":"Maxicosi","ExtDescripcion":"Lorem ipsum lorem pete can\r\n•\tBlue\r\n•\tBlue\r\n•\t“blue”","ExtPrecioDia":"0","ExtPrecio":"0","ExtCuantificable":"true"},{"ExtIdremoto":"12","ExtNombre":"GPS","ExtDescripcion":"Lorem ipsum lorem pete can","ExtPrecioDia":"0","ExtPrecio":"0","ExtCuantificable":"true"}]');
最佳答案
我相信您在\r
,\n
和\t
中缺少一个反斜杠-它应该是\\r
,\\n
和\\t
。添加这些使jQuery.parseJSON()
正常工作-http://jsfiddle.net/Nv282/。您能说明如何在escaparCaracteresJSON()
函数中转义字符吗?