1.Json模塊簡介,全名JavaScript Object Notation,輕量級的數據交換格式,經常使用於http請求中。html
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
布爾值 | 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的數據類型ajax
Python | Json |
dict | object |
list,tuple | array |
str,long,float | number |
True | true |
False | false |
None | null |
3.decode(Json-->Python)json
字符串:s = {"success":true}url
轉成字典:j = s.json(),而後能夠經過 j["success"]=true來獲取字典的相應key的value值spa
Json數據轉成python可識別的數據,對應關係以下3d
Json | Python |
object | dict |
array | list |
string | unicode |
number(int) | int,long, |
number(real) | float |
true | True |
false | False |
None | null |
實例:查詢快遞單號code
# _*_ 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'}
#客戶 簽收人: 郵政收發章 已簽收 感謝使用圓通速遞,期待再次爲您服務