[
{
"name": {
"first": "Laurence",
"last": "Svekis"
},
"age": 40,
"location": {
"city": "Toronto",
"country": "Canada"
}
},
{
"name": {
"first": "Lisa",
"last": "Suekis"
},
"age": 30,
"location": {
"city": "New York",
"country": "USA"
}
},
{
"name": {
"first": "Johyn",
"last": "Sekis"
},
"age": 50,
"location": {
"city": "New York",
"country": "USA"
}
}
]<!DOCTYPE html>
<html>
<head>
<title>JavaScript JSON</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Potta+One&display=swap');
body{
font-family: 'Potta One', cursive;
}
.output{
font-size: 1.2em;
width:80%;
margin:auto;
padding:10px;
}
</style>
</head>
<body>
<h1>JSON</h1>
<input type="text" class="val">
<button class="btn">Click</button>
<div class="output"></div>
<script src="app1.js"></script>
</body>
</html>const url = 'https://www.discoveryvip.com/shared/test1.json';
const localUrl = 'people.json';
const btn = document.querySelector('.btn');
const output = document.querySelector('.output');
const inputVal = document.querySelector('.val');
let attemptCounter = false;
inputVal.style.display = 'none';
btn.textContent = 'Load JSON data';
btn.addEventListener('click',(e)=>{
getData(url);
})
function getData(urlPath){
fetch(urlPath).then(rep => {
return rep.json()
}).then((json)=>{
maker(json);
}).catch(err=>{
if(!attemptCounter){
getData(localUrl);
}
attemptCounter = true;
console.log(err);
})
}
function maker(data){
output.innerHTML = '<h1>JSON Data</h1>';
data.forEach((el,index) => {
console.log(index%2);
const bg = index%2 == 0 ? '#eee' : '#fff';
//${JSON.stringify(el)}
const div = document.createElement('div');
div.style.backgroundColor = bg;
div.innerHTML += `<div>${el.name.first} ${el.name.last}</div>`;
div.innerHTML += `<div>${el.location.city} ${el.location.country}</div>`;
div.innerHTML += `<div>${el.age} </div>`;
output.append(div);
});
}