i am new to javascript and am not sure how to read data from json file using javascript.
i have data like below in my json file located in path api/data.json
{
"description": " description",
"data": [
{
"id": "1",
"title": "first_data_title",
"items": [
{
"id": 1,
"title": "item1_title"
},
{
"id": 2,
"title": "item2_title",
},
{
"id": 3,
"title": "item3_title",
}
]
},
{
"id": "2",
"title": "second_data_title",
"items": [
{
"id": 4,
"title": "item4_title"
}
{
"id": 5,
"title": "item5_title"
}
]
},
{
"id": "3",
"title": "third_data_title",
"items": [
{
"id": 6,
"title": "item6_title",
},
]
}
]
}
as seen from above data is an array of objects where each data has array of items.
now i want to display each data with its title and its items title in a list. meaning like below,
[![enter image description here][1]][1]
on loading the application
my code is like below,
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="src/styles.css">
<script src="src/scripts.js"></script>
</head>
<body>
<h2>page loaded</h2>
</body>
</html>
in scripts.js
function onload() {
console.log('onload');
//how to fetch data from data.json file and display it as in the
//picture
}
window.onload = onload;
could someone help me with this. thanks.
EDIT:
tried like below
i am trying something like this
function onload() {
console.log('onload');
fetch('api/data.json')
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(json => {
const data = json;
console.log(data);
})
}
this gives unexpected token error. i think the problem is using .then
so i tried using async method
async function onload() {
const data = await fetch('api/data.json');
console.log('data', data);
}
this gives the regeneratorRuntime not defined error.
i have tried to do like below
functio onload() {
fetch('api/data.json)
.then((response) => {
console.log('res', response.json);
return response.json();
})
}
and this logs error and log statement in console like below
below is how the files are structured and i am trying to just read json data from data.json file located in api folder.