0

I am writing code to obtain geolocation information using the IP Geolocation API. I used the following code in my jupyter notebook...

try:
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen

ip = '8.8.8.8'
api_key = 'your_api_key'
api_url = 'https://geo.ipify.org/api/v1?'

url = api_url + 'apiKey=' + api_key + '&ipAddress=' + ip
result = urlopen(url).read().decode('utf8')
print(result)

I got the following result, but it returns the following string...

'{"ip":"8.8.8.8","location":{"country":"US","region":"California","city":"Mountain View","lat":37.4223,"lng":-122.085,"postalCode":"94043","timezone":"-07:00","geonameId":5375480},"domains":["0--9.ru","000.lyxhwy.xyz","000180.top","00049ok.com","001998.com.he2.aqb.so"],"as":{"asn":15169,"name":"Google LLC","route":"8.8.8.0\\/24","domain":"https:\\/\\/about.google\\/intl\\/en\\/","type":"Content"},"isp":"Google LLC"}'

I am trying to remove the strings at the beginning and end. I tried changing this string to a list by calling the list function on the result variable but that didn't work. I would like to obtain the following output...

{"ip":"8.8.8.8","location":{"country":"US","region":"California","city":"Mountain View","lat":37.4223,"lng":-122.085,"postalCode":"94043","timezone":"-07:00","geonameId":5375480},"domains":["0--9.ru","000.lyxhwy.xyz","000180.top","00049ok.com","001998.com.he2.aqb.so"],"as":{"asn":15169,"name":"Google LLC","route":"8.8.8.0\\/24","domain":"https:\\/\\/about.google\\/intl\\/en\\/","type":"Content"},"isp":"Google LLC"}

By doing this, I will get a dictionary which I can work with using the various keys. Any help will be greatly appreciated.

  • Those `'` aren't in the string; those quotes are indicating that the whole thing is a string. This question is similar to asking how you remove the `[]` from the list `[1, 2, 3]`. You need to *parse* the string as a dictionary. – Carcigenicate Aug 05 '20 at 15:51
  • Yes it does, thank you! – Slwd-wave540 Aug 05 '20 at 16:06

2 Answers2

1

If you want a dictionary, you shouldn't try to remove the quotes, that is there because it denotes a string variable. You should instead use JSON as this is a valid JSON string:

import json
try:
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen

ip = '8.8.8.8'
api_key = 'your_api_key'
api_url = 'https://geo.ipify.org/api/v1?'

url = api_url + 'apiKey=' + api_key + '&ipAddress=' + ip

result = json.loads(urlopen(url).read().decode('utf8'))
print(result)

This will give you the dictionary you are looking for.

M Z
  • 4,571
  • 2
  • 13
  • 27
1

You can use json library.

import json
str = '{"ip": "8.8.8.8"}'
res = json.loads(str)
print(res)

Result will be a dict.

enesdemirag
  • 325
  • 1
  • 10