Análisis de JSON no válido [cerrado]

What happens if I use JSON.parse on an invalid string? Will it return an error code, or just break the script?

Is the behavior consistent across browsers? And for older browsers, does json2.js also have the same behavior?

Context: my script is collecting JSON strings from different sources and parses them. If a string is not well formed, I want my script to ignore it and move to the next.

preguntado el 30 de enero de 12 a las 19:01

What language & library are you using? -

This can be answered very quickly by leyendo el manual -

2 Respuestas

It will throw an error for any invalid syntax. If the JSON you're parsing can be malformed, use try/catch:

try {
  obj = JSON.parse(x)
} catch(e) {
  obj = {}
}

Respondido el 31 de enero de 12 a las 00:01

It will throw a catchable error. On proper browsers, es un SyntaxError. JSON2's implementation refleja esto.

Respondido el 31 de enero de 12 a las 00:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.