[英]How do i pull out certain data from this json response?
Here is the link im opening in python: 这是在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! 提前致谢!
Your result object returned from json.loads will be a dictionary, so you can print the value like so: 从json.loads返回的结果对象将是一个字典,因此您可以像这样打印值:
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: 另请注意,您的urllib调用应为:
response = urllib.urlopen('http://freegeoip.net/json/1.2.3.4').read()
此时,您将能够像使用python对象一样访问它:
result['region_code']
you can use ast.literal_eval: 您可以使用ast.literal_eval:
>>> import ast
>>> my_dict = ast.literal_eval(response.strip())
>>> my_dict['region_name']
'Washington'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.