一 json模块
json是一种轻量级的数据交换格式。json的数据格式其实就是python里面的字典格式,里面可以包含方括号括起来的数组,也就是python里面的列表
1.将python对象编码成为json的字符串格式:json.dumps()
2.将获取的json字符串解码为python的对象:json.loads()
3.将python对象编码成为json的字符串格式并写入文件中
import json
d={'name':'fentiao'}
with open('json.txt','w') as f:
json.dump(d,f)
4.将文件中的json字符串解码为python的对象
import json
with open('json.txt','w') as f:
json_Dict=json.load(f)
print(json_Dict,type(json_Dict))
二 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=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)