javascriptarraysjsonajaxgeotargetting

Convert country code to country full names


I am using the ipinfo.io library to check the user's country and everything is working fine.

I am using this code to pull the data

$.get("https://ipinfo.io?token=0000000000", function(response) {
    console.log(response.ip, response.country);
   }, "jsonp")

I read in the https://ipinfo.io/developers/full-country-names that i can use the full country names json file but i have no idea how to map it together don't even know where to start. Any advice here?

thanks!


Solution

  • One way would be to store that names.json file locally in your project environment. Then you can check if the country code is a key of that object literal. If found, you can print that value.

    Something like this:

    var countries = {"BD": "Bangladesh", "BE": "Belgium", "BF": "Burkina Faso"}; // your json object names.json
    var foundCountryCode = "BE"; // the country code you found
    var countryName = countries[foundCountryCode]; // here you get the name
    console.log(countryName); // do stuff