Codelab Editor
Free Online HTML Editor
Run
Learn JSON
<!DOCTYPE html> <html> <head> <style> body { padding: 10px; background: #fdfdfd; font-family: sans-serif; } pre { background-color: #eee; padding: 10px; border-radius: 6px; overflow-x: auto; display: none; } button { margin-right: 10px; padding: 8px 16px; border: none; background-color: #0088cc; color: white; border-radius: 6px; cursor: pointer; } button:hover { background-color: #006fa3; } h3 { margin-top: 20px; } </style> </head> <body> <h2>Custom Serialization with toJSON() Method</h2> <p>Click the button to serialize an object with a custom <kbd>toJSON()</kbd> method using <kbd>JSON.stringify()</kbd>.</p> <p>So only id and name are included in the final JSON string. The price property is intentionally excluded.</p> <p>If you want to include price too, you must return it inside toJSON():</p> <button onclick="serializeCustom()">Serialize Object</button> <h3 id="objectTitle" style="display:none;">Original Object</h3> <pre id="objectOutput"><code></code></pre> <h3 id="jsonTitle" style="display:none;">JSON String</h3> <pre id="jsonOutput"><code></code></pre> <script> function serializeCustom() { const product = { id: 101, name: "Gadget", price: 199.99, toJSON() { return { id: this.id, name: this.name }; } }; const jsonString = JSON.stringify(product); document.getElementById('objectOutput').style.display = 'block'; document.getElementById('jsonOutput').style.display = 'block'; document.getElementById('objectTitle').style.display = 'block'; document.getElementById('jsonTitle').style.display = 'block'; document.querySelector('#objectOutput code').textContent = `const product = { id: 101, name: "Gadget", price: 199.99, toJSON() { return { id: this.id, name: this.name }; } };`; document.querySelector('#jsonOutput code').textContent = jsonString; } </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