JSON 이해하기

Json and Ajax Example

Object

var myCat = {
‘name’ : ‘Meowsalot’,
‘species’ : ‘cat’,
‘favoriteFood’: ‘tuna’
}
// myCat.name : Meowsalot
// myCat.species : tuna

Array

var myFavColors = [‘blue’, ‘green’, ‘purple’];
// myFavColors[1] : green

Arrays + Objects

var thePets = [
{
'name' : 'Meowsalot',
'species' : 'cat',
'favoriteFood': 'tuna'
},
{
'name' : 'Barky',
'species' : 'dog',
'favoriteFood': 'carrots'
}
]
// thePets[1].favoriteFood : carrots

Json and Ajax

.title {font-size:1.4em; font-weight:normal; display: inline-block;}
.wrap {margin: 1em;}
.hide {visibility: hidden; opacity: 0; transform:scale(.75);}
.btn {position:relative; outline:none; cursor: pointer; background-color: #046380; color:#fff; border:0; margin-left: 1em; padding: 5px 10px; border-radius: 4px; transition: opacity .4s ease-out, transform .4s ease-out, visibility .4s ease-out;}
.btn:active {background-color: #034154; left:2px; top: 2px;}
p {padding: 4px 0 2px 8px; line-height: 1.7; border-bottom: 1px solid #ddd;}
const animalContainer = document.getElementById('animal-info');
const btn = document.getElementById('btn');
let pageCounter = 1;
btn.addEventListener('click', function() {
const ourRequest = new XMLHttpRequest();
//GET : Download Data, Post: Send Data
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequest.onload = function() {
//console.log(ourRequest.responseText);
//the first item in the array
//console.log(ourData[0]);
if (ourRequest.status >= 200 && ourRequest.status < 400) { 
const ourData = JSON.parse(ourRequest.responseText); 
renderHTML(ourData); 
} else { 
console.log('We connected to the server, btn it returned an error.'); 
} 
}; 
ourRequest.onerror = function() { 
console.log('Connect error') }; 
ourRequest.send(); 
pageCounter++; 
if (pageCounter > 3) {
btn.classList.add('hide')
}
});
const renderHTML = function(data) {
let htmlString = '';
for (i = 0; i < data.length; i++) {
htmlString += `
${data[i].name} is a ${data[i].species} that likes to eat `;
for (j = 0; j < data[i].foods.likes.length; j++) {
if (j === 0) {
htmlString += data[i].foods.likes[j];
} else {
htmlString += ` and ${data[i].foods.likes[j]}`
}
}
htmlString += ` and dislikes `;
for (j = 0; j < data[i].foods.dislikes.length; j++) {
if (j === 0) {
htmlString += data[i].foods.dislikes[j];
} else {
htmlString += ` and ${data[i].foods.dislikes[j]}`
}
}
htmlString += `.
`
}
animalContainer.insertAdjacentHTML('beforeend', htmlString);
}