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?
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.
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.
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.
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.
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'));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With