Codelab Editor
Free Online HTML Editor
Run
Learn JSON
<!DOCTYPE html> <html> <head> <style> body { padding: 10px; background: #fdfdfd; font-family: sans-serif; } .user-card { display: none; max-width: 320px; padding: 16px; border: 1px solid #ccc; border-radius: 12px; background-color: #f5f5f5; margin-top: 20px; } .user-card h3 { margin: 0 0 10px; font-size: 20px; } .user-card p { margin: 6px 0; } button { margin-right: 10px; padding: 8px 16px; border: none; background-color: #0088cc; color: white; border-radius: 6px; cursor: pointer; } button:hover { background-color: #006fa3; } #errorMsg { color: #c00; margin-top: 16px; } </style> </head> <body> <h2>Handling <code>JSON.parse()</code> Exceptions</h2> <p>Click below to attempt parsing malformed JSON with a safeParse helper.</p> <button onclick="loadUser()">Parse Bad JSON</button> <div id="errorMsg"></div> <div class="user-card" id="userCard"> <h3 id="fullName"></h3> <p><strong>Age:</strong> <span id="age"></span></p> </div> <script> // malformed JSON string (missing quotes around age) const badJson = '{"name": "Alice", age:30}'; /** * Attempts to parse JSON and returns either the parsed object * or null on failure. Errors are logged and can be handled by caller. */ function safeParse(jsonString) { try { return JSON.parse(jsonString); } catch (err) { console.error('JSON.parse error:', err.message); return null; } } function loadUser() { // clear previous output document.getElementById('errorMsg').textContent = ''; document.getElementById('userCard').style.display = 'none'; const data = safeParse(badJson); if (data) { // show parsed data document.getElementById('fullName').textContent = data.name; document.getElementById('age').textContent = data.age; document.getElementById('userCard').style.display = 'block'; } else { // show user-friendly error document.getElementById('errorMsg').textContent = 'Unable to parse user data. Please check the JSON format and try again.'; } } </script> </body> </html>
Editor Commands
Ctrl
F
Find
Ctrl
G
Find Next
Ctrl
⇧
G
Find Previous
Ctrl
⇧
F
Find & Replace
Ctrl
]
Indent Code Right
Ctrl
[
Indent Code Left
⇧
Tab
Auto Indent Code
Ctrl
/
Line Comment
Ctrl
Alt
/
Block Comment
TutsInsider Actions
Alt
S
Run Code
Ctrl
C
Copy Editor Code
Ctrl
A
Select All Editor Code
Ctrl
S
Save/Download
Ctrl
Alt
X
Rotate
Ctrl
Alt
T
Switch Theme
Ctrl
⇧
C
Open Console
Esc
Close Console