Fetch JSON and handle failures
#Load a local JSON fixture, check HTTP status, and parse the response.
JavaScript code
async function loadStatus() {
const response = await fetch('/demo-status.json');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
loadStatus().then(console.log).catch(() => console.error('Cannot load demo status'));
Practical useUse a sanitized local fixture for a status prototype.
Common mistakesfetch does not reject on HTTP 404/500. CORS and authentication still apply; do not put secrets in browser code.
Source: developer.mozilla.org documentation
JSON.parse and JSON.stringify
#Convert JSON text to a value and format it back into readable text.
JavaScript code
const status = JSON.parse('{"running":true}');
console.log(JSON.stringify(status, null, 2));
Practical useInspect a demo API fixture.
Common mistakesJSON parsing can throw. JSON cannot represent functions or undefined as object values.
Source: developer.mozilla.org documentation