Requests方法 --- json模塊


1、Json 簡介:Json,全名 JavaScript Object Notation,是一種輕量級的數據交換格式,常用於 http 請求中

2、可以用 help(json),查看對應的源碼注釋內容

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"]'

3、Encode (python->json )
a、首先說下為什么要encode,python里面bool值是True和False,json里面bool值是true和 false,並且區分大小寫,這就尷尬了,明明都是 bool 值。
在python里面寫的代碼,傳到json里,肯定識別不了,所以需要把python的代碼經過encode后成為 json 可識別的數據類型。
b、舉個簡單例子,下圖中 dict 類型經過 json.dumps()后變成 str,True 變成了 true,False變成了 fasle
c、以下對應關系表是從 json 模塊的源碼里面爬出來的.python 的數據類,經過 encode 成
json 的數據類型,對應的表如下
| | Python | JSON |
| +===================+===============+
| | dict | object |
| +-------------- -----+---------------+
| | list, tuple | array |
| +-------------------+---------------+
| | str, unicode | string |
| +-------------------+---------------+
| | int, long, float | number |
| +-------------------+---------------+
| | True | true |
| +-------------------+---------------+
| | False | false |
| +-------------------+---------------+
| | None | null |
| +-------------------+---------------+

 

4、 decode(json->python)

a、以Requests方法 -- session方法 為例:{"success":true}為例,我們其實最想知道的是 success 這個字段返回的是 True 還是 False
b、如果以 content 字節輸出,返回的是一個字符串:{"success":true},這樣獲取后面那個結果就不方便了
c、如果經過 json 解碼后,返回的就是一個字典:{u'success': True},這樣獲取后面那個結果,就用字典的方式去取值:result2["success"]
d、同樣 json 數據轉化成 python 可識別的數據,對應的表關系如下
| +---------------+-------------------+
| | JSON | Python |
| +===============+===================+
| | object | dict |
| +---------------+-------------------+
| | array | list |
| +---------------+-------------------+
| | string | unicode |
| +---------------+-------------------+
| | number (int) | int, long |
| +---------------+-------------------+
| | number (real) | float |
| +---------------+-------------------+
| | true |
True |
| +---------------+-------------------+
| | false | False |
| +---------------+-------------------+
| | null |
None |
| +---------------+-------------------+

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM