Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling errors for broken JSON

If the element #the-json is empty it will cause this error:

Uncaught SyntaxError: Unexpected end of input

For the following code:

myJSON = JSON.parse($("#the-json").attr('value'));

How should this error be handled so it doesn't stop the entire script working?

like image 302
el_pup_le Avatar asked Jul 29 '12 10:07

el_pup_le


People also ask

How does JSON handle line breaks?

In JSON object make sure that you are having a sentence where you need to print in different lines. Now in-order to print the statements in different lines we need to use '\\n' (backward slash). As we now know the technique to print in newlines, now just add '\\n' wherever you want.

What happens if JSON parse fails?

Copied! We call the JSON. parse method inside of a try/catch block. If passed an invalid JSON value, the method will throw an error, which will get passed to the catch() function.

How do I fix the response is not a valid JSON response?

Deactivate all plugins to see if it solves the problem. If you no longer see the “The response is not a valid JSON response” error message, and all post updates made from the block editor are saved correctly, reactivate plugins one by one to identify the one causing issues.

How do I check if JSON is correct?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JSchema) method with the JSON Schema. To get validation error messages use the IsValid(JToken, JSchema, IList<String> ) or Validate(JToken, JSchema, SchemaValidationEventHandler) overloads.


1 Answers

Use try-catch statement:

try {
  myJSON = JSON.parse($("#the-json").attr('value'));
} catch (e) {
  // handle error
}

Or check before do something:

var myJSON = JSON.parse('{}'); // default value

if ($("#the-json").attr('value')) {
  myJSON = JSON.parse($("#the-json").attr('value'));
}
like image 50
Danil Speransky Avatar answered Sep 22 '22 02:09

Danil Speransky