0

I'm trying to get the region_code from freegeoip using...

$.getJSON('http://freegeoip.net/json/', function(location) {
console.log(location);

It returns an object as follows...

city: "Medford"
country_code: "US"
country_name: "United States"
ip: "69.142.34.172"
latitude: 39.8741
longitude: -74.809
metro_code: 504
region_code: "NJ"
region_name: "New Jersey"
time_zone: "America/New_York"
zip_code: "08055"

I need to get the region_code and if it is "NJ", do a redirect to a different URL?

I tried this...

var t = JSON.parse('{"city": "", "country_code": "", "country_name": "", "ip": "", "latitude": "", "longitude": "", "metro_code": "", "region_code": "", "region_name": "", "time_zone": "", "zip_code": ""}'); console.log(t['region_code']);

But saw nothing in the console.

webguy
  • 664
  • 10
  • 27
  • 3
    "I tried this" — Why did you try ignoring the data you were getting, constructing some new JSON with no data in it, parsing that JSON and then reading the value you already set to an empty string? Why not use the data you were getting back from the HTTP request? – Quentin Apr 03 '17 at 15:13
  • Well done for trying something first before asking, but it seems you've not investigated the right problem, and have logged a blank property which you made... – evolutionxbox Apr 03 '17 at 15:17
  • I assumed that even though I was getting a JSON, I still needed to parse it to get the value of the key I need. So if I'm getting a valid JSON, how can I get the value of one of the keys? As to what I was trying, I was following advice from a SO post [link](http://stackoverflow.com/questions/18910939/how-to-get-json-key-and-value-in-javascript) – webguy Apr 03 '17 at 18:42

1 Answers1

1

Try this...

$.getJSON('http://freegeoip.net/json/', function(location) {
    if (location.region_code == "NJ") {
        window.location.href = "anotherPage.html";
    }
});

Assuming the data you've show is what is returned then this will do what you need.

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67