您的位置:首页 > 编程语言 > Python开发

Python接口自动化--Json数据处理 5

2018-01-25 11:24 603 查看
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可识别的数据类型。
布尔值pythonjson
Truetrue
Falsefalse
# _*_ 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的数据类型
PythonJson
dictobject
list,tuplearray
str,long,floatnumber
Truetrue
Falsefalse
Nonenull
3.decode(Json-->Python)字符串:s = {"success":true}转成字典:j = s.json(),然后可以通过 j["success"]=true来获取字典的相应key的value值Json数据转成python可识别的数据,对应关系如下
JsonPython
objectdict
arraylist
stringunicode
number(int)int,long,
number(real)float
trueTrue
falseFalse
Nonenull
实例:查询快递单号
# _*_ 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'}
#客户 签收人: 邮政收发章 已签收 感谢使用圆通速递,期待再次为您服务

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: