Skip to content

Instantly share code, notes, and snippets.

@codebubb
Created November 1, 2023 10:21
Show Gist options
  • Save codebubb/8786e70c64f8ce33bf13e9d8a0e69267 to your computer and use it in GitHub Desktop.
Save codebubb/8786e70c64f8ce33bf13e9d8a0e69267 to your computer and use it in GitHub Desktop.
How To Fix the JSON parse error
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON.parse Error</title>
<style>
* {
box-sizing: border-box;
}
body {
font-family: sans-serif;
margin: 2rem;
}
hr {
margin: 2rem 0;
}
textarea {
padding: 1rem;
border: 2px solid black;
width: 100%;
}
pre {
padding: 2rem;
box-shadow: 0 0 16px 4px rgba(0, 0, 0, 0.1);
}
</style>
</head>
<body>
<h1>JSON.parse Error</h1>
<h2>1. Manual String Parsing:</h2>
<label for="jsonInput">JSON String</label>
<textarea id="jsonInput"></textarea>
<pre id="manualResult"></pre>
<hr>
<h2>2. Network Request Result:</h2>
<pre id="networkResult"></pre>
<script>
window.onload = () => {
// Manual strings
const jsonInputElement = document.getElementById('jsonInput');
jsonInputElement.addEventListener('input', () => {
let objectValue;
try {
objectValue = JSON.parse(jsonInputElement.value);
} catch (error) {
objectValue = {};
}
console.log(objectValue);
document.getElementById('manualResult')
.textContent = JSON.stringify(objectValue, null, 2);
});
const apiUrl = 'http://localhost:3000';
// Fetch API
fetch(`${apiUrl}/users`)
.then(result => {
console.log(result);
if (!result.ok) {
throw new Error(`Not JSON data [${result.statusText}]`)
}
return result.json();
})
.then(json => {
document.getElementById('networkResult')
.textContent = JSON.stringify(json, null, 2);
})
.catch(error => {
console.error(error);
document.getElementById('networkResult')
.textContent = error;
})
};
</script>
</body>
</html>
import express from 'express';
import cors from 'cors';
const app = express();
app.use(cors());
const users = [
{
id: '78d2c770-08da-4273-a475-c9301108766e',
username: 'crazymorality',
lastLogin: '2021-10-31T09:27:21.302Z'
},
{
id: 'b7863e79-5d99-458b-92ff-116e74847e70',
username: 'baboonreader',
lastLogin: '2022-09-31T02:17:21.002Z'
},
{
id: 'c260f6b5-89ff-4cce-88fd-43aba55dfdd6',
username: 'infantryknight',
lastLogin: '2022-03-21T01:14:11.002Z'
}
];
app.get('/users', (request, response) => {
return response.json(users);
})
const port = 3000;
app.listen(port, () => {
console.log(`App listening on port:${port}`);
})
@codebubb
Copy link
Author

codebubb commented Nov 1, 2023

Source code for tutorial at https://youtu.be/eJXSLCFLJJE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment