python中json.loads和json.dumps對比理解
阿新 • • 發佈:2019-02-15
json.loads和json.dumps最近經常用到,就稍微整理了下二者的關係和區別。
一開始用到的時候是把json.loads理解為把json字串轉換為python物件;而json.dumps是把python物件轉換為json字串的。這麼理解感覺就挺合適的,為了加深理解,下面再進一步來剖析二者。
看一下json.loads和json.dumps原始碼中的註釋。
"""Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object. If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to ``unicode`` first.
"""Serialize ``obj`` to a JSON formatted ``str``.
二者分別是序列化和反序列化的兩個作用。
先說一下什麼是序列化和反序列化。
把物件轉換為位元組序列的過程成為物件的序列化;把位元組序列恢復為物件的過程稱為物件的反序列化。
在使用序列化的時候,通常有兩個場景:
1)、把物件的位元組序列儲存在硬碟上,通常存放在一個檔案中。就像打單機遊戲時,現在多少級多少裝備然後進行存檔一樣。
2)、在網路上傳送物件的位元組序列時,就要先把物件進行序列化操作,接受端接收後再進行反序列化。
舉個例子:
下面程式碼是通過新浪介面獲取期貨資料。
class SinaDemo(object): def __init__(self): super(SinaDemo, self).__init__() def getData(self): id = 'rb1901' url = 'http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesMiniKLine5m?symbol='+ id req = urllib2.Request(url) rsp = urllib2.urlopen(req) res = rsp.read() res_json = json.loads(res) print res print res_json if __name__ == '__main__': sd = SinaDemo() sd.getData()
返回的結果是:
[["2018-02-09 23:00:00","3681.000","3683.000","3680.000","3680.000","32"]]
[[u'2018-02-09 23:00:00', u'3681.000', u'3683.000', u'3680.000', u'3680.000', u'32']]
res是一個json資料,陣列中的元素都是str,其中根據註釋只要是str或者unicode編碼的例項都可以被反序列化為python物件。
經過json.loads()後得到的每個元素都是python字元物件了。前面的u是宣告是unicode編碼。
json.dumps()的作用正好相反。
def sendData(self): dict = {'size':10, 'length':10.0, 'color':'blue'} json_dict = json.dumps(dict) print dict print json_dict
{'color': 'blue', 'length': 10.0, 'size': 10}
{"color": "blue", "length": 10.0, "size": 10}
將python中的dict序列化為了json格式的字串。