前言
有些post的請求參數是json格式的,需要導入json模塊進行處理,json是一種數據交換格式,獨立於編程語言
一般常見的接口返回數據也是json格式的,我們在做判斷的時候,往往只需要提取其中幾個關鍵的參數就行,這時候就需要json來解析返回的數據了
一、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('\u1234'))
"\u1234"
>>> print(json.dumps('\\'))
"\\"
>>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
{"a": 0, "b": 0, "c": 0}
>>> from io import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'
二、encode(python ---> json)
1.首先說下為什么要 encode?
python 里面 bool 值是 True 和 False ,
json 里面 bool 值是 true 和 false ,
注意區分大小寫!!! 在 python 里面寫的代碼,傳到json里,肯定識別不了,所以需要把 python 的代碼經過 encode 后成為 json 可識別的數據類型
2.舉個簡單例子,下圖中 dict 類型經過 json.dumps() 后變成 str,True 變成了 true,False 變成了 fasle
注:查看數據類型用 type 函數
3.以下對應關系表是從 json 模塊的源碼里面爬出來的 .python 的數據類,經過 encode 成 json 的數據類型,對應的表如下:
| | Python | JSON |
| +-------------------+---------------+
| +-------------------+---------------+
| | dict | object |
| +-------------------+---------------+
| | list, tuple | array |
| +-------------------+---------------+
| | str, unicode | string |
| +-------------------+---------------+
| | int, long, float | number |
| +-------------------+---------------+
| | True | true |
| +-------------------+---------------+
| | False | false |
| +-------------------+---------------+
| | None | null |
| +-------------------+---------------+
三、decode(json ---> python)
1.轉換操作詳見代碼:
#conding:utf-8
import requests
import json
d = {
"a": None, "b": True, "c": False, "d": "JODIE", "e": ["1",11], "f": ("1r",27), "g": {"h": 3, "i": "17", "j": True}
}
print(type(d))
dict_json = json.dumps(d) #字典轉json
print(type(dict_json))
print(dict_json)
print("--------------------------------------")
json_dict = json.loads(dict_json) #json 轉字典
print(type(json_dict))
print(json_dict)
運行后的結果:
2.同樣json數據轉化成python可識別的數據,對應的表關系如下
| | JSON | Python |
| +-------------------+---------------+
| +-------------------+---------------+
| | object | dict |
| +-------------------+---------------+
| | array | list |
| +-------------------+---------------+
| | string | unicode |
| +-------------------+---------------+
| | number (int) | int, long |
| +-------------------+---------------+
| | number (real) | float |
| +-------------------+---------------+
| | true | True |
| +-------------------+---------------+
| | false | False |
| +-------------------+---------------+
| | null | None |
| +-------------------+---------------+