user4530588
user4530588

Reputation:

How do i pull out certain data from this json response?

Here is the link im opening in python:

response = urllib.request.urlopen('http://freegeoip.net/json/1.2.3.4').read()

print(response)

After printing the response it gives the result:

b'{"ip":"1.2.3.4","country_code":"US","country_name":"United States","region_code":"WA","region_name":"Washington","city":"Mukilteo","zip_code":"98275","time_zone":"America/Los_Angeles","latitude":47.913,"longitude":-122.305,"metro_code":819}\n'

My question is, how can i print just the region name? i have this code so far:

import json
import urllib.request
response = urllib.request.urlopen('http://freegeoip.net/json/1.2.3.4').read()
print(response)
result = json.loads(response.decode('utf8'))

Its the last bit of pulling out the specific piece of data im stuck on. Thanks in advance!

Upvotes: 2

Views: 213

Answers (3)

Hackaholic
Hackaholic

Reputation: 19733

you can use ast.literal_eval:

>>> import ast
>>> my_dict = ast.literal_eval(response.strip())
>>> my_dict['region_name']
'Washington'

Upvotes: 0

jimjkelly
jimjkelly

Reputation: 1651

Your result object returned from json.loads will be a dictionary, so you can print the value like so:

print result['region_name']

Or even better, a bit more defensively, in the event that key doesn't exist:

print result.get('region_name', 'No region specified')

Also note that your urllib call should be:

response = urllib.urlopen('http://freegeoip.net/json/1.2.3.4').read()

Upvotes: 3

Ryan O'Donnell
Ryan O'Donnell

Reputation: 617

At this point, you'd be able to access it as you would a python object:

result['region_code']

Upvotes: 1

Related Questions