REST API #4 BEKERJA DENGAN JSON
Table of Contents
Introduction
In this tutorial, we will learn how to create a simple website that displays data from a JSON file. This process is essential for web developers as it allows for dynamic data presentation and interaction with APIs. By the end of this tutorial, you will be able to fetch and display JSON data on a webpage.
Step 1: Download JSON and Image Files
To start, you need to download the necessary files that contain the JSON data and any images you will use in your website.
- Access the download link: Download JSON & IMG Files
- Save the JSON file (e.g.,
data.json
) and any images to your project directory.
Step 2: Set Up Your Project Structure
Organizing your project files is crucial for easy maintenance and development.
- Create a new folder for your project.
- Inside the project folder, create the following subfolders
images
(for storing image files)js
(for JavaScript files)css
(for CSS files)- Place the downloaded JSON file in the root of your project folder and images in the
images
folder.
Step 3: Create the HTML File
Your HTML file will serve as the foundation of your website.
- Create a new file named
index.html
in the project root. - Add the following basic HTML structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Display JSON Data</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1>Data from JSON</h1>
<div id="data-container"></div>
<script src="js/script.js"></script>
</body>
</html>
Step 4: Create the CSS File
Styling your website enhances its appearance and user experience.
- Create a file named
styles.css
in thecss
folder. - Add some basic styles to improve layout and design:
body {
font-family: Arial, sans-serif;
margin: 20px;
}
#data-container {
display: flex;
flex-wrap: wrap;
}
.item {
border: 1px solid #ccc;
margin: 10px;
padding: 10px;
width: 200px;
}
Step 5: Create the JavaScript File
This file will handle fetching and displaying the JSON data.
- Create a file named
script.js
in thejs
folder. - Use the following code to fetch and display data from the JSON file:
fetch('data.json')
.then(response => response.json())
.then(data => {
const container = document.getElementById('data-container');
data.forEach(item => {
const div = document.createElement('div');
div.className = 'item';
div.innerHTML = `
<h2>${item.title}</h2>
<img src="images/${item.image}" alt="${item.title}">
<p>${item.description}</p>
`;
container.appendChild(div);
});
})
.catch(error => console.error('Error fetching data:', error));
Conclusion
You have successfully set up a simple website that displays data from a JSON file. By following these steps, you learned how to structure your project, create HTML, CSS, and JavaScript files, and fetch JSON data dynamically.
Next, consider enhancing your website with additional features, such as user interaction or more complex data handling. Happy coding!