Tools, FAQ, Tutorials:
JSON-parse-Error.html - JSON.parse() Errors
How to catch errors when calling the JSON.parse() function in JavaScript?
✍: FYIcenter.com
If you want to catch errors when calling the JSON.parse() function in JavaScript,
you can follow this tutorial:
1. Use the "try {...} catch {...}" block to catch the error object throw from the JSON.parse() function, as shown below:
try {
var val = JSON.parse(...);
...
} catch (err) {
...
}
2. Print out the "message" string from the error object back to the user or the log file. The message string gives more details about the error, as shown below:
try {
...
} catch (err) {
document.write(" err.message = "+err.message+"\n");
...
}
3. Enter the following example JavaScript code in a file, JSON-parse-Error.html:
<!-- JSON-parse-Error.html
Copyright (c) FYIcenter.com
-->
<html>
<body>
<script type="text/javascript">
try {
var val1 = JSON.parse('2020'); // Valid
var val2 = JSON.parse('"foo"'); // Valid
var val3 = JSON.parse('[1, 5, "false",]'); // Invalid
document.write("<p>Value from JSON.parse():</p>");
document.write("<pre>");
document.write(" val1.toString() = "+val1.toString()+"\n");
document.write(" val2.toString() = "+val2.toString()+"\n");
document.write(" val3.toString() = "+val3.toString()+"\n");
document.write("</pre>");
} catch (err) {
document.write("<p>Error from JSON.parse():</p>");
document.write("<pre>");
document.write(" err.message = "+err.message+"\n");
document.write("</pre>");
}
</script>
</body>
</html>
4. Save the above code in a file and open it in a Web browser. You see the following output:
Error from JSON.parse(): err.message = Unexpected token ] in JSON at position 15
⇒ Call JSON.parse() with Reviver Function
2023-09-07, ∼2400🔥, 0💬
Popular Posts:
How To Remove Slashes on Submitted Input Values in PHP? By default, when input values are submitted ...
Tools, FAQ, Tutorials: JSON Validator JSON-XML Converter XML-JSON Converter JSON FAQ/Tutorials Pytho...
How to convert JSON Objects to PHP Associative Arrays using the json_decode() function? Actually, JS...
Where can I download the EPUB 2.0 sample book "The Metamorphosis" by Franz Kafka? You can following ...
How To Break a File Path Name into Parts in PHP? If you have a file name, and want to get different ...