一 json模块
json是一种轻量级的数据交换格式。json的数据格式其实就是python里面的字典格式,里面可以包含方括号括起来的数组,也就是python里面的列表
1) dumps方法:将python对象编码成为json的字符串格式
import json
# 将python对象编码成为json的字符串格式;
d = {'name': 'fentiao'}
jsonStr = json.dumps(d)
print(jsonStr)
print(type(jsonStr))
2) dump方法:将python对象编码成为json的字符串格式并写入文件中
d = {'name': 'fentiao'}
# 将python对象编码成为json的字符串格式并写入文件中;
with open('json.txt', 'w') as f:
json.dump(d, f)
3) loads方法:将获取的json字符串解码为python的对象
d = {'name': 'fentiao'}
jsonStr = json.dumps(d)
# 将获取的json字符串解码为python的对象
pythonDict = json.loads(jsonStr)
print(pythonDict, type(pythonDict))
4) load方法:将文件中的json字符串解码为python的对象
# 将文件中的json字符串解码为python的对象
with open('json.txt') as f:
json_Dict = json.load(f)
print(json_Dict, type(json_Dict))
5)总结:
json序列化方法:
dumps:无文件操作 dump:序列化+写入文件
json反序列化方法:
loads:无文件操作 load: 读文件+反序列化
二 json模块的应用
利用dump方法以指定的格式写入数据
import json
import string
from random import choice
keys = string.ascii_lowercase
values = string.ascii_letters + string.digits
dict = {choice(keys): choice(values) for i in range(100)}
with open('json.txt', 'w') as f:
# separators = ("每个元素间的分隔符", “key和value之间的分隔符”)
json.dump(dict, f, indent=4, sort_keys=True, separators=(';', '='))
三 利用json处理获取IP对应的地理位置
网上有很多API接口, 有的可以直接返回json格式的数据,这样就可以通过json模块对数据进行处理了
如果直接查看API接口的话,返回的其结果为:
这里需要得到相应的地理位置
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)
利用json模块对其进行处理,得到相应的地理位置