Python接口自动化--Json数据处理 5
1.Json模块简介,全名JavaScript Object Notation,轻量级的数据交换格式,常用于http请求中。
Encoding basic Python object hierarchies::
>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print json.dumps("\"foo\bar")
"\"foo\bar"
>>> print json.dumps(u'\u1234')
"\u1234"
>>> print json.dumps('\\')
"\\"
>>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
{"a": 0, "b": 0, "c": 0}
>>> from StringIO import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'
2.Encode(python->Json),在python和json中的bool值,不同,如下图,所以不转换的话,会报错,所以需要把python的代码经过encode后成为json可识别的数据类型。
布尔值 | python | json |
真 | True | true |
假 | False | false |
# _*_ encoding:utf-8 _*_ import requests import json #python的字典 payload = {"cye":True, "json":False, "python":"22137284235",} print (type(payload)) #输出 # <type 'dict'> #转化成json格式 data_json = json.dumps(payload) print (type(data_json)) #输出 # <type 'str'> print (data_json) # 输出 # {"python": "22137284235", "json": false, "cye": true}
Python经过encode成Json的数据类型
Python | Json |
dict | object |
list,tuple | array |
str,long,float | number |
True | true |
False | false |
None | null |
3.decode(Json-->Python)
字符串:s = {"success":true}
转成字典:j = s.json(),然后可以通过 j["success"]=true来获取字典的相应key的value值
Json数据转成python可识别的数据,对应关系如下
Json | Python |
object | dict |
array | list |
string | unicode |
number(int) | int,long, |
number(real) | float |
true | True |
false | False |
None | null |
实例:查询快递单号
# _*_ coding:utf-8 _*_ import requests import json id = 8881************* url = "http://www.kuaidi.com/index-ajaxselectcourierinfo-%s-yuantong.html"%id # print (url) head = {"Connection": "keep-alive", "X-Requested-With": "XMLHttpRequest", "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6"} r = requests.get(url=url,headers=head,verify=True) j = r.json() data = j["data"] print (data[0]) print (data[0]["context"])
#输出结果
#{u'context': u'\u5ba2\u6237 \u7b7e\u6536\u4eba: \u90ae\u653f\u6536\u53d1\u7ae0 \u5df2\u7b7e\u6536 \u611f\u8c22\u4f7f\u7528\u5706\u901a\u901f\u9012\uff0c\u671f\u5f85\u518d\u6b21\u4e3a\u60a8\u670d\u52a1', u'time': u'2018-01-22 15:43:23'}
#客户 签收人: 邮政收发章 已签收 感谢使用圆通速递,期待再次为您服务