Fetching the data through this API https://restcountries.com/v3.1/name/portugal. For couple of fields i.e flag,name,currency getting [object object]
XMLHTTPRequest
const request = new XMLHttpRequest();
// Here we need URL for AJAX calls
//request is an object
// Type of Request - GET
request.open('GET','https://restcountries.com/v3.1/name/portugal');
// open the request
//we have to send this request to the url to fetch the data
request.send();
//We need request call back on the load. callback function
request.addEventListener('load',function() {
// converting json file to normal text.
const [data] = JSON.parse(this.responseText);
console.log(data);
const html=`
<article class="country">
<img class="country__img" src="${data.flags}"/>
console.log(data.flags);
<div class="country__data">
<h3 class="country__name">${data.name}</h3>
<h4 class="country__region">${data.region}</h4>
<p class="country__row"><span>๐ซ</span>${data.population}</p>
<p class="country__row"><span>๐ฃ๏ธ</span>${data.languages}</p>
<p class="country__row"><span>๐ฐ</span>${data.currencies}</p>
</div>
</article>
`;
For Flag image getting Cannot GET /[object%20Object] other fields too [object%20Object].
Do i have to use JSON.stringify?
Any help appreciated.
Thanks, Ajeet
I think you need to do this:
const data = JSON.parse(this.responseText);
console.log(data);
console.log(data[0].population); etc
ie remove the square brackets from const [data] and get using index 0
The data.flags property you are using for src attribute is an object itself, not a simple URL, since it contains URLs for png and svg formats.
Try to pass data.flags.png or data.flags.svg for the src attribute and it should work.
You need to use proper notation to get values out from JSON. You can refer below code to get more understandings.
request.addEventListener('load', function () {
// converting json file to normal text.
const [data] = JSON.parse(this.responseText);
console.log(data);
const lang = Object.values(data.languages).join(',');
const currencies = Object.values(data.currencies).map((c) => c.name).join(',');
const html = `
<article class="country">
<img class="country__img" src="${data.flags.png}"/>
<div class="country__data">
<h3 class="country__name">${data.name.common}</h3>
<h4 class="country__region">${data.region}</h4>
<p class="country__row"><span>๐ซ</span>${data.population}</p>
<p class="country__row"><span>๐ฃ๏ธ</span>${lang}</p>
<p class="country__row"><span>๐ฐ</span>${currencies}</p>
</div>
</article>
`;
const divEl = document.createElement('div');
divEl.innerHTML = html;
document.body.appendChild(divEl);
console.log(html);
});