fetch() from url, cant access object, console.log() works

Viewed 103

I have the 3 following lines of code:

const response = await fetch(`https://restcountries.com/v3/alpha/${countrycode}`);
let json = await response.json();
console.log("this is my json file: ", json.borders)

The problem is, when I do this I receive in my console log undefined but I want to access the 'borders' property of the object. On the other side, if I change the third line into this:

console.log("this is my json file: ", json)

I get the full object which looks like this:

{"altSpellings": ["DE", "Federal Republic of Germany", "Bundesrepublik Deutschland"], "area": 357114, "borders": ["AUT", "BEL", "CZE", "DNK", "FRA", "LUX", "NLD", "POL", "CHE"], "capital": ["Berlin"], "cca2": "DE", "cca3": "DEU", "ccn3": "276", "cioc": "GER", "currencies": {"EUR": [Object]}, "demonyms": {"eng": [Object], "fra": [Object]}, "flag": "", "flags": ["https://restcountries.com/data/deu.svg", "https://restcountries.com/data/png/deu.png"], "idd": {"root": "+4", "suffixes": [Array]}, "independent": true, "landlocked": false, "languages": {"deu": "German"}, "latlng": [51, 9], "name": {"common": "Germany", "nativeName": [Object], "official": "Federal Republic of Germany"}, "region": "Europe", "status": "officially-assigned", "subregion": "Western Europe", "tld": [".de"], "translations": {"ces": [Object], "deu": [Object], "est": [Object], "fin": [Object], "fra": [Object], "hrv": [Object], "hun": [Object], "ita": [Object], "jpn": [Object], "kor": [Object], "nld": [Object], "per": [Object], "pol": [Object], "por": [Object], "rus": [Object], "slk": [Object], "spa": [Object], "swe": [Object], "urd": [Object], "zho": [Object]}, "unMember": true}

What can I do to be able to access all those values, or just like in my example the 'borders' , what am I doing wrong here?

1 Answers

The response is an Array, not an Object. Change the 3rd line to this to access the property.

    console.log("this is my json file: ", json[0].borders)
Related