JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。
json.dumps : 将Python对象编码澄JSON字符串
json.loads : 将已编码的JSON字符串解码为Python对象
举例:
import json
# 将python对象编码成为json的字符串格式;
d = {'name': 'fentiao'}
jsonStr = json.dumps(d)
print(jsonStr)
print(type(jsonStr))
l = [1, 2, 3, 4]
jsonLi = json.dumps(l)
print(jsonLi, type(jsonLi))
import json
# 将python对象编码成为json的字符串格式;
d = {'name': 'fentiao'}
jsonStr = json.dumps(d)
# 将获取的json字符串解码为python的对象
pythonDict = json.loads(jsonStr)
print(pythonDict, type(pythonDict))
import json
# 将python对象编码成为json的字符串格式;
d = {'name': 'fentiao'}
jsonStr = json.dumps(d)
# 将python对象编码成为json的字符串格式并写入文件中;
with open('json.txt', 'w') as f:
json.dump(d, f)
import json
# 将python对象编码成为json的字符串格式;
d = {'name': 'fentiao'}
jsonStr = json.dumps(d)
# 将文件中的json字符串解码为python的对象
with open('json.txt') as f:
json_Dict = json.load(f)
print(json_Dict, type(json_Dict))
根据IP查询所在地、运营商等信息的一些API如下:
1. 淘宝的API(推荐):http://ip.taobao.com/service/getIpInfo.php?ip=110.84.0.129
2. 国外freegeoip.net(推荐):http://freegeoip.net/json/110.84.0.129 这个还提供了经纬度信息(但不一定准)
3. 新浪的API:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=110.84.0.129
4. 腾讯的网页查询(返回的非json格式): http://ip.qq.com/cgi-bin/searchip?searchip1=110.84.0.129
5. ip.cn的网页(返回的非json格式):http://www.ip.cn/index.php?ip=110.84.0.129
6. ip-api.com: http://ip-api.com/json/110.84.0.129
上述的API接口,大多有一个特点是, 返回的直接是个json格式;
# ip = input('IP:')
import json
from urllib.request import urlopen
# ip = '8.8.8.8'
ip = input("请输入查询的IP:")
url = "http://ip.taobao.com/service/getIpInfo.php?ip=%s" %(ip)
# 根据url获取网页的内容, 并且解码为utf-8格式, 识别中文;
text = urlopen(url).read().decode('utf-8')
# print(text)
# print(type(text))
# 将获取的字符串类型转换为字典, 方便处理
d = json.loads(text)['data']
country = d['country']
city = d['city']
print(country, city)